@b3os/cli 0.2.1 → 0.2.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 (214) hide show
  1. package/README.md +87 -8
  2. package/assets/b3os-run.py +137 -0
  3. package/assets/skill/b3os/SKILL.md +111 -0
  4. package/dist/commands/_agents.d.ts +14 -0
  5. package/dist/commands/_agents.js +33 -0
  6. package/dist/commands/_agents.js.map +1 -0
  7. package/dist/commands/_common.js +6 -2
  8. package/dist/commands/_common.js.map +1 -1
  9. package/dist/commands/_context.d.ts +49 -0
  10. package/dist/commands/_context.js +260 -0
  11. package/dist/commands/_context.js.map +1 -0
  12. package/dist/commands/_next.d.ts +39 -0
  13. package/dist/commands/_next.js +77 -0
  14. package/dist/commands/_next.js.map +1 -0
  15. package/dist/commands/agent.d.ts +42 -0
  16. package/dist/commands/agent.js +218 -0
  17. package/dist/commands/agent.js.map +1 -0
  18. package/dist/commands/app.d.ts +2 -5
  19. package/dist/commands/app.js +229 -69
  20. package/dist/commands/app.js.map +1 -1
  21. package/dist/commands/auth.d.ts +70 -2
  22. package/dist/commands/auth.js +308 -33
  23. package/dist/commands/auth.js.map +1 -1
  24. package/dist/commands/docs.d.ts +54 -0
  25. package/dist/commands/docs.js +202 -0
  26. package/dist/commands/docs.js.map +1 -0
  27. package/dist/commands/doctor.d.ts +23 -0
  28. package/dist/commands/doctor.js +313 -0
  29. package/dist/commands/doctor.js.map +1 -0
  30. package/dist/commands/init.d.ts +38 -1
  31. package/dist/commands/init.js +259 -60
  32. package/dist/commands/init.js.map +1 -1
  33. package/dist/commands/listen.d.ts +30 -0
  34. package/dist/commands/listen.js +194 -0
  35. package/dist/commands/listen.js.map +1 -0
  36. package/dist/commands/manifest.d.ts +13 -1
  37. package/dist/commands/manifest.js +59 -7
  38. package/dist/commands/manifest.js.map +1 -1
  39. package/dist/commands/mcp.d.ts +25 -2
  40. package/dist/commands/mcp.js +120 -11
  41. package/dist/commands/mcp.js.map +1 -1
  42. package/dist/commands/sandbox.d.ts +35 -6
  43. package/dist/commands/sandbox.js +208 -9
  44. package/dist/commands/sandbox.js.map +1 -1
  45. package/dist/commands/setup.d.ts +39 -0
  46. package/dist/commands/setup.js +203 -0
  47. package/dist/commands/setup.js.map +1 -0
  48. package/dist/commands/tool.d.ts +109 -1
  49. package/dist/commands/tool.js +635 -47
  50. package/dist/commands/tool.js.map +1 -1
  51. package/dist/config.d.ts +30 -6
  52. package/dist/config.js +39 -8
  53. package/dist/config.js.map +1 -1
  54. package/dist/ctx.d.ts +5 -45
  55. package/dist/ctx.js +25 -160
  56. package/dist/ctx.js.map +1 -1
  57. package/dist/docs/index.json +1 -0
  58. package/dist/docs/pages/actions/call.md +300 -0
  59. package/dist/docs/pages/actions/catalog/airtable.md +737 -0
  60. package/dist/docs/pages/actions/catalog/arxiv.md +166 -0
  61. package/dist/docs/pages/actions/catalog/chainalysis-sanctions.md +125 -0
  62. package/dist/docs/pages/actions/catalog/coingecko.md +1558 -0
  63. package/dist/docs/pages/actions/catalog/deps-dev.md +465 -0
  64. package/dist/docs/pages/actions/catalog/dexscreener.md +568 -0
  65. package/dist/docs/pages/actions/catalog/discord.md +784 -0
  66. package/dist/docs/pages/actions/catalog/finnhub.md +776 -0
  67. package/dist/docs/pages/actions/catalog/frankfurter.md +438 -0
  68. package/dist/docs/pages/actions/catalog/github.md +1853 -0
  69. package/dist/docs/pages/actions/catalog/gmail.md +575 -0
  70. package/dist/docs/pages/actions/catalog/google-calendar.md +654 -0
  71. package/dist/docs/pages/actions/catalog/google-drive.md +502 -0
  72. package/dist/docs/pages/actions/catalog/google-sheets.md +700 -0
  73. package/dist/docs/pages/actions/catalog/hacker-news.md +542 -0
  74. package/dist/docs/pages/actions/catalog/http.md +824 -0
  75. package/dist/docs/pages/actions/catalog/hyperliquid.md +942 -0
  76. package/dist/docs/pages/actions/catalog/jira.md +920 -0
  77. package/dist/docs/pages/actions/catalog/kalshi.md +917 -0
  78. package/dist/docs/pages/actions/catalog/linear.md +1030 -0
  79. package/dist/docs/pages/actions/catalog/markets.md +21 -0
  80. package/dist/docs/pages/actions/catalog/morpho.md +247 -0
  81. package/dist/docs/pages/actions/catalog/notion.md +1077 -0
  82. package/dist/docs/pages/actions/catalog/nws.md +485 -0
  83. package/dist/docs/pages/actions/catalog/open-meteo.md +559 -0
  84. package/dist/docs/pages/actions/catalog/polymarket.md +1523 -0
  85. package/dist/docs/pages/actions/catalog/pushbullet.md +220 -0
  86. package/dist/docs/pages/actions/catalog/resend.md +307 -0
  87. package/dist/docs/pages/actions/catalog/s3.md +513 -0
  88. package/dist/docs/pages/actions/catalog/sec-edgar.md +487 -0
  89. package/dist/docs/pages/actions/catalog/slack.md +2629 -0
  90. package/dist/docs/pages/actions/catalog/stripe.md +1405 -0
  91. package/dist/docs/pages/actions/catalog/wikipedia.md +379 -0
  92. package/dist/docs/pages/actions/catalog.md +46 -0
  93. package/dist/docs/pages/actions/limits.md +50 -0
  94. package/dist/docs/pages/actions/model-tools.md +225 -0
  95. package/dist/docs/pages/actions/packs.md +148 -0
  96. package/dist/docs/pages/actions/settings.md +69 -0
  97. package/dist/docs/pages/actions/tools.md +244 -0
  98. package/dist/docs/pages/actions/triggers.md +149 -0
  99. package/dist/docs/pages/actions.md +88 -0
  100. package/dist/docs/pages/compat/anthropic.md +168 -0
  101. package/dist/docs/pages/compat/e2b.md +194 -0
  102. package/dist/docs/pages/compat/firecrawl.md +138 -0
  103. package/dist/docs/pages/compat/openai.md +168 -0
  104. package/dist/docs/pages/concepts/auth.md +151 -0
  105. package/dist/docs/pages/concepts/beta.md +55 -0
  106. package/dist/docs/pages/concepts/glossary.md +71 -0
  107. package/dist/docs/pages/concepts/ids.md +98 -0
  108. package/dist/docs/pages/concepts/jobs.md +229 -0
  109. package/dist/docs/pages/concepts/latency.md +138 -0
  110. package/dist/docs/pages/concepts/limits.md +191 -0
  111. package/dist/docs/pages/concepts/stack.md +59 -0
  112. package/dist/docs/pages/concepts/timing.md +86 -0
  113. package/dist/docs/pages/concepts/usage.md +110 -0
  114. package/dist/docs/pages/design/b3os-yaml.md +370 -0
  115. package/dist/docs/pages/design/deploy-from-github.md +122 -0
  116. package/dist/docs/pages/design/observability.md +134 -0
  117. package/dist/docs/pages/errors.md +1824 -0
  118. package/dist/docs/pages/infer/chat.md +570 -0
  119. package/dist/docs/pages/infer/limits.md +55 -0
  120. package/dist/docs/pages/infer/messages.md +185 -0
  121. package/dist/docs/pages/infer/responses.md +173 -0
  122. package/dist/docs/pages/infer/settings.md +154 -0
  123. package/dist/docs/pages/infer/speech.md +323 -0
  124. package/dist/docs/pages/infer.md +154 -0
  125. package/dist/docs/pages/introduction.md +162 -0
  126. package/dist/docs/pages/platform/addresses.md +174 -0
  127. package/dist/docs/pages/platform/call-log.md +99 -0
  128. package/dist/docs/pages/platform/custom-domains.md +104 -0
  129. package/dist/docs/pages/platform/keys.md +79 -0
  130. package/dist/docs/pages/platform/limits.md +57 -0
  131. package/dist/docs/pages/platform/members.md +101 -0
  132. package/dist/docs/pages/platform/requests.md +116 -0
  133. package/dist/docs/pages/platform/settings.md +129 -0
  134. package/dist/docs/pages/platform/webhooks.md +68 -0
  135. package/dist/docs/pages/platform.md +67 -0
  136. package/dist/docs/pages/quickstart/mcp.md +94 -0
  137. package/dist/docs/pages/quickstart/sandbox-agent.md +205 -0
  138. package/dist/docs/pages/quickstart/scrape.md +134 -0
  139. package/dist/docs/pages/quickstart.md +45 -0
  140. package/dist/docs/pages/render/inspections.md +162 -0
  141. package/dist/docs/pages/render/limits.md +72 -0
  142. package/dist/docs/pages/render/screenshots.md +179 -0
  143. package/dist/docs/pages/render/settings.md +431 -0
  144. package/dist/docs/pages/render/styles.md +342 -0
  145. package/dist/docs/pages/render/videos.md +272 -0
  146. package/dist/docs/pages/render.md +118 -0
  147. package/dist/docs/pages/routines/callables.md +174 -0
  148. package/dist/docs/pages/routines/definitions.md +361 -0
  149. package/dist/docs/pages/routines/limits.md +117 -0
  150. package/dist/docs/pages/routines/runs.md +328 -0
  151. package/dist/docs/pages/routines/settings.md +104 -0
  152. package/dist/docs/pages/routines/triggers.md +339 -0
  153. package/dist/docs/pages/routines.md +216 -0
  154. package/dist/docs/pages/sandboxes/agents.md +217 -0
  155. package/dist/docs/pages/sandboxes/commands.md +272 -0
  156. package/dist/docs/pages/sandboxes/images.md +166 -0
  157. package/dist/docs/pages/sandboxes/limits.md +143 -0
  158. package/dist/docs/pages/sandboxes/ports.md +260 -0
  159. package/dist/docs/pages/sandboxes/settings.md +358 -0
  160. package/dist/docs/pages/sandboxes/snapshots.md +423 -0
  161. package/dist/docs/pages/sandboxes/swarms.md +146 -0
  162. package/dist/docs/pages/sandboxes/volumes.md +131 -0
  163. package/dist/docs/pages/sandboxes.md +231 -0
  164. package/dist/docs/pages/sdks/cli.md +121 -0
  165. package/dist/docs/pages/sdks/mcp.md +169 -0
  166. package/dist/docs/pages/sdks/python.md +146 -0
  167. package/dist/docs/pages/sdks/typescript.md +202 -0
  168. package/dist/docs/pages/sdks.md +282 -0
  169. package/dist/docs/pages/settings.md +33 -0
  170. package/dist/docs/pages/vault/limits.md +46 -0
  171. package/dist/docs/pages/vault.md +133 -0
  172. package/dist/docs/pages/vision/agent-browser.md +115 -0
  173. package/dist/docs/pages/vision/crawl.md +333 -0
  174. package/dist/docs/pages/vision/extract.md +152 -0
  175. package/dist/docs/pages/vision/fetcher.md +15 -0
  176. package/dist/docs/pages/vision/limits.md +79 -0
  177. package/dist/docs/pages/vision/profiles.md +111 -0
  178. package/dist/docs/pages/vision/proxy.md +131 -0
  179. package/dist/docs/pages/vision/scrape.md +356 -0
  180. package/dist/docs/pages/vision/sessions.md +311 -0
  181. package/dist/docs/pages/vision/settings.md +656 -0
  182. package/dist/docs/pages/vision.md +175 -0
  183. package/dist/errors.d.ts +129 -0
  184. package/dist/errors.js +326 -0
  185. package/dist/errors.js.map +1 -0
  186. package/dist/main.d.ts +1 -1
  187. package/dist/main.js +26 -13
  188. package/dist/main.js.map +1 -1
  189. package/dist/manifest/domains.d.ts +50 -0
  190. package/dist/manifest/domains.js +159 -0
  191. package/dist/manifest/domains.js.map +1 -0
  192. package/dist/manifest/link.d.ts +20 -0
  193. package/dist/manifest/link.js +24 -0
  194. package/dist/manifest/link.js.map +1 -0
  195. package/dist/manifest/record.d.ts +1 -1
  196. package/dist/tool/archive.d.ts +33 -0
  197. package/dist/tool/archive.js +174 -0
  198. package/dist/tool/archive.js.map +1 -0
  199. package/dist/tool/calls.d.ts +46 -0
  200. package/dist/tool/calls.js +274 -0
  201. package/dist/tool/calls.js.map +1 -0
  202. package/dist/tool/checks.d.ts +21 -0
  203. package/dist/tool/checks.js +145 -0
  204. package/dist/tool/checks.js.map +1 -0
  205. package/dist/tool/elf.d.ts +19 -0
  206. package/dist/tool/elf.js +107 -0
  207. package/dist/tool/elf.js.map +1 -0
  208. package/dist/tool/predict.d.ts +8 -0
  209. package/dist/tool/predict.js +38 -0
  210. package/dist/tool/predict.js.map +1 -0
  211. package/dist/tool/ustar.d.ts +5 -0
  212. package/dist/tool/ustar.js +220 -0
  213. package/dist/tool/ustar.js.map +1 -0
  214. package/package.json +6 -5
