omnicell-router 0.1.0 → 0.2.0

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 (212) hide show
  1. package/RELEASING.md +238 -238
  2. package/RELEASING.zh-CN.md +230 -230
  3. package/backend/dist/capture/recorder.js +2 -1
  4. package/backend/dist/cli/clients/base.js +8 -16
  5. package/backend/dist/cli/clients/dsh.js +8 -16
  6. package/backend/dist/cli/clients/pi.js +16 -9
  7. package/backend/dist/cli/types.d.ts +5 -0
  8. package/backend/dist/config/env.js +2 -1
  9. package/backend/dist/config/index.js +2 -0
  10. package/backend/dist/config/types.d.ts +23 -0
  11. package/backend/dist/harness/adapters/amp.d.ts +2 -0
  12. package/backend/dist/harness/adapters/amp.js +7 -0
  13. package/backend/dist/harness/adapters/claude.d.ts +2 -0
  14. package/backend/dist/harness/adapters/claude.js +7 -0
  15. package/backend/dist/harness/adapters/cline.d.ts +2 -0
  16. package/backend/dist/harness/adapters/cline.js +6 -0
  17. package/backend/dist/harness/adapters/codex.d.ts +2 -0
  18. package/backend/dist/harness/adapters/codex.js +6 -0
  19. package/backend/dist/harness/adapters/cursor.d.ts +5 -0
  20. package/backend/dist/harness/adapters/cursor.js +10 -0
  21. package/backend/dist/harness/adapters/declarative.d.ts +62 -0
  22. package/backend/dist/harness/adapters/declarative.js +202 -0
  23. package/backend/dist/harness/adapters/dsh.d.ts +5 -0
  24. package/backend/dist/harness/adapters/dsh.js +6 -0
  25. package/backend/dist/harness/adapters/gemini-cli.d.ts +2 -0
  26. package/backend/dist/harness/adapters/gemini-cli.js +7 -0
  27. package/backend/dist/harness/adapters/github-copilot.d.ts +5 -0
  28. package/backend/dist/harness/adapters/github-copilot.js +10 -0
  29. package/backend/dist/harness/adapters/index.d.ts +44 -0
  30. package/backend/dist/harness/adapters/index.js +99 -0
  31. package/backend/dist/harness/adapters/opencode.d.ts +2 -0
  32. package/backend/dist/harness/adapters/opencode.js +55 -0
  33. package/backend/dist/harness/adapters/pi.d.ts +1 -0
  34. package/backend/dist/harness/adapters/pi.js +22 -0
  35. package/backend/dist/harness/adapters/skills-paths.d.ts +15 -0
  36. package/backend/dist/harness/adapters/skills-paths.js +17 -0
  37. package/backend/dist/harness/adapters/types.d.ts +174 -0
  38. package/backend/dist/harness/adapters/types.js +12 -0
  39. package/backend/dist/harness/adapters/universal.d.ts +6 -0
  40. package/backend/dist/harness/adapters/universal.js +10 -0
  41. package/backend/dist/harness/adapters/windsurf.d.ts +2 -0
  42. package/backend/dist/harness/adapters/windsurf.js +10 -0
  43. package/backend/dist/harness/adapters/zed.d.ts +2 -0
  44. package/backend/dist/harness/adapters/zed.js +6 -0
  45. package/backend/dist/harness/awesome-opencode.d.ts +40 -0
  46. package/backend/dist/harness/awesome-opencode.js +75 -0
  47. package/backend/dist/harness/browse.d.ts +202 -0
  48. package/backend/dist/harness/browse.js +1214 -0
  49. package/backend/dist/harness/catalog-npm.d.ts +59 -0
  50. package/backend/dist/harness/catalog-npm.js +145 -0
  51. package/backend/dist/harness/clawhub.d.ts +212 -0
  52. package/backend/dist/harness/clawhub.js +426 -0
  53. package/backend/dist/harness/config-file.d.ts +29 -0
  54. package/backend/dist/harness/config-file.js +35 -0
  55. package/backend/dist/harness/detail.d.ts +74 -0
  56. package/backend/dist/harness/detail.js +330 -0
  57. package/backend/dist/harness/discover.d.ts +118 -0
  58. package/backend/dist/harness/discover.js +507 -0
  59. package/backend/dist/harness/drift.d.ts +21 -0
  60. package/backend/dist/harness/drift.js +25 -0
  61. package/backend/dist/harness/hash.d.ts +10 -0
  62. package/backend/dist/harness/hash.js +63 -0
  63. package/backend/dist/harness/hosts.d.ts +18 -0
  64. package/backend/dist/harness/hosts.js +15 -0
  65. package/backend/dist/harness/install.d.ts +88 -0
  66. package/backend/dist/harness/install.js +301 -0
  67. package/backend/dist/harness/inventory.d.ts +10 -0
  68. package/backend/dist/harness/inventory.js +198 -0
  69. package/backend/dist/harness/ledger.d.ts +39 -0
  70. package/backend/dist/harness/ledger.js +83 -0
  71. package/backend/dist/harness/maintenance.d.ts +115 -0
  72. package/backend/dist/harness/maintenance.js +603 -0
  73. package/backend/dist/harness/manifest.d.ts +31 -0
  74. package/backend/dist/harness/manifest.js +234 -0
  75. package/backend/dist/harness/net.d.ts +86 -0
  76. package/backend/dist/harness/net.js +113 -0
  77. package/backend/dist/harness/opencode-cafe.d.ts +40 -0
  78. package/backend/dist/harness/opencode-cafe.js +85 -0
  79. package/backend/dist/harness/opencode-ecosystem.d.ts +34 -0
  80. package/backend/dist/harness/opencode-ecosystem.js +246 -0
  81. package/backend/dist/harness/pi-dev.d.ts +81 -0
  82. package/backend/dist/harness/pi-dev.js +187 -0
  83. package/backend/dist/harness/probe.d.ts +33 -0
  84. package/backend/dist/harness/probe.js +85 -0
  85. package/backend/dist/harness/registry.d.ts +2 -0
  86. package/backend/dist/harness/registry.js +26 -0
  87. package/backend/dist/harness/scopes.d.ts +21 -0
  88. package/backend/dist/harness/scopes.js +22 -0
  89. package/backend/dist/harness/skill-md.d.ts +18 -0
  90. package/backend/dist/harness/skill-md.js +71 -0
  91. package/backend/dist/harness/skills-sh.d.ts +109 -0
  92. package/backend/dist/harness/skills-sh.js +178 -0
  93. package/backend/dist/harness/smithery.d.ts +64 -0
  94. package/backend/dist/harness/smithery.js +146 -0
  95. package/backend/dist/harness/sources/awesome-opencode.d.ts +11 -0
  96. package/backend/dist/harness/sources/awesome-opencode.js +39 -0
  97. package/backend/dist/harness/sources/clawhub.d.ts +2 -0
  98. package/backend/dist/harness/sources/clawhub.js +83 -0
  99. package/backend/dist/harness/sources/github.d.ts +9 -0
  100. package/backend/dist/harness/sources/github.js +202 -0
  101. package/backend/dist/harness/sources/mcp-official.d.ts +2 -0
  102. package/backend/dist/harness/sources/mcp-official.js +110 -0
  103. package/backend/dist/harness/sources/npm.d.ts +2 -0
  104. package/backend/dist/harness/sources/npm.js +152 -0
  105. package/backend/dist/harness/sources/opencode-cafe.d.ts +11 -0
  106. package/backend/dist/harness/sources/opencode-cafe.js +41 -0
  107. package/backend/dist/harness/sources/smithery.d.ts +2 -0
  108. package/backend/dist/harness/sources/smithery.js +81 -0
  109. package/backend/dist/harness/spi.d.ts +98 -0
  110. package/backend/dist/harness/spi.js +8 -0
  111. package/backend/dist/harness/stars.d.ts +70 -0
  112. package/backend/dist/harness/stars.js +202 -0
  113. package/backend/dist/harness/translation.d.ts +142 -0
  114. package/backend/dist/harness/translation.js +567 -0
  115. package/backend/dist/harness/tree.d.ts +13 -0
  116. package/backend/dist/harness/tree.js +19 -0
  117. package/backend/dist/harness/types.d.ts +286 -0
  118. package/backend/dist/harness/types.js +8 -0
  119. package/backend/dist/harness/writers/extension.d.ts +116 -0
  120. package/backend/dist/harness/writers/extension.js +219 -0
  121. package/backend/dist/harness/writers/mcp.d.ts +72 -0
  122. package/backend/dist/harness/writers/mcp.js +195 -0
  123. package/backend/dist/harness/writers/skill.d.ts +60 -0
  124. package/backend/dist/harness/writers/skill.js +146 -0
  125. package/backend/dist/opencode/agents.d.ts +5 -0
  126. package/backend/dist/opencode/agents.js +10 -1
  127. package/backend/dist/opencode/catalog/cache.js +2 -1
  128. package/backend/dist/opencode/catalog/logos.js +2 -1
  129. package/backend/dist/opencode/catalog/ocr-store.js +2 -1
  130. package/backend/dist/opencode/catalog/overrides-store.js +2 -1
  131. package/backend/dist/opencode/credentials/factory.js +10 -27
  132. package/backend/dist/opencode/credentials/ocr-store.js +2 -1
  133. package/backend/dist/opencode/provider-defs.js +2 -1
  134. package/backend/dist/opencode/user-config.js +8 -16
  135. package/backend/dist/providers/registry.d.ts +15 -4
  136. package/backend/dist/providers/registry.js +29 -5
  137. package/backend/dist/providers/virtual-meta.d.ts +13 -0
  138. package/backend/dist/providers/virtual-meta.js +18 -0
  139. package/backend/dist/quota/store.js +2 -1
  140. package/backend/dist/resilience/breaker-state.js +2 -1
  141. package/backend/dist/resilience/credential-state.js +2 -1
  142. package/backend/dist/routes/console.js +137 -15
  143. package/backend/dist/routes/harness.d.ts +2 -0
  144. package/backend/dist/routes/harness.js +622 -0
  145. package/backend/dist/server.js +4 -0
  146. package/backend/dist/session/session-manager.js +2 -1
  147. package/backend/dist/surfaces/systemone-probe.d.ts +25 -0
  148. package/backend/dist/surfaces/systemone-probe.js +74 -0
  149. package/backend/dist/utils/atomic-write.d.ts +12 -0
  150. package/backend/dist/utils/atomic-write.js +29 -0
  151. package/bin/ocr.js +2 -2
  152. package/frontend/dist/assets/{index-DEo2iAT7.css → index-1o7qI-KJ.css} +1 -1
  153. package/frontend/dist/assets/index-DvXKvNxl.js +962 -0
  154. package/frontend/dist/index.html +2 -2
  155. package/package.json +87 -87
  156. package/backend/dist/budget/budget-manager.d.ts +0 -25
  157. package/backend/dist/budget/budget-manager.js +0 -54
  158. package/backend/dist/config/governance-limits.d.ts +0 -68
  159. package/backend/dist/config/governance-limits.js +0 -261
  160. package/backend/dist/flywheel/collector.d.ts +0 -74
  161. package/backend/dist/flywheel/collector.js +0 -235
  162. package/backend/dist/flywheel/dataset.d.ts +0 -130
  163. package/backend/dist/flywheel/dataset.js +0 -638
  164. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  165. package/backend/dist/flywheel/decision-capture.js +0 -85
  166. package/backend/dist/flywheel/prune.d.ts +0 -133
  167. package/backend/dist/flywheel/prune.js +0 -495
  168. package/backend/dist/flywheel/schema.d.ts +0 -108
  169. package/backend/dist/flywheel/schema.js +0 -117
  170. package/backend/dist/flywheel/trainer.d.ts +0 -84
  171. package/backend/dist/flywheel/trainer.js +0 -198
  172. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  173. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  174. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  175. package/backend/dist/opencode/credentials/push.js +0 -116
  176. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  177. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  178. package/backend/dist/opencode/sync.d.ts +0 -29
  179. package/backend/dist/opencode/sync.js +0 -186
  180. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  181. package/backend/dist/pipeline/account-selection.js +0 -112
  182. package/backend/dist/providers/systemone.d.ts +0 -29
  183. package/backend/dist/providers/systemone.js +0 -170
  184. package/backend/dist/ratelimit/duration.d.ts +0 -24
  185. package/backend/dist/ratelimit/duration.js +0 -43
  186. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  187. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  188. package/backend/dist/ratelimit/index.d.ts +0 -4
  189. package/backend/dist/ratelimit/index.js +0 -4
  190. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  191. package/backend/dist/ratelimit/limiter.js +0 -244
  192. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  193. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  194. package/backend/dist/ratelimit/subject.d.ts +0 -26
  195. package/backend/dist/ratelimit/subject.js +0 -28
  196. package/backend/dist/resilience/account-state.d.ts +0 -84
  197. package/backend/dist/resilience/account-state.js +0 -228
  198. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  199. package/backend/dist/router/layer1-classifier.js +0 -467
  200. package/backend/dist/router/layer2-judge.d.ts +0 -111
  201. package/backend/dist/router/layer2-judge.js +0 -373
  202. package/backend/dist/router/retry-escalation.d.ts +0 -89
  203. package/backend/dist/router/retry-escalation.js +0 -99
  204. package/backend/dist/routes/flywheel.d.ts +0 -3
  205. package/backend/dist/routes/flywheel.js +0 -268
  206. package/backend/dist/routes/systemone.d.ts +0 -3
  207. package/backend/dist/routes/systemone.js +0 -90
  208. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  209. package/backend/dist/surfaces/governance-envelope.js +0 -47
  210. package/backend/dist/utils/token-estimator.d.ts +0 -7
  211. package/backend/dist/utils/token-estimator.js +0 -20
  212. package/frontend/dist/assets/index-nwgWkmU1.js +0 -840