@@ -1,25 +1,70 @@
1
- // b3os tool publish <dir> | earnings (hosted tools, slice A). A hosted tool is a pack whose actions run in a fresh
2
- // microVM; packages/packs/src/cli/tool.ts builds a tool's directory into <dir>/dist/ (the archive, the signed
3
- // manifest, the pack bundle). `publish` uploads that build: HEAD the archive, PUT it when the registry does not have
4
- // it, then POST the pack; it prints the version, the exact pin of each action and one `b3os action call` line.
5
- // `earnings` reads a namespace's earnings line: calls, gross, B3OS's cut at the rate in force and why, net.
6
- import { createHash } from "node:crypto";
7
- import { existsSync, readFileSync } from "node:fs";
8
- import { join } from "node:path";
1
+ // b3os tool: hosted tools, from a binary on disk to a first call (slice A's publish of a signed build, slice B's
2
+ // private publishing). A hosted tool is a pack whose actions run in a fresh microVM, one per call.
3
+ //
4
+ // init <dir> --from-binary <path> [--call '<key>: <command line>']...
5
+ // writes a tool directory around the binary: b3pack.json in your organization's own namespace
6
+ // (org.<host-safe org id>, from GET /v1/keys/current), tool/bin/<binary>, the stock wrapper tool/bin/b3os-run
7
+ // (assets/b3os-run.py), tool/calls.json and fixtures/<key>.json. It refuses a macOS binary and an ELF for
8
+ // another machine, and warns about a dynamically linked one (src/tool/elf.ts).
9
+ // dev [dir] [--input <json>] [--action <key>]
10
+ // packs and publishes <x.y.z>-dev.<unix seconds> (an org-private dev version: it replaces the pack's earlier
11
+ // one and counts toward no limit), waits for the node, calls once and prints the answer or the error with
12
+ // the tool's stderr.
13
+ // publish [dir] [--format tar|tar.gz] [--no-call]
14
+ // a signed dist/ (slice A, packages/packs/src/cli/tool.ts build) is uploaded as it is. Otherwise it packs
15
+ // (src/tool/archive.ts: tar up to 32 MiB, else tar.gz), checks the binaries, the strict ustar walk
16
+ // (src/tool/ustar.ts, the node's rules) and the schema caps, prints the sizes and the predicted start
17
+ // (src/tool/predict.ts), uploads the archive and the pack, waits until describe answers for the exact
18
+ // version (up to 120 s), calls the first fixture once with an Idempotency-Key, and prints the pins, a curl
19
+ // line and the MCP URL.
20
+ // rm <pack>[@<version>], yank <pin> [--undo], health [--pack P] [--hours N], earnings
21
+ //
22
+ // Publishing needs a key that holds actions:tools:publish by name (* and actions:* do not grant it) and
23
+ // actions:write; the first call needs actions:run.
24
+ import { createHash, randomUUID } from "node:crypto";
25
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
26
+ import { basename, join, resolve } from "node:path";
27
+ import { createInterface } from "node:readline/promises";
9
28
  import { B3OSError } from "@b3os/sdk";
10
- import { CliError, EXIT, parse, splitSub, UsageError } from "../ctx.js";
11
- import { showUsage, unknownSub } from "./_common.js";
29
+ import { CliError, EXIT, exitCodeFor, intFlag, parse, splitSub, UsageError } from "../ctx.js";
30
+ import { archiveEntries, bundleFiles, defaultFormat, writeArchive, writeBundle, } from "../tool/archive.js";
31
+ import { callsFile, fixtureFor, manifestFor, parseCall, TemplateError, wrapperBytes, } from "../tool/calls.js";
32
+ import { archiveCapProblems, manifestCapProblems } from "../tool/checks.js";
33
+ import { describeProgram, ProgramRefused, programKind, programWarning } from "../tool/elf.js";
34
+ import { START_BASIS, startEstimateMs } from "../tool/predict.js";
35
+ import { checkExtent } from "../tool/ustar.js";
36
+ import { inputFlag, showUsage, unknownSub } from "./_common.js";
12
37
  const TOOL_USAGE = `usage: b3os tool <command>
13
- publish <dir> upload <dir>/dist/ (archive, then pack); print the pins
38
+ init <dir> --from-binary <path> [--call '<key>: <command line>']...
39
+ a tool directory around a binary, in your organization's namespace
40
+ dev [dir] [--input JSON] [--action KEY] publish a dev version, wait for the node, call it once
41
+ publish [dir] [--format tar|tar.gz] [--no-call] pack, check, publish, wait, call the first fixture; print the pins
42
+ rm <pack>[@<version>] delete an org-private tool, or one version of it
43
+ yank <pack>@<version> [--undo] yank a version: @<major> skips it, the exact pin still resolves
44
+ health [--namespace NS] [--pack P] [--hours N] how a namespace's tools answered, per hour
14
45
  earnings [--namespace NS] [--period YYYY-MM] a namespace's earnings line, with B3OS's rate and why
15
46
 
16
- Build first: node packages/packs/src/cli/tool.ts build <dir> --kid <namespace>#dev-<label>. Publishing a hosted
17
- tool needs a key with actions:tools:publish (named exactly: * and actions:* do not grant it) and actions:write.`;
47
+ In --call, {x} is the string input x, {x:int} an integer, {x:file} (or {x:file=application/pdf}) an input file's
48
+ path and {out:<file>} an output file the binary writes; without {out:...} its stdout is the output. Publishing needs
49
+ a key with actions:tools:publish (named exactly: * and actions:* do not grant it) and actions:write.`;
18
50
  /** `b3os tool`'s options, each named after the request field it sets. */
19
51
  export const TOOL_OPTIONS = {
20
- namespace: { type: "string", fields: ["platformGetPublisherEarnings:namespace"] },
52
+ namespace: {
53
+ type: "string",
54
+ fields: ["platformGetPublisherEarnings:namespace", "platformGetPublisherHealth:namespace"],
55
+ },
21
56
  period: { type: "string", fields: ["platformGetPublisherEarnings:period"] },
57
+ pack: { type: "string", fields: ["platformGetPublisherHealth:pack"] },
58
+ hours: { type: "string", fields: ["platformGetPublisherHealth:hours"] },
59
+ input: { type: "string", fields: ["actionsCall:input"] },
60
+ action: { type: "string" },
61
+ "from-binary": { type: "string" },
62
+ call: { type: "string", multiple: true },
63
+ format: { type: "string" },
64
+ "no-call": { type: "boolean" },
65
+ undo: { type: "boolean" },
22
66
  };
67
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
23
68
  /** USD from micro-USD: two decimals, more only when the amount has them ($1.23, $0.002, $0.000001). */
24
69
  export function usd(micro) {
25
70
  const s = (micro / 1_000_000).toFixed(6).replace(/0{1,4}$/, "");
@@ -71,22 +116,10 @@ function callLine(dir, m) {
71
116
  }
72
117
  return `b3os action call ${m.pack}/${a.key}@${m.version} --input ${quoted(JSON.stringify(input))}`;
73
118
  }
74
- async function publish(ctx, dir) {
119
+ /** Slice A's path: a signed dist/ (packages/packs/src/cli/tool.ts build) uploaded as it is. */
120
+ async function publishBuilt(ctx, dir) {
75
121
  const dist = join(dir, "dist");
76
122
  const manifestPath = join(dist, "b3pack.json");
77
- if (!existsSync(manifestPath)) {
78
- if (existsSync(join(dist, "release-request.json")))
79
- throw new CliError(`${dist} holds a release request, not a signed build: nothing to publish`, {
80
- code: "not_built",
81
- exit: EXIT.USAGE,
82
- hint: "the release key's holder signs the request's message; or build with a dev key id on a dev registry",
83
- });
84
- throw new CliError(`${dist} has no build`, {
85
- code: "not_built",
86
- exit: EXIT.USAGE,
87
- hint: `node packages/packs/src/cli/tool.ts build ${dir} --kid <namespace>#dev-<label>`,
88
- });
89
- }
90
123
  const m = JSON.parse(readFileSync(manifestPath, "utf8"));