@@ -0,0 +1,426 @@
1
+ /**
2
+ * ClawHub reader (`https://clawhub.ai`) — the public skill registry of OpenClaw, and the one skill
3
+ * registry whose rows install from the registry's OWN store rather than from a GitHub repository.
4
+ *
5
+ * Everything below reads the registry's documented public API (measured 2026-10-25, anonymous):
6
+ * `GET /api/v1/skills?limit=&cursor=&sort=` → 200 `{items: [...], nextCursor}` — cursor-paged
7
+ * whole-catalog listing; `sort` accepts `recommended|updated|createdAt|downloads|stars|…`
8
+ * (the OpenAPI enum; aliases `rating`/`installs`/`newest` are legacy spellings). A page honors
9
+ * the requested `limit` (measured: 100 → 99 rows), so one console page (≤ 50) is one upstream
10
+ * page. `trending` is the one sort the cursor does NOT apply — never declared to the console.
11
+ * `GET /api/v1/search?q=&limit=` → 200 `{results: [...]}` — relevance-ranked whole-catalog search
12
+ * with NO paging parameter (measured: `offset` is ignored, identical first page; the OpenAPI
13
+ * spec declares only `q`/`limit`/filters). One answer is the whole reach of a query, so the
14
+ * console treats it as a window, exactly like skills.sh's search.
15
+ * `GET /api/v1/skills/<slug>?ownerHandle=` → 200 `{skill, latestVersion, metadata, owner,
16
+ * moderation}` — the registry's own record for ONE skill, including `skill.description` (the
17
+ * published `SKILL.md` verbatim, frontmatter and all), `latestVersion.license/createdAt` and the
18
+ * moderation verdict. This is the long-form half a detail dialog renders (`harness/detail.ts`);
19
+ * the row itself still carries only the summary. An `ownerHandle` that owns no such slug answers
20
+ * 404 (measured 2026-10-25), so the parameter doubles as the disambiguator the versions and
21
+ * download endpoints already need.
22
+ * `GET /api/v1/skills/<slug>/versions?limit=&ownerHandle=` → 200 `{items: [{version, …}]}` —
23
+ * semver list, newest first. `ownerHandle` is UNDOCUMENTED on this endpoint but is the
24
+ * parameter the registry's own `409 Ambiguous skill slug` error names, and it is what
25
+ * disambiguates a slug several publishers use (measured: `self-improving-agent` + ownerHandle
26
+ * answers that owner's versions).
27
+ * `GET /api/v1/download?slug=&ownerHandle=&version=` → 200 `application/zip` — deterministic
28
+ * bytes for that version (bare `slug` 404s nothing an `ownerHandle` fixes; `@owner/slug` and
29
+ * `owner/slug` path/query forms answer 404 — only the bare slug plus `ownerHandle` resolves).
30
+ * A 200 that carries JSON instead of ZIP bytes is the registry's `public-github` handoff
31
+ * descriptor for GitHub-backed skills — this reader refuses it by name rather than guessing
32
+ * the descriptor's shape.
33
+ *
34
+ * Errors are plain text (`404 Skill not found`) or a JSON body behind `409` (`AMBIGUOUS_SKILL_SLUG`
35
+ * with a `matches[]` listing the owning handles) — both mapped to the shared failure vocabulary.
36
+ * Anonymous reads are limited to 3000/min per IP with `Retry-After` on 429 — the widest budget of
37
+ * any source this market reads — and every read still goes through the shared retry policy, because
38
+ * the registry's CDN drops bursts from this environment (`000` on roughly one probe in three).
39
+ *
40
+ * Deliberately NOT folded into `MarketItem.stars`: ClawHub's own `stats.stars` and download/install
41
+ * counts. `MarketItem.stars` is a GitHub star count one unit per field (`harness/stars.ts` resolves
42
+ * it from a repository, and these rows have none), so printing ClawHub's own rating under it would
43
+ * relabel one number as another — the same rule that keeps skills.sh's install tally out. They travel
44
+ * in their OWN field (`MarketItem.registryStats` / `MarketDetail.registryStats`) instead, where the
45
+ * console labels them with the source's name.
46
+ */
47
+ import zlib from 'node:zlib';
48
+ import { describeFetchFailure, fetchFailureReason, fetchWithRetry } from './net.js';
49
+ const SITE = 'https://clawhub.ai';
50
+ /** Largest console page this adapter forwards (upstream honors at least 100; the market asks ≤ 50). */
51
+ export const CLAWHUB_PAGE_MAX = 50;
52
+ /**
53
+ * The limit one search request carries. The endpoint ignores every paging parameter, so this is the
54
+ * whole reach of one query — the console slices the answer locally and reports it as a window.
55
+ */
56
+ export const CLAWHUB_SEARCH_LIMIT = 200;
57
+ /** Deepest console page the cursor walk will serve (40 × 50 rows) — same bound as the MCP registry
58
+ * walk: a cursor API has no offset, so page N costs N reads, and past this depth the answer is a
59
+ * typed refusal rather than a silent clamp onto the last page. */
60
+ export const CLAWHUB_WALK_MAX = 40;
61
+ /** Payload caps, identical to the GitHub skill adapter's — enforced before any disk write. */
62
+ export const CLAWHUB_MAX_FILES = 200;
63
+ export const CLAWHUB_MAX_BYTES = 8 * 1024 * 1024;
64
+ /** `ownerHandle`/`slug` are the identity; a row missing either has no installable identity at all. */
65
+ const OWNER = /^[\w.-]+$/;
66
+ const SLUG = /^[\w.-]+$/;
67
+ /** A counter, or `null` — never a guess, never `0` for a count the answer did not state. */
68
+ const countOrNull = (value) => typeof value === 'number' && Number.isFinite(value) ? value : null;
69
+ /** The vendor's `stats` object → the three counters this market shows, or `null` when absent. */
70
+ function toStats(raw) {
71
+ if (!raw || typeof raw !== 'object')
72
+ return null;
73
+ const row = raw;
74
+ const stats = {
75
+ stars: countOrNull(row.stars),
76
+ downloads: countOrNull(row.downloads),
77
+ installs: countOrNull(row.installs),
78
+ };
79
+ return stats.stars === null && stats.downloads === null && stats.installs === null ? null : stats;
80
+ }
81
+ function toEntry(ownerHandle, slug, name, summary, topics, updatedAtMs, stats) {
82
+ if (typeof ownerHandle !== 'string' || typeof slug !== 'string')
83
+ return null;
84
+ if (!OWNER.test(ownerHandle) || !SLUG.test(slug))
85
+ return null;
86
+ return {
87
+ ownerHandle,
88
+ slug,
89
+ name: typeof name === 'string' && name.trim() ? name.trim() : slug,
90
+ summary: typeof summary === 'string' && summary.trim() ? summary.trim() : null,
91
+ topics: Array.isArray(topics) ? topics.filter((t) => typeof t === 'string') : [],
92
+ updatedAtMs: typeof updatedAtMs === 'number' && Number.isFinite(updatedAtMs) ? updatedAtMs : null,
93
+ stats: toStats(stats),
94
+ };
95
+ }
96
+ /** One JSON read with the shared retry policy and the failure vocabulary every adapter answers with. */
97
+ async function readJson(url, label, fetchImpl) {
98
+ let res;
99
+ try {
100
+ res = await fetchWithRetry(url, { headers: { Accept: 'application/json', 'User-Agent': 'omnicellrouter-harness' } }, undefined, { fetchImpl });
101
+ }
102
+ catch (e) {
103
+ return { ok: false, code: 'upstream', reason: fetchFailureReason(e), message: describeFetchFailure(label, e) };
104
+ }
105
+ if (res.status === 429 || res.status >= 500) {
106
+ return {
107
+ ok: false,
108
+ code: 'unavailable',
109
+ reason: 'unavailable',
110
+ message: `${label} returned HTTP ${res.status} — try again later`,
111
+ };
112
+ }
113
+ if (!res.ok) {
114
+ return {
115
+ ok: false,
116
+ code: 'upstream',
117
+ reason: 'http',
118
+ reasonParams: { status: String(res.status) },
119
+ message: `${label} returned HTTP ${res.status}`,
120
+ };
121
+ }
122
+ try {
123
+ return { ok: true, body: JSON.parse(await res.text()) };
124
+ }
125
+ catch (e) {
126
+ return { ok: false, code: 'upstream', reason: 'badPayload', message: describeFetchFailure(label, e) };
127
+ }
128
+ }
129
+ /** One catalog page → normalized entries, in the registry's own order (its ranking). */
130
+ export async function fetchClawHubCatalogPage(sort, limit, cursor, fetchImpl = fetch) {
131
+ const params = new URLSearchParams({ limit: String(Math.min(Math.max(limit, 1), CLAWHUB_PAGE_MAX)), sort });
132
+ if (cursor)
133
+ params.set('cursor', cursor);
134
+ const read = await readJson(`${SITE}/api/v1/skills?${params.toString()}`, 'ClawHub catalog', fetchImpl);
135
+ if (!read.ok)
136
+ return read;
137
+ const body = read.body;
138
+ if (!Array.isArray(body?.items)) {
139
+ return { ok: false, code: 'upstream', reason: 'badPayload', message: 'ClawHub catalog answered no `items` array — the endpoint changed shape' };
140
+ }
141
+ const entries = body.items
142
+ .map((row) => {
143
+ const r = row;
144
+ return toEntry(r.ownerHandle, r.slug, r.displayName, r.summary, r.topics, r.updatedAt, r.stats);
145
+ })
146
+ .filter((entry) => entry !== null);
147
+ return { ok: true, entries, next: typeof body.nextCursor === 'string' && body.nextCursor ? body.nextCursor : null };
148
+ }
149
+ /** One whole-catalog search answer → normalized entries, in the registry's relevance order. */
150
+ export async function fetchClawHubSearch(query, fetchImpl = fetch) {
151
+ const params = new URLSearchParams({ q: query, limit: String(CLAWHUB_SEARCH_LIMIT) });
152
+ const read = await readJson(`${SITE}/api/v1/search?${params.toString()}`, 'ClawHub search', fetchImpl);
153
+ if (!read.ok)
154
+ return read;
155
+ const body = read.body;
156
+ if (!Array.isArray(body?.results)) {
157
+ return { ok: false, code: 'upstream', reason: 'badPayload', message: 'ClawHub search answered no `results` array — the endpoint changed shape' };
158
+ }
159
+ const entries = body.results
160
+ .map((row) => {
161
+ const r = row;
162
+ const native = (r.native ?? {});
163
+ const skill = (native.skill ?? {});
164
+ const metrics = (r.metrics ?? {});
165
+ return toEntry(r.ownerHandle, r.slug, r.displayName, r.summary, skill.topics, metrics.updatedAt, skill.stats);
166
+ })
167
+ .filter((entry) => entry !== null);
168
+ return { ok: true, entries };
169
+ }
170
+ /** The newest published version of one (owner, slug), or `null` when the registry lists none. */
171
+ export async function fetchClawHubLatestVersion(slug, ownerHandle, fetchImpl = fetch) {
172
+ const params = new URLSearchParams({ limit: '1', ownerHandle });
173
+ const read = await readJson(`${SITE}/api/v1/skills/${encodeURIComponent(slug)}/versions?${params.toString()}`, 'ClawHub versions', fetchImpl);
174
+ if (!read.ok)
175
+ return read;
176
+ const body = read.body;
177
+ const items = Array.isArray(body?.items) ? body.items : [];
178
+ const first = items[0];
179
+ return { ok: true, version: typeof first?.version === 'string' && first.version ? first.version : null };
180
+ }
181
+ /**
182
+ * Strip a leading YAML frontmatter block (`---` … `---`) from a published `SKILL.md`.
183
+ *
184
+ * The registry stores the file VERBATIM, so the body a dialog renders would otherwise open with an
185
+ * `---` rule and a wall of `key: value` lines the operator did not ask for. Only a block that
186
+ * actually opens the document is removed — a horizontal rule further down is content.
187
+ */
188
+ export function stripFrontmatter(text) {
189
+ const body = text.replace(/\r\n/g, '\n');
190
+ if (!body.startsWith('---\n'))
191
+ return body;
192
+ const end = body.indexOf('\n---', 3);
193
+ if (end < 0)
194
+ return body;
195
+ // The closing delimiter's own newline, plus the blank line authors put after it, are part of the
196
+ // header block — the body starts at the first line that carries text.
197
+ return body.slice(end + 4).replace(/^\n+/, '');
198
+ }
199
+ const msOrNull = (value) => typeof value === 'number' && Number.isFinite(value) ? value : null;
200
+ const textOrNull = (value) => typeof value === 'string' && value.trim() ? value : null;
201
+ /**
202
+ * Read ONE skill's own record (`GET /api/v1/skills/<slug>?ownerHandle=`).
203
+ *
204
+ * The identity is the pair the row already carries (`ownerHandle` + `slug`), and the answer is
205
+ * checked against it: the registry's per-slug endpoint resolves a slug to ONE publisher, so a record
206
+ * whose `owner.handle` is not the owner we asked for is not this row's skill — it is refused rather
207
+ * than rendered under the wrong name.
208
+ */
209
+ export async function fetchClawHubSkill(slug, ownerHandle, fetchImpl = fetch) {
210
+ const params = new URLSearchParams({ ownerHandle });
211
+ const read = await readJson(`${SITE}/api/v1/skills/${encodeURIComponent(slug)}?${params.toString()}`, 'ClawHub skill', fetchImpl);
212
+ if (!read.ok) {
213
+ if (read.reason === 'http' && read.reasonParams?.status === '404') {
214
+ return {
215
+ ok: false,
216
+ code: 'no_artifact',
217
+ reason: 'http',
218
+ reasonParams: { status: '404' },
219
+ message: `ClawHub lists no skill '${ownerHandle}/${slug}'`,
220
+ };
221
+ }
222
+ return read;
223
+ }
224
+ const body = read.body;
225
+ const skill = body?.skill;
226
+ if (!skill || typeof skill.slug !== 'string') {
227
+ return {
228
+ ok: false,
229
+ code: 'upstream',
230
+ reason: 'badPayload',
231
+ message: 'ClawHub skill answered no `skill` record — the endpoint changed shape',
232
+ };
233
+ }
234
+ const answeredOwner = typeof body?.owner?.handle === 'string' ? body.owner.handle : null;
235
+ if (answeredOwner && answeredOwner.toLowerCase() !== ownerHandle.toLowerCase()) {
236
+ return {
237
+ ok: false,
238
+ code: 'no_artifact',
239
+ message: `ClawHub resolved '${slug}' to '${answeredOwner}', not '${ownerHandle}'`,
240
+ };
241
+ }
242
+ const latest = body?.latestVersion ?? {};
243
+ const tags = (skill.tags ?? {});
244
+ const description = typeof skill.description === 'string' ? stripFrontmatter(skill.description).trim() : '';
245
+ return {
246
+ ok: true,
247
+ detail: {
248
+ slug,
249
+ ownerHandle,
250
+ name: textOrNull(skill.displayName) ?? slug,
251
+ summary: textOrNull(skill.summary),
252
+ body: description === '' ? null : description,
253
+ topics: Array.isArray(skill.topics) ? skill.topics.filter((t) => typeof t === 'string') : [],
254
+ version: textOrNull(latest.version) ?? textOrNull(tags.latest),
255
+ license: textOrNull(latest.license),
256
+ publishedAtMs: msOrNull(latest.createdAt),
257
+ updatedAtMs: msOrNull(skill.updatedAt),
258
+ stats: toStats(skill.stats),
259
+ },
260
+ };
261
+ }
262
+ /**
263
+ * Download one pinned version's ZIP (`GET /api/v1/download?slug=&ownerHandle=&version=`).
264
+ *
265
+ * The bytes are the install payload, so the caps here guard MEMORY the way the GitHub adapter's
266
+ * guard the tarball: a declared length past the cap is refused before buffering. A 200 that answers
267
+ * JSON instead of ZIP is the registry's `public-github` handoff for GitHub-backed skills — its shape
268
+ * is undocumented, so the reader refuses it by name instead of guessing.
269
+ */
270
+ export async function downloadClawHubZip(slug, ownerHandle, version, fetchImpl = fetch, sleep) {
271
+ const params = new URLSearchParams({ slug, ownerHandle, version });
272
+ let res;
273
+ try {
274
+ res = await fetchWithRetry(`${SITE}/api/v1/download?${params.toString()}`, { headers: { Accept: 'application/zip, application/json', 'User-Agent': 'omnicellrouter-harness' } }, undefined,
275
+ // `sleep` is net.ts's own test seam: a fixture answering 404/409 must not spend the market
276
+ // policy's real backoff to prove a status mapping.
277
+ sleep ? { fetchImpl, sleep } : { fetchImpl });
278
+ }
279
+ catch (e) {
280
+ return { ok: false, code: 'upstream', reason: fetchFailureReason(e), message: describeFetchFailure('ClawHub download', e) };
281
+ }
282
+ if (res.status === 404) {
283
+ return { ok: false, code: 'no_artifact', message: `ClawHub lists no skill '${ownerHandle}/${slug}'` };
284
+ }
285
+ if (res.status === 409) {
286
+ const text = await res.text().catch(() => '');
287
+ let candidates = [];
288
+ try {
289
+ const body = JSON.parse(text);
290
+ candidates = (body.matches ?? [])
291
+ .map((m) => (typeof m.ownerHandle === 'string' && typeof m.slug === 'string' ? `${m.ownerHandle}/${m.slug}` : ''))
292
+ .filter((ref) => ref !== '');
293
+ }
294
+ catch {
295
+ // A plain-text 409 still means "several publishers use this slug" — report it without candidates.
296
+ }
297
+ return {
298
+ ok: false,
299
+ code: 'ambiguous',
300
+ message: `slug '${slug}' is published by several owners — pick one`,
301
+ ...(candidates.length > 0 ? { candidates } : {}),
302
+ };
303
+ }
304
+ if (res.status === 429 || res.status >= 500) {
305
+ return { ok: false, code: 'unavailable', reason: 'unavailable', message: `ClawHub download returned HTTP ${res.status} — try again later` };
306
+ }
307
+ if (!res.ok) {
308
+ return { ok: false, code: 'upstream', reason: 'http', reasonParams: { status: String(res.status) }, message: `ClawHub download returned HTTP ${res.status}` };
309
+ }
310
+ const declaredLength = Number(res.headers.get('content-length') ?? 0);
311
+ if (declaredLength > CLAWHUB_MAX_BYTES) {
312
+ return { ok: false, code: 'too_large', message: `${Math.round(declaredLength / 1024 / 1024)} MiB archive exceeds the 8 MiB cap` };
313
+ }
314
+ const type = (res.headers.get('content-type') ?? '').toLowerCase();
315
+ const archive = Buffer.from(await res.arrayBuffer());
316
+ if (archive.length > CLAWHUB_MAX_BYTES) {
317
+ return { ok: false, code: 'too_large', message: `${Math.round(archive.length / 1024 / 1024)} MiB archive exceeds the 8 MiB cap` };
318
+ }
319
+ if (type.includes('json')) {
320
+ return {
321
+ ok: false,
322
+ code: 'upstream',
323
+ reason: 'badPayload',
324
+ message: 'registry answered a public-github handoff descriptor — this skill is GitHub-backed; install it through the GitHub source',
325
+ };
326
+ }
327
+ if (!type.includes('zip') && archive.subarray(0, 2).toString('latin1') !== 'PK') {
328
+ return { ok: false, code: 'upstream', reason: 'badPayload', message: 'ClawHub download answered neither ZIP bytes nor a known descriptor' };
329
+ }
330
+ return { ok: true, zip: archive };
331
+ }
332
+ /**
333
+ * A payload that passed the compressed-size check but breaks a cap once expanded (file count or
334
+ * expanded bytes). Distinct from a corrupt archive so the caller can answer `too_large` — "this
335
+ * artifact is too big" and "this archive is broken" are different facts to the user.
336
+ */
337
+ export class ZipTooLargeError extends Error {
338
+ }
339
+ /**
340
+ * Minimal ZIP reader for ClawHub's skill archives — the counterpart of the GitHub adapter's tar
341
+ * reader: 32-bit ZIP only (stored + deflate), no Zip64, no encryption, no data descriptors, and no
342
+ * CRC verification. The trust posture is the one ADR-0015 already states for third-party content —
343
+ * files are DATA written under caps (200 files / 8 MiB, enforced by the caller) and never executed —
344
+ * and an integrity check would not change it; the manifest's content hash is computed over what
345
+ * actually landed, which is what "is this copy still ours?" answers from.
346
+ *
347
+ * Central-directory driven (one pass, no per-entry scans): EOCD is searched from the tail, each
348
+ * central record names its entry, and the DATA offset comes from the LOCAL header's own name/extra
349
+ * lengths — the central copy may disagree with it.
350
+ */
351
+ export function readZip(buffer) {
352
+ let eocd = -1;
353
+ const minEocd = Math.max(0, buffer.length - 22 - 65_536);
354
+ for (let i = buffer.length - 22; i >= minEocd; i -= 1) {
355
+ if (buffer.readUInt32LE(i) === 0x06054b50) {
356
+ eocd = i;
357
+ break;
358
+ }
359
+ }
360
+ if (eocd < 0)
361
+ throw new Error('not a ZIP archive (no end-of-central-directory record)');
362
+ const count = buffer.readUInt16LE(eocd + 10);
363
+ const cdOffset = buffer.readUInt32LE(eocd + 16);
364
+ if (count === 0xffff || cdOffset === 0xffffffff)
365
+ throw new Error('zip64 archives are not supported');
366
+ // Both caps are enforced HERE, before any decompression: the entry count is known from the EOCD,
367
+ // and the expanded-byte budget bounds every `inflateRawSync` call (a deflate stream can expand
368
+ // ~1000:1, so a compressed-size check alone is not a memory bound).
369
+ if (count > CLAWHUB_MAX_FILES)
370
+ throw new ZipTooLargeError(`${count} entries exceeds the ${CLAWHUB_MAX_FILES}-file cap`);
371
+ const out = [];
372
+ let expanded = 0;
373
+ let p = cdOffset;
374
+ for (let n = 0; n < count; n += 1) {
375
+ if (p + 46 > buffer.length || buffer.readUInt32LE(p) !== 0x02014b50)
376
+ throw new Error('corrupt central directory');
377
+ const flags = buffer.readUInt16LE(p + 8);
378
+ const method = buffer.readUInt16LE(p + 10);
379
+ const compSize = buffer.readUInt32LE(p + 20);
380
+ const nameLen = buffer.readUInt16LE(p + 28);
381
+ const extraLen = buffer.readUInt16LE(p + 30);
382
+ const commentLen = buffer.readUInt16LE(p + 32);
383
+ const localOffset = buffer.readUInt32LE(p + 42);
384
+ const name = buffer.toString('utf8', p + 46, p + 46 + nameLen);
385
+ p += 46 + nameLen + extraLen + commentLen;
386
+ if (name.endsWith('/'))
387
+ continue;
388
+ if (flags & 0x0001)
389
+ throw new Error(`encrypted entry '${name}' is not supported`);
390
+ if (method !== 0 && method !== 8)
391
+ throw new Error(`entry '${name}' uses an unsupported compression method (${method})`);
392
+ if (compSize === 0xffffffff)
393
+ throw new Error('zip64 archives are not supported');
394
+ if (localOffset + 30 > buffer.length || buffer.readUInt32LE(localOffset) !== 0x04034b50) {
395
+ throw new Error(`corrupt local header for '${name}'`);
396
+ }
397
+ const localNameLen = buffer.readUInt16LE(localOffset + 26);
398
+ const localExtraLen = buffer.readUInt16LE(localOffset + 28);
399
+ const dataStart = localOffset + 30 + localNameLen + localExtraLen;
400
+ if (dataStart + compSize > buffer.length)
401
+ throw new Error(`truncated entry '${name}'`);
402
+ const raw = buffer.subarray(dataStart, dataStart + compSize);
403
+ const room = CLAWHUB_MAX_BYTES - expanded;
404
+ if (room <= 0)
405
+ throw new ZipTooLargeError(`expanded archive exceeds the ${CLAWHUB_MAX_BYTES}-byte cap`);
406
+ let data;
407
+ if (method === 0)
408
+ data = Buffer.from(raw);
409
+ else {
410
+ try {
411
+ data = zlib.inflateRawSync(raw, { maxOutputLength: room });
412
+ }
413
+ catch (e) {
414
+ // `ERR_BUFFER_TOO_LARGE` is the cap doing its job; anything else is a broken stream.
415
+ if (e.code !== 'ERR_BUFFER_TOO_LARGE')
416
+ throw e;
417
+ throw new ZipTooLargeError(`expanded archive exceeds the ${CLAWHUB_MAX_BYTES}-byte cap`);
418
+ }
419
+ }
420
+ if (data.length > room)
421
+ throw new ZipTooLargeError(`expanded archive exceeds the ${CLAWHUB_MAX_BYTES}-byte cap`);
422
+ expanded += data.length;
423
+ out.push({ path: name, data });
424
+ }
425
+ return out;
426
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Read/write one runtime config file with the house safety contract (ADR-0015 §D5, gate 2).
3
+ *
4
+ * Shared by the two write paths that MUTATE an existing config member — the extension writer's
5
+ * `plugin[]` merge and removal's `drop-entry` / `drop-server` ops — so a member is removed with
6
+ * exactly the discipline that added it: parse plain JSON only (a JSONC file would lose its comments
7
+ * in a round-trip), snapshot with `createBackup` (`.bak.ocr`), then an atomic rename.
8
+ *
9
+ * The merge paths that may also CREATE a file (`writers/mcp.ts`) keep their own reader: their
10
+ * contract answers `{}` for an absent file, which is the wrong answer for a removal.
11
+ */
12
+ export type ConfigRead = {
13
+ ok: true;
14
+ config: Record<string, unknown>;
15
+ } | {
16
+ ok: false;
17
+ reason: string;
18
+ };
19
+ export declare function readConfigJson(file: string): ConfigRead;
20
+ /**
21
+ * Snapshot then atomically write. A failure leaves the original file untouched: `createBackup` runs
22
+ * first, `safeWriteJson` renames only after a complete write.
23
+ */
24
+ export declare function writeConfigJson(file: string, config: Record<string, unknown>): {
25
+ ok: true;
26
+ } | {
27
+ ok: false;
28
+ reason: string;
29
+ };
@@ -0,0 +1,35 @@
1
+ import fs from 'node:fs';
2
+ import { createBackup, safeWriteJson } from '../cli/clients/base.js';
3
+ export function readConfigJson(file) {
4
+ let text;
5
+ try {
6
+ text = fs.readFileSync(file, 'utf8');
7
+ }
8
+ catch (e) {
9
+ return { ok: false, reason: `cannot read config: ${e instanceof Error ? e.message : e}` };
10
+ }
11
+ try {
12
+ const parsed = JSON.parse(text.replace(/^\uFEFF/, ''));
13
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
14
+ return { ok: false, reason: 'config root is not a JSON object' };
15
+ }
16
+ return { ok: true, config: parsed };
17
+ }
18
+ catch {
19
+ return { ok: false, reason: 'config is not valid plain JSON; refusing a lossy rewrite' };
20
+ }
21
+ }
22
+ /**
23
+ * Snapshot then atomically write. A failure leaves the original file untouched: `createBackup` runs
24
+ * first, `safeWriteJson` renames only after a complete write.
25
+ */
26
+ export function writeConfigJson(file, config) {
27
+ try {
28
+ createBackup(file);
29
+ safeWriteJson(file, config);
30
+ return { ok: true };
31
+ }
32
+ catch (e) {
33
+ return { ok: false, reason: e instanceof Error ? e.message : String(e) };
34
+ }
35
+ }
@@ -0,0 +1,74 @@
1
+ import { type FailureReason } from './net.js';
2
+ export interface MarketDetail {
3
+ /** Markdown body, already capped. `null` when the row publishes none. */
4
+ readme: string | null;
5
+ /** Repository the body came from, when one could be resolved. */
6
+ repo?: string;
7
+ description?: string;
8
+ homepage?: string;
9
+ license?: string;
10
+ latestVersion?: string;
11
+ /** ISO timestamp of the latest publish (npm) / last push (GitHub). */
12
+ publishedAt?: string;
13
+ updatedAt?: string;
14
+ language?: string;
15
+ stars?: number;
16
+ topics?: string[];
17
+ /**
18
+ * The SOURCE'S OWN popularity counters — today ClawHub's star/download/install tally. Separate
19
+ * from `stars` on purpose: those are GitHub's unit, and the console labels this row with its
20
+ * source instead of relabelling a number (ADR-0015 §D6).
21
+ */
22
+ registryStats?: {
23
+ stars: number | null;
24
+ downloads: number | null;
25
+ installs: number | null;
26
+ };
27
+ /** Which upstream actually answered. `none` = nothing could be read (the caller renders local
28
+ * row data only, so the dialog still opens). */
29
+ readFrom: 'npm' | 'github' | 'clawhub' | 'none';
30
+ /** Why the long-form read produced nothing, in the console's translatable vocabulary. */
31
+ reason?: FailureReason;
32
+ reasonParams?: Record<string, string>;
33
+ /** English fallback for `reason` — and the diagnostic. */
34
+ message?: string;
35
+ }
36
+ /** Test hook: a cached detail would otherwise leak between cases. */
37
+ export declare function resetDetailCache(): void;
38
+ /**
39
+ * A package name this reader is willing to interpolate into a registry URL.
40
+ *
41
+ * The input reaches us from a market row named by a THIRD PARTY (a catalog prints its own install
42
+ * command), so it is validated here, at the boundary, before any string concatenation: no traversal
43
+ * segment, no extra slash, no scheme.
44
+ */
45
+ export declare function safePackageName(name: string | undefined | null): string | null;
46
+ /** `npm:<name>` → the package name, or null when the key names another source. */
47
+ export declare function packageFromKey(key: string | undefined | null): string | null;
48
+ /** `owner/repo` as the console spelled it, or null. Never a URL: the API host is ours to pick. */
49
+ export declare function safeRepoSlug(slug: string | undefined | null): string | null;
50
+ /**
51
+ * `clawhub:<owner>/<slug>` → the two identity halves, or null when the key names another source.
52
+ *
53
+ * ClawHub rows carry no npm name and no repository, so their detail is read from the registry's own
54
+ * record — and the pair is validated here, at the boundary, for exactly the reason `safeRepoSlug`
55
+ * exists: both halves are interpolated into a URL this process chooses.
56
+ */
57
+ export declare function clawhubFromKey(key: string | undefined | null): {
58
+ owner: string;
59
+ slug: string;
60
+ } | null;
61
+ /**
62
+ * Read the long-form half of one market row.
63
+ *
64
+ * Order: the registry first (one request, and it carries the README for the overwhelming majority of
65
+ * packages), then the repository (facts + README) when the registry had no body or the row has no
66
+ * package at all. A `clawhub:<owner>/<slug>` row takes neither of those paths — it has no npm name
67
+ * and no repository, and its registry's own per-skill record carries the published SKILL.md. A row
68
+ * that reaches none of them still answers — `readFrom: 'none'` — because the dialog is built on the
69
+ * row the console already holds.
70
+ */
71
+ export declare function readMarketDetail(input: {
72
+ key?: string;
73
+ repo?: string;
74
+ }, fetchImpl?: typeof fetch): Promise<MarketDetail>;