91
124
  const ar = m.tool?.bundle?.archive;
92
125
  if (!ar)
@@ -106,20 +139,9 @@ async function publish(ctx, dir) {
106
139
  hint: "build again: the archive and the manifest come from one build",
107
140
  });
108
141
  const bundle = readFileSync(join(dist, "bundle.tar.gz"));
109
- const b3 = ctx.client();
110
142
  const digest = `sha256:${ar.sha256}`;
111
- let uploaded = false;
112
- try {
113
- await b3.actions.headRegistryBlob(digest);
114
- }
115
- catch (e) {
116
- if (!(e instanceof B3OSError && e.status === 404))
117
- throw e;
118
- ctx.info(`uploading the archive ${digest} (${archive.length} bytes)`);
119
- await b3.actions.putRegistryBlob(digest, archive);
120
- uploaded = true;
121
- }
122
- const v = await b3.actions.publishPack(bundle);
143
+ const uploaded = await uploadArchive(ctx, digest, archive);
144
+ const v = await ctx.client().actions.publishPack(bundle);
123
145
  const pins = m.actions.map((a) => `${m.pack}/${a.key}@${m.version}`);
124
146
  const call = callLine(dir, m);
125
147
  ctx.result({ ...v, archive: { digest, bytes: ar.bytes, uploaded }, pins, call }, () => {
@@ -131,6 +153,501 @@ async function publish(ctx, dir) {
131
153
  });
132
154
  return EXIT.OK;
133
155
  }
156
+ /** HEAD the archive; PUT it when the registry does not have it. True when it was uploaded. */
157
+ async function uploadArchive(ctx, digest, archive) {
158
+ const b3 = ctx.client();
159
+ try {
160
+ await b3.actions.headRegistryBlob(digest);
161
+ return false;
162
+ }
163
+ catch (e) {
164
+ if (!(e instanceof B3OSError && e.status === 404))
165
+ throw e;
166
+ }
167
+ ctx.info(`uploading the archive ${digest} (${archive.length} bytes)`);
168
+ await b3.actions.putRegistryBlob(digest, archive);
169
+ return true;
170
+ }
171
+ const MIB = 1024 * 1024;
172
+ /** A size as the archive line prints it: bytes, KiB or MiB to a tenth. */
173
+ const mib = (n) => n < 1024 ? `${n} bytes` : n < MIB ? `${(n / 1024).toFixed(1)} KiB` : `${(n / MIB).toFixed(1)} MiB`;
174
+ /** Every refusal of a tool directory before upload, as one error listing them. */
175
+ function refused(what, problems) {
176
+ return new CliError(`${what}: ${problems.length} problem${problems.length === 1 ? "" : "s"}\n ${problems.join("\n ")}`, {
177
+ code: "tool_invalid",
178
+ exit: EXIT.INVALID,
179
+ });
180
+ }
181
+ /** The program files a tool runs: each vm action's cmd[0] under tool/, and the wrapper's binary (tool/calls.json). */
182
+ function programs(dir, m) {
183
+ const out = new Map();
184
+ const actions = Array.isArray(m.actions) ? m.actions : [];
185
+ actions.forEach((a, i) => {
186
+ const x = isObj(a) ? a : {};
187
+ const cmd = isObj(x.impl) && Array.isArray(x.impl.cmd) ? x.impl.cmd : [];
188
+ const c0 = typeof cmd[0] === "string" ? cmd[0] : "";
189
+ if (!c0.startsWith("/tool/"))
190
+ return;
191
+ const rel = c0.slice("/tool/".length);
192
+ out.set(rel, {
193
+ path: join(dir, "tool", rel),
194
+ shown: `tool/${rel}`,
195
+ at: `actions[${i}] (${String(x.key)}).impl.cmd[0]`,
196
+ });
197
+ });
198
+ const calls = join(dir, "tool", "calls.json");
199
+ if (existsSync(calls)) {
200
+ const bin = JSON.parse(readFileSync(calls, "utf8")).bin;
201
+ if (typeof bin === "string")
202
+ out.set(bin, { path: join(dir, "tool", bin), shown: `tool/${bin}`, at: "tool/calls.json bin" });
203
+ }
204
+ return [...out.values()];
205
+ }
206
+ /** Packs `dir` (with `version` in place of the manifest's, for a dev version) and runs the local checks. */
207
+ export async function packTool(dir, opts = {}) {
208
+ const path = join(dir, "b3pack.json");
209
+ if (!existsSync(path))
210
+ throw new CliError(`${dir} has no b3pack.json`, {
211
+ code: "not_a_tool",
212
+ exit: EXIT.USAGE,
213
+ hint: "b3os tool init <dir> --from-binary <path> makes one",
214
+ });
215
+ let m;
216
+ try {
217
+ m = JSON.parse(readFileSync(path, "utf8"));
218
+ }
219
+ catch (e) {
220
+ throw new CliError(`${path} is not JSON: ${e.message}`, { code: "tool_invalid", exit: EXIT.INVALID });
221
+ }
222
+ const pack = String(m.pack ?? "");
223
+ if (opts.version)
224
+ m.version = opts.version;
225
+ if (!isObj(m.tool))
226
+ throw new CliError(`${path} has no tool block: not a hosted tool`, { code: "not_a_tool", exit: EXIT.INVALID });
227
+ if (pack.startsWith("org.") && m.signature !== undefined)
228
+ throw refused(`${pack}@${String(m.version)}`, [
229
+ "an org-private version is signed by the registry; leave signature out",
230
+ ]);
231
+ let entries;
232
+ try {
233
+ entries = archiveEntries(join(dir, "tool"));
234
+ }
235
+ catch (e) {
236
+ throw new CliError(e.message, { code: "tool_invalid", exit: EXIT.INVALID });
237
+ }
238
+ const format = opts.format ?? defaultFormat(entries);
239
+ const built = writeArchive(entries, format);
240
+ const tool = m.tool;
241
+ tool.bundle = { ...(isObj(tool.bundle) ? tool.bundle : {}), archive: built.archive };
242
+ const problems = [...archiveCapProblems(built.archive), ...manifestCapProblems(m)];
243
+ const warnings = [];
244
+ for (const p of programs(dir, m)) {
245
+ if (!existsSync(p.path)) {
246
+ problems.push(`${p.at}: ${p.shown} is not a file of tool/`);
247
+ continue;
248
+ }
249
+ try {
250
+ const w = programWarning(programKind(p.path, p.shown), p.shown);
251
+ if (w)
252
+ warnings.push(w);
253
+ }
254
+ catch (e) {
255
+ if (e instanceof ProgramRefused)
256
+ problems.push(e.message);
257
+ else
258
+ throw e;
259
+ }
260
+ }
261
+ const walk = await checkExtent(built.bytes, format, built.archive.unpackedBytes, built.archive.entries);
262
+ if (walk)
263
+ problems.push(`the archive: ${walk}`);
264
+ if (problems.length)
265
+ throw refused(`${pack}@${String(m.version)}`, problems);
266
+ const notices = typeof tool.notices === "string" ? tool.notices : undefined;
267
+ const files = bundleFiles(dir, notices);
268
+ files.set("b3pack.json", Buffer.from(`${JSON.stringify(m, null, 2)}\n`, "utf8"));
269
+ return {
270
+ manifest: m,
271
+ archive: built.bytes,
272
+ numbers: built.archive,
273
+ bundle: writeBundle(files),
274
+ startMs: startEstimateMs(built.archive.bytes, format),
275
+ warnings,
276
+ };
277
+ }
278
+ /** The archive line: "archive 12.4 MiB tar, 12.4 MiB unpacked, 6 entries; start about 45 ms (warm pool, ...)". */
279
+ export function archiveLine(p) {
280
+ const n = p.numbers;
281
+ return `archive ${mib(n.bytes)} ${n.format}, ${mib(n.unpackedBytes)} unpacked, ${n.entries} entries; start about ${Math.round(p.startMs)} ms (${START_BASIS})`;
282
+ }
283
+ /** How long `wait` polls describe for the exact version, and how often. */
284
+ export const WAIT = { totalMs: 120_000, everyMs: 250 };
285
+ /** Polls describe of `ref` until the node answers for it; the milliseconds that took. */
286
+ async function waitCallable(ctx, ref, since) {
287
+ const b3 = ctx.client();
288
+ for (;;) {
289
+ try {
290
+ await b3.actions.describe({ ref });
291
+ return Date.now() - since;
292
+ }
293
+ catch (e) {
294
+ if (!(e instanceof B3OSError && e.status === 404))
295
+ throw e;
296
+ }
297
+ if (Date.now() - since > WAIT.totalMs)
298
+ throw new CliError(`${ref} is published, but no node answered for it within ${WAIT.totalMs / 1000} s`, {
299
+ code: "not_callable",
300
+ exit: EXIT.TIMEOUT,
301
+ hint: "a node installs a new version at its next registry sync; try b3os action describe in a minute",
302
+ });
303
+ await new Promise((r) => setTimeout(r, WAIT.everyMs));
304
+ }
305
+ }
306
+ /** The first action that has a fixture file, with that fixture's input; else the first action with none. */
307
+ function firstFixture(dir, m) {
308
+ const actions = (Array.isArray(m.actions) ? m.actions : []).filter(isObj);
309
+ for (const a of actions)
310
+ for (const ex of Array.isArray(a.examples) ? a.examples : []) {
311
+ if (!isObj(ex))
312
+ continue;
313
+ if (isObj(ex.input))
314
+ return { key: String(a.key), input: ex.input };
315
+ if (typeof ex.fixture === "string" && existsSync(join(dir, ex.fixture))) {
316
+ const f = JSON.parse(readFileSync(join(dir, ex.fixture), "utf8"));
317
+ return { key: String(a.key), input: isObj(f.input) ? f.input : {} };
318
+ }
319
+ }
320
+ const a = actions[0];
321
+ return a ? { key: String(a.key), input: undefined } : undefined;
322
+ }
323
+ /** Calls `ref` once with an Idempotency-Key; a refusal is returned, not thrown. */
324
+ async function callOnce(ctx, ref, input) {
325
+ const t0 = Date.now();
326
+ try {
327
+ const r = await ctx.client().actions.call({ ref, input }, { idempotencyKey: randomUUID() });
328
+ return { ref, status: 200, ms: Date.now() - t0, ...(r.cost ? { cost: r.cost } : {}), output: r.output };
329
+ }
330
+ catch (e) {
331
+ if (!(e instanceof B3OSError) || e.status === null)
332
+ throw e;
333
+ const p = e.problem ?? {};
334
+ return {
335
+ ref,
336
+ failure: e,
337
+ status: e.status,
338
+ ms: Date.now() - t0,
339
+ error: {
340
+ code: e.code,
341
+ detail: e.detail,
342
+ ...(typeof p.reason === "string" ? { reason: p.reason } : {}),
343
+ ...(typeof p.stderr === "string" ? { stderr: p.stderr } : {}),
344
+ },
345
+ };
346
+ }
347
+ }
348
+ function firstCallLines(c, label) {
349
+ if (!c.error)
350
+ return [`${label} 200 in ${c.ms} ms, cost ${usd(c.cost?.total ?? 0)}`];
351
+ const why = c.error.reason ? ` (${c.error.reason})` : "";
352
+ const lines = [`${label} ${c.status} ${c.error.code}${why} in ${c.ms} ms: ${c.error.detail}`];
353
+ if (c.error.stderr)
354
+ lines.push("stderr:", ...c.error.stderr
355
+ .replace(/\n$/, "")
356
+ .split("\n")
357
+ .map((l) => ` ${l}`));
358
+ return lines;
359
+ }
360
+ /** The API host the lines print, without a trailing slash. */
361
+ const apiBase = (ctx) => ctx.credential().baseUrl.replace(/\/+$/, "");
362
+ /** The step clock --json reports (the timed run records each step's elapsed_ms). */
363
+ class Steps {
364
+ t0 = Date.now();
365
+ last = this.t0;
366
+ list = [];
367
+ mark(step) {
368
+ const now = Date.now();
369
+ this.list.push({ step, elapsed_ms: now - this.last });
370
+ this.last = now;
371
+ }
372
+ }
373
+ /** Uploads a packed tool and publishes it; the version object. */
374
+ async function upload(ctx, p, steps) {
375
+ const digest = `sha256:${p.numbers.sha256}`;
376
+ const uploaded = await uploadArchive(ctx, digest, p.archive);
377
+ steps.mark("upload");
378
+ const v = await ctx.client().actions.publishPack(p.bundle);
379
+ steps.mark("publish");
380
+ return { v, digest, uploaded };
381
+ }
382
+ async function publish(ctx, dir, values) {
383
+ const format = values.format;
384
+ if (format !== undefined && format !== "tar" && format !== "tar.gz")
385
+ throw new UsageError("--format is tar or tar.gz");
386
+ if (existsSync(join(dir, "dist", "b3pack.json"))) {
387
+ if (format !== undefined)
388
+ throw new UsageError("--format is for a tool the CLI packs; dist/ is already built");
389
+ return publishBuilt(ctx, dir);
390
+ }
391
+ if (existsSync(join(dir, "dist", "release-request.json")))
392
+ throw new CliError(`${join(dir, "dist")} holds a release request, not a signed build: nothing to publish`, {
393
+ code: "not_built",
394
+ exit: EXIT.USAGE,
395
+ hint: "the release key's holder signs the request's message; or build with a dev key id on a dev registry",
396
+ });
397
+ const m0 = existsSync(join(dir, "b3pack.json"))
398
+ ? JSON.parse(readFileSync(join(dir, "b3pack.json"), "utf8"))
399
+ : undefined;
400
+ if (!m0)
401
+ throw new CliError(`${dir} has no build and no b3pack.json`, {
402
+ code: "not_built",
403
+ exit: EXIT.USAGE,
404
+ hint: `b3os tool init ${dir} --from-binary <path>, or node packages/packs/src/cli/tool.ts build ${dir} --kid <namespace>#dev-<label>`,
405
+ });
406
+ if (!String(m0.pack ?? "").startsWith("org."))
407
+ throw new CliError(`${String(m0.pack)} is a listed namespace: its versions are signed with its publisher key`, {
408
+ code: "not_built",
409
+ exit: EXIT.USAGE,
410
+ hint: `node packages/packs/src/cli/tool.ts build ${dir} --kid <namespace>#dev-<label>, then b3os tool publish ${dir}`,
411
+ });
412
+ const steps = new Steps();
413
+ const p = await packTool(dir, format ? { format: format } : {});
414
+ steps.mark("pack");
415
+ for (const w of p.warnings)
416
+ ctx.warn(`warning: ${w}`);
417
+ if (!ctx.json)
418
+ ctx.out(archiveLine(p));
419
+ return publishAndCall(ctx, dir, p, steps, { call: !values["no-call"], label: "first call" });
420
+ }
421
+ /** Publishes `p`, waits for the node, calls once, prints the lines; shared by publish and dev. */
422
+ async function publishAndCall(ctx, dir, p, steps, o) {
423
+ const { v, digest, uploaded } = await upload(ctx, p, steps);
424
+ if (!ctx.json)
425
+ ctx.out(`published ${v.pack}@${v.version} (signed ${v.signature.kid})`);
426
+ const m = p.manifest;
427
+ const keys = (Array.isArray(m.actions) ? m.actions : []).filter(isObj).map((a) => String(a.key));
428
+ const fixture = firstFixture(dir, m);
429
+ const key = o.action ?? fixture?.key ?? keys[0] ?? "";
430
+ if (o.action && !keys.includes(o.action))
431
+ throw new UsageError(`--action ${o.action}: ${v.pack} has ${keys.join(", ")}`);
432
+ const input = o.input ?? (key === fixture?.key ? fixture?.input : undefined) ?? {};
433
+ const ref = `${v.pack}/${key}@${v.version}`;
434
+ const afterMs = await waitCallable(ctx, ref, Date.now());
435
+ steps.mark("callable");
436
+ let first;
437
+ if (o.call) {
438
+ first = await callOnce(ctx, ref, input);
439
+ steps.mark("call");
440
+ }
441
+ const base = apiBase(ctx);
442
+ const pins = keys.map((k) => `${v.pack}/${k}@${v.version}`);
443
+ const curl = `curl ${base}/v1/actions/call -H "Authorization: Bearer $B3OS_API_KEY" -H "Content-Type: application/json" -d ${quoted(JSON.stringify({ ref, input }))}`;
444
+ const mcp = `${base}/mcp?packs=${v.pack}`;
445
+ ctx.result({
446
+ ...v,
447
+ archive: { digest, ...p.numbers, uploaded },
448
+ start_estimate_ms: p.startMs,
449
+ callable_after_ms: afterMs,
450
+ first_call: first ? { ...first, failure: undefined } : null,
451
+ pins,
452
+ curl,
453
+ mcp,
454
+ steps: steps.list,
455
+ elapsed_ms: Date.now() - steps.t0,
456
+ }, () => {
457
+ const lines = first ? firstCallLines(first, o.label) : [];
458
+ ctx.out(`callable on the node after ${(afterMs / 1000).toFixed(1)} s${lines[0] ? `; ${lines[0]}` : ""}`);
459
+ for (const l of lines.slice(1))
460
+ ctx.out(l);
461
+ if (o.showOutput && first && !first.error)
462
+ ctx.out(`output ${JSON.stringify(first.output ?? null)}`);
463
+ for (const pin of pins)
464
+ ctx.out(`pin ${pin}`);
465
+ ctx.out(`curl ${curl.slice(5)}`);
466
+ ctx.out(`mcp ${mcp}`);
467
+ });
468
+ return first?.failure ? exitCodeFor(first.failure) : EXIT.OK;
469
+ }
470
+ /** The x.y.z of a version, and the dev version of it published now. */
471
+ export function devVersion(version, nowMs = Date.now()) {
472
+ const core = /^(\d+\.\d+\.\d+)/.exec(version)?.[1];
473
+ if (!core)
474
+ throw new UsageError(`version ${version} is not x.y.z`);
475
+ return `${core}-dev.${Math.floor(nowMs / 1000)}`;
476
+ }
477
+ async function dev(ctx, dir, values) {
478
+ const path = join(dir, "b3pack.json");
479
+ if (!existsSync(path))
480
+ throw new CliError(`${dir} has no b3pack.json`, {
481
+ code: "not_a_tool",
482
+ exit: EXIT.USAGE,
483
+ hint: "b3os tool init <dir> --from-binary <path> makes one",
484
+ });
485
+ const m0 = JSON.parse(readFileSync(path, "utf8"));
486
+ const pack = String(m0.pack ?? "");
487
+ if (!pack.startsWith("org."))
488
+ throw new UsageError(`tool dev publishes dev versions, which only org-private tools have; ${pack} is not in an org. namespace`);
489
+ const input = inputFlag(values.input);
490
+ const action = values.action;
491
+ const keys = (Array.isArray(m0.actions) ? m0.actions : []).filter(isObj).map((a) => String(a.key));
492
+ if (action && !keys.includes(action))
493
+ throw new UsageError(`--action ${action}: ${pack} has ${keys.join(", ")}`);
494
+ const steps = new Steps();
495
+ const p = await packTool(dir, { version: devVersion(String(m0.version ?? "")) });
496
+ steps.mark("pack");
497
+ for (const w of p.warnings)
498
+ ctx.warn(`warning: ${w}`);
499
+ if (!ctx.json)
500
+ ctx.out(archiveLine(p));
501
+ return publishAndCall(ctx, dir, p, steps, {
502
+ call: true,
503
+ label: "call",
504
+ showOutput: true,
505
+ ...(input ? { input } : {}),
506
+ ...(action ? { action } : {}),
507
+ });
508
+ }
509
+ /** The organization's own namespace, org.org-<id>, from the calling key. */
510
+ export function orgNamespaceOf(orgId) {
511
+ return /^org_[0-9a-z]{1,40}$/.test(orgId) ? `org.org-${orgId.slice(4)}` : null;
512
+ }
513
+ const PACK_NAME = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
514
+ const BIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
515
+ /** Asks for the actions on a terminal: one `<key>: <command line>` per line, an empty line to finish. */
516
+ async function askCalls(ctx, bin) {
517
+ const rl = createInterface({ input: ctx.io.stdin, output: process.stderr });
518
+ const out = [];
519
+ try {
520
+ ctx.info(`One action per line, as <key>: <command line> (for example convert: ${bin} {doc:file} -o {out:out.html}).`);
521
+ for (;;) {
522
+ const line = (await rl.question(out.length ? "next action (empty to finish): " : "action: ")).trim();
523
+ if (!line)
524
+ break;
525
+ out.push(line);
526
+ }
527
+ }
528
+ finally {
529
+ rl.close();
530
+ }
531
+ return out;
532
+ }
533
+ async function init(ctx, dir, values) {
534
+ const from = values["from-binary"];
535
+ if (!from)
536
+ throw new UsageError("tool init needs --from-binary <path>: the program the tool runs");
537
+ const target = resolve(dir);
538
+ if (existsSync(target) && readdirSync(target).length)
539
+ throw new UsageError(`${dir} exists and is not empty; init writes a new directory`);
540
+ const name = basename(target);
541
+ if (!PACK_NAME.test(name))
542
+ throw new UsageError(`${name} is not a pack name: name the directory in kebab-case (pandoc, my-tool)`);
543
+ if (!existsSync(from))
544
+ throw new UsageError(`can't open ${from}: no such file`);
545
+ const bin = basename(from);
546
+ if (!BIN_NAME.test(bin) || bin === "b3os-run" || bin === "calls.json")
547
+ throw new UsageError(`${bin}: name the binary with letters, digits, ".", "_" or "-" (not b3os-run)`);
548
+ let kind;
549
+ try {
550
+ kind = programKind(from, from);
551
+ }
552
+ catch (e) {
553
+ if (e instanceof ProgramRefused)
554
+ throw new CliError(e.message, { code: "binary_refused", exit: EXIT.INVALID });
555
+ throw e;
556
+ }
557
+ const given = values.call ?? [];
558
+ const specs = given.length ? given : ctx.isTTY ? await askCalls(ctx, bin) : [];
559
+ if (!specs.length)
560
+ throw new UsageError(`tool init needs at least one --call '<key>: ${bin} <arguments>'`, "for example --call 'convert: pandoc {doc:file} -o {out:out.html}'");
561
+ const calls = [];
562
+ for (const s of specs) {
563
+ let c;
564
+ try {
565
+ c = parseCall(s, bin);
566
+ }
567
+ catch (e) {
568
+ if (e instanceof TemplateError)
569
+ throw new UsageError(e.message);
570
+ throw e;
571
+ }
572
+ if (calls.some((x) => x.key === c.key))
573
+ throw new UsageError(`--call ${c.key} is given twice`);
574
+ calls.push(c);
575
+ }
576
+ let namespace = values.namespace;
577
+ if (!namespace) {
578
+ const me = await ctx.client().keys.getCurrentKey();
579
+ const ns = orgNamespaceOf(me.org_id);
580
+ if (!ns)
581
+ throw new CliError(`the calling key's organization ${me.org_id} has no org. namespace`, {
582
+ code: "no_namespace",
583
+ exit: EXIT.ERROR,
584
+ });
585
+ namespace = ns;
586
+ }
587
+ else if (!namespace.startsWith("org."))
588
+ throw new UsageError(`--namespace ${namespace}: init writes org-private tools, in your organization's org. namespace`);
589
+ mkdirSync(join(target, "tool", "bin"), { recursive: true });
590
+ mkdirSync(join(target, "fixtures"), { recursive: true });
591
+ const manifest = manifestFor(namespace, name, bin, calls);
592
+ writeFileSync(join(target, "b3pack.json"), `${JSON.stringify(manifest, null, 2)}\n`);
593
+ copyFileSync(from, join(target, "tool", "bin", bin));
594
+ chmodSync(join(target, "tool", "bin", bin), 0o755);
595
+ writeFileSync(join(target, "tool", "bin", "b3os-run"), wrapperBytes());
596
+ chmodSync(join(target, "tool", "bin", "b3os-run"), 0o755);
597
+ writeFileSync(join(target, "tool", "calls.json"), `${JSON.stringify(callsFile(bin, calls), null, 2)}\n`);
598
+ for (const c of calls)
599
+ writeFileSync(join(target, "fixtures", `${c.key}.json`), `${JSON.stringify(fixtureFor(c), null, 2)}\n`);
600
+ const warning = programWarning(kind, `tool/bin/${bin}`);
601
+ const keys = calls.map((c) => c.key);
602
+ ctx.result({
603
+ dir: target,
604
+ pack: manifest.pack,
605
+ actions: keys,
606
+ binary: { path: `tool/bin/${bin}`, ...kind },
607
+ warnings: warning ? [warning] : [],
608
+ }, () => {
609
+ const shown = dir.startsWith("/") || dir.startsWith(".") ? dir : `./${dir}`;
610
+ ctx.out(`wrote ${shown} (${keys.length} action${keys.length === 1 ? "" : "s"}: ${keys.join(", ")}); tool/bin/${bin} is ${describeProgram(kind)}`);
611
+ if (warning)
612
+ ctx.warn(`warning: ${warning}`);
613
+ ctx.out(`next put real input in fixtures/${keys[0]}.json, set license and tool.upstream in b3pack.json, then b3os tool dev ${shown}`);
614
+ });
615
+ return EXIT.OK;
616
+ }
617
+ /** `<ns>/<name>` and an optional version from `<ns>/<name>[@<v>]` (or an action pin `<ns>/<name>/<action>@<v>`). */
618
+ export function parsePackRef(ref) {
619
+ const m = /^([a-z0-9][a-z0-9.-]*\.[a-z0-9.-]*[a-z0-9])\/([a-z0-9][a-z0-9-]*)(?:\/[a-z][a-z0-9-]*)?(?:@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?))?$/.exec(ref);
620
+ if (!m)
621
+ return null;
622
+ return { namespace: m[1], name: m[2], ...(m[3] ? { version: m[3] } : {}) };
623
+ }
624
+ async function rm(ctx, ref) {
625
+ const r = ref ? parsePackRef(ref) : null;
626
+ if (!r)
627
+ throw new UsageError("tool rm takes <pack> or <pack>@<version>: org.org-01m9q.../pandoc@1.0.0");
628
+ const pack = `${r.namespace}/${r.name}`;
629
+ const what = r.version ? `${pack}@${r.version}` : `${pack} and every version of it`;
630
+ if (!(await ctx.confirm(`Delete ${what}? Calls pinned to it stop working.`)))
631
+ return EXIT.ERROR;
632
+ const b3 = ctx.client();
633
+ if (r.version)
634
+ await b3.actions.deleteRegistryPackVersion(r.namespace, r.name, r.version);
635
+ else
636
+ await b3.actions.deleteRegistryPack(r.namespace, r.name);
637
+ ctx.result({ deleted: r.version ? `${pack}@${r.version}` : pack }, () => ctx.out(`deleted ${r.version ? `${pack}@${r.version}` : pack}`));
638
+ return EXIT.OK;
639
+ }
640
+ async function yank(ctx, ref, undo) {
641
+ const r = ref ? parsePackRef(ref) : null;
642
+ if (!r?.version)
643
+ throw new UsageError("tool yank takes an exact pin, <pack>@<version>: org.org-01m9q.../pandoc@1.0.0");
644
+ const v = await ctx.client().actions.yankRegistryPackVersion(r.namespace, r.name, r.version, { yanked: !undo });
645
+ const major = r.version.split(".")[0];
646
+ ctx.result(v, () => ctx.out(undo
647
+ ? `restored ${v.pack}@${v.version}: @${major} and ranges select it again`
648
+ : `yanked ${v.pack}@${v.version}: @${major} and ranges skip it; the exact pin still resolves`));
649
+ return EXIT.OK;
650
+ }
134
651
  /** The namespace of the tool in the current directory (./dist/b3pack.json or ./b3pack.json), if there is one. */
135
652
  function localNamespace() {
136
653
  for (const p of [join("dist", "b3pack.json"), "b3pack.json"]) {
@@ -165,19 +682,90 @@ async function earnings(ctx, values) {
165
682
  });
166
683
  return EXIT.OK;
167
684
  }
685
+ const count = (o) => Object.entries(o)
686
+ .filter(([, n]) => n > 0)
687
+ .map(([k, n]) => `${k} ${n}`)
688
+ .join(", ") || "-";
689
+ /** The health view as lines: one per hour and version, newest first, then the alert. */
690
+ export function healthText(h) {
691
+ const rows = [...h.rows].sort((a, b) => a.hour < b.hour ? 1 : a.hour > b.hour ? -1 : a.version < b.version ? -1 : 1);
692
+ const lines = [];
693
+ if (!rows.length)
694
+ lines.push(`${h.namespace}: no calls whose command ran from ${h.from} to ${h.to}`);
695
+ else {
696
+ const table = rows.map((r) => [
697
+ r.hour.replace(/:00(\.000)?Z$/, "Z"),
698
+ `${r.pack.split("/")[1] ?? r.pack}@${r.version}`,
699
+ String(r.calls),
700
+ String(r.ok),
701
+ String(r.tool_failed),
702
+ String(r.timed_out),
703
+ `${r.run_ms.p50}/${r.run_ms.p95}`,
704
+ [
705
+ count(r.reasons),
706
+ r.tool_codes && Object.values(r.tool_codes).some((n) => n > 0) ? `codes: ${count(r.tool_codes)}` : "",
707
+ ]
708
+ .filter((x) => x && x !== "-")
709
+ .join("; ") || "-",
710
+ ]);
711
+ const head = ["HOUR", "VERSION", "CALLS", "OK", "FAILED", "TIMED_OUT", "RUN_MS_P50/P95", "WHY"];
712
+ const widths = head.map((c, i) => Math.max(c.length, ...table.map((r) => r[i].length)));
713
+ const line = (vals) => vals
714
+ .map((v, i) => (i === vals.length - 1 ? v : v.padEnd(widths[i] ?? 0)))
715
+ .join(" ")
716
+ .trimEnd();
717
+ lines.push(line(head), ...table.map(line));
718
+ }
719
+ if (h.alert)
720
+ lines.push(h.alert.over_5pct
721
+ ? `alert: ${pct(h.alert.failure_rate)} of calls failed in the hour from ${h.alert.hour}, over 5%`
722
+ : `latest hour ${h.alert.hour}: ${pct(h.alert.failure_rate)} failed`);
723
+ return lines;
724
+ }
725
+ async function health(ctx, values) {
726
+ const ns = values.namespace ?? localNamespace();
727
+ if (!ns)
728
+ throw new UsageError("name the publisher namespace: b3os tool health --namespace <namespace>");
729
+ const hours = intFlag(values.hours, "--hours");
730
+ if (hours !== undefined && (hours < 1 || hours > 168))
731
+ throw new UsageError("--hours is 1 to 168");
732
+ let pack = values.pack;
733
+ if (pack && !pack.includes("/"))
734
+ pack = `${ns}/${pack}`;
735
+ const h = await ctx.client().request({
736
+ method: "GET",
737
+ path: `/v1/actions/publishers/${encodeURIComponent(ns)}/health`,
738
+ query: { ...(pack ? { pack } : {}), ...(hours !== undefined ? { hours: String(hours) } : {}) },
739
+ edge: true,
740
+ });
741
+ ctx.result(h, () => {
742
+ for (const l of healthText(h))
743
+ ctx.out(l);
744
+ });
745
+ return EXIT.OK;
746
+ }
168
747
  export async function tool(ctx, argv) {
169
748
  const [sub, rest] = splitSub(argv);
170
749
  const a = parse(rest, TOOL_OPTIONS);
171
750
  ctx.applyGlobals(a.values);
172
751
  if (!sub || a.values.help)
173
752
  return showUsage(ctx, TOOL_USAGE, sub, a.values.help);
753
+ const dir = a.positionals[0];
174
754
  switch (sub) {
175
- case "publish": {
176
- const dir = a.positionals[0];
755
+ case "init":
177
756
  if (!dir)
178
- throw new UsageError("tool publish needs the tool's directory (it reads <dir>/dist/)");
179
- return publish(ctx, dir);
180
- }
757
+ throw new UsageError("tool init needs the directory to write: b3os tool init ./pandoc --from-binary ./pandoc");
758
+ return init(ctx, dir, a.values);
759
+ case "dev":
760
+ return dev(ctx, dir ?? ".", a.values);
761
+ case "publish":
762
+ return publish(ctx, dir ?? ".", a.values);
763
+ case "rm":
764
+ return rm(ctx, dir);
765
+ case "yank":
766
+ return yank(ctx, dir, Boolean(a.values.undo));
767
+ case "health":
768
+ return health(ctx, a.values);
181
769
  case "earnings":
182
770
  return earnings(ctx, a.values);
183
771
  default:
@@ -188,7 +776,7 @@ export async function tool(ctx, argv) {
188
776
  export const commands = [
189
777
  {
190
778
  name: "tool",
191
- summary: "Publish a hosted tool and read its earnings",
779
+ summary: "Make, publish and run a hosted tool; read its health and earnings",
192
780
  order: 155,
193
781
  run: tool,
194
782
  options: TOOL_OPTIONS,