blast-studio 0.0.0-stage → 0.1.1

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 (256) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +138 -2
  3. package/bin/bstudio.mjs +13 -0
  4. package/dist/agent-env.js +177 -0
  5. package/dist/brief.js +53 -0
  6. package/dist/budget/ledger.js +153 -0
  7. package/dist/campaign-zip.js +93 -0
  8. package/dist/cli.js +118 -0
  9. package/dist/commands/accept.js +64 -0
  10. package/dist/commands/auth.js +77 -0
  11. package/dist/commands/brief.js +117 -0
  12. package/dist/commands/budget.js +22 -0
  13. package/dist/commands/dashboard.js +9 -0
  14. package/dist/commands/doctor.js +57 -0
  15. package/dist/commands/export.js +42 -0
  16. package/dist/commands/init.js +24 -0
  17. package/dist/commands/install-skills.js +52 -0
  18. package/dist/commands/library.js +12 -0
  19. package/dist/commands/make.js +71 -0
  20. package/dist/commands/mark.js +44 -0
  21. package/dist/commands/new.js +25 -0
  22. package/dist/commands/plan.js +57 -0
  23. package/dist/commands/render-preview.js +43 -0
  24. package/dist/commands/render.js +243 -0
  25. package/dist/commands/review.js +119 -0
  26. package/dist/commands/revise.js +73 -0
  27. package/dist/commands/sources.js +33 -0
  28. package/dist/commands/status.js +34 -0
  29. package/dist/config.js +141 -0
  30. package/dist/dashboard/server.js +171 -0
  31. package/dist/dashboard/static/app.css +1 -0
  32. package/dist/dashboard/static/app.js +52 -0
  33. package/dist/dashboard/static/index.html +8 -0
  34. package/dist/env.js +47 -0
  35. package/dist/export.js +110 -0
  36. package/dist/fetch-text.js +64 -0
  37. package/dist/io.js +1 -0
  38. package/dist/keychain.js +41 -0
  39. package/dist/library.js +49 -0
  40. package/dist/packs.js +91 -0
  41. package/dist/plan.js +75 -0
  42. package/dist/posts.js +40 -0
  43. package/dist/providers/images.js +116 -0
  44. package/dist/providers/voice.js +55 -0
  45. package/dist/render/bins.js +21 -0
  46. package/dist/render/ffmpeg.js +102 -0
  47. package/dist/render/metrics.js +109 -0
  48. package/dist/render/stills.js +175 -0
  49. package/dist/render/template.js +20 -0
  50. package/dist/render/video.js +175 -0
  51. package/dist/review/gates.js +201 -0
  52. package/dist/review/reviewer.js +79 -0
  53. package/dist/review/score.js +21 -0
  54. package/dist/review/slop.js +17 -0
  55. package/dist/review-hash.js +21 -0
  56. package/dist/types.js +29 -0
  57. package/dist/updater/check.js +140 -0
  58. package/dist/updater/propose.js +144 -0
  59. package/dist/workspace.js +142 -0
  60. package/package.json +45 -4
  61. package/platforms/bluesky/guide.md +94 -0
  62. package/platforms/bluesky/pack.yml +150 -0
  63. package/platforms/dailydev/guide.md +82 -0
  64. package/platforms/dailydev/pack.yml +152 -0
  65. package/platforms/devto/guide.md +93 -0
  66. package/platforms/devto/pack.yml +119 -0
  67. package/platforms/gist/guide.md +92 -0
  68. package/platforms/gist/pack.yml +119 -0
  69. package/platforms/github-discussion/guide.md +92 -0
  70. package/platforms/github-discussion/pack.yml +122 -0
  71. package/platforms/hashnode/guide.md +93 -0
  72. package/platforms/hashnode/pack.yml +124 -0
  73. package/platforms/hn/guide.md +48 -0
  74. package/platforms/hn/pack.yml +59 -0
  75. package/platforms/instagram/guide.md +95 -0
  76. package/platforms/instagram/pack.yml +136 -0
  77. package/platforms/lemmy/guide.md +88 -0
  78. package/platforms/lemmy/pack.yml +141 -0
  79. package/platforms/linkedin/guide.md +93 -0
  80. package/platforms/linkedin/pack.yml +145 -0
  81. package/platforms/mastodon/guide.md +92 -0
  82. package/platforms/mastodon/pack.yml +138 -0
  83. package/platforms/medium/guide.md +92 -0
  84. package/platforms/medium/pack.yml +119 -0
  85. package/platforms/newsletter/guide.md +94 -0
  86. package/platforms/newsletter/pack.yml +144 -0
  87. package/platforms/producthunt/guide.md +92 -0
  88. package/platforms/producthunt/pack.yml +166 -0
  89. package/platforms/reddit/guide.md +92 -0
  90. package/platforms/reddit/pack.yml +151 -0
  91. package/platforms/snapshots/.gitkeep +0 -0
  92. package/platforms/snapshots/bluesky-10.sha256 +1 -0
  93. package/platforms/snapshots/bluesky-10.txt +1 -0
  94. package/platforms/snapshots/bluesky-11.sha256 +1 -0
  95. package/platforms/snapshots/bluesky-11.txt +1 -0
  96. package/platforms/snapshots/bluesky-12.sha256 +1 -0
  97. package/platforms/snapshots/bluesky-12.txt +1 -0
  98. package/platforms/snapshots/bluesky-13.sha256 +1 -0
  99. package/platforms/snapshots/bluesky-13.txt +1 -0
  100. package/platforms/snapshots/bluesky-14.sha256 +1 -0
  101. package/platforms/snapshots/bluesky-14.txt +1 -0
  102. package/platforms/snapshots/cross-platform-63.sha256 +1 -0
  103. package/platforms/snapshots/cross-platform-63.txt +1 -0
  104. package/platforms/snapshots/cross-platform-64.sha256 +1 -0
  105. package/platforms/snapshots/cross-platform-64.txt +1 -0
  106. package/platforms/snapshots/dailydev-55.sha256 +1 -0
  107. package/platforms/snapshots/dailydev-55.txt +1 -0
  108. package/platforms/snapshots/dailydev-56.sha256 +1 -0
  109. package/platforms/snapshots/dailydev-56.txt +1 -0
  110. package/platforms/snapshots/dailydev-57.sha256 +1 -0
  111. package/platforms/snapshots/dailydev-57.txt +1 -0
  112. package/platforms/snapshots/devto-26.sha256 +1 -0
  113. package/platforms/snapshots/devto-26.txt +1 -0
  114. package/platforms/snapshots/devto-27.sha256 +1 -0
  115. package/platforms/snapshots/devto-27.txt +1 -0
  116. package/platforms/snapshots/devto-28.sha256 +1 -0
  117. package/platforms/snapshots/devto-28.txt +1 -0
  118. package/platforms/snapshots/devto-29.sha256 +1 -0
  119. package/platforms/snapshots/devto-29.txt +1 -0
  120. package/platforms/snapshots/gist-52.sha256 +1 -0
  121. package/platforms/snapshots/gist-52.txt +1 -0
  122. package/platforms/snapshots/gist-53.sha256 +1 -0
  123. package/platforms/snapshots/gist-53.txt +1 -0
  124. package/platforms/snapshots/gist-54.sha256 +1 -0
  125. package/platforms/snapshots/gist-54.txt +1 -0
  126. package/platforms/snapshots/github-discussion-policy.sha256 +1 -0
  127. package/platforms/snapshots/github-discussion-policy.txt +1 -0
  128. package/platforms/snapshots/hashnode-30.sha256 +1 -0
  129. package/platforms/snapshots/hashnode-30.txt +1 -0
  130. package/platforms/snapshots/hashnode-31.sha256 +1 -0
  131. package/platforms/snapshots/hashnode-31.txt +1 -0
  132. package/platforms/snapshots/hashnode-32.sha256 +1 -0
  133. package/platforms/snapshots/hashnode-32.txt +1 -0
  134. package/platforms/snapshots/hn-23.sha256 +1 -0
  135. package/platforms/snapshots/hn-23.txt +1 -0
  136. package/platforms/snapshots/hn-24.sha256 +1 -0
  137. package/platforms/snapshots/hn-24.txt +1 -0
  138. package/platforms/snapshots/hn-25.sha256 +1 -0
  139. package/platforms/snapshots/hn-25.txt +1 -0
  140. package/platforms/snapshots/hyperframes-releases.sha256 +1 -0
  141. package/platforms/snapshots/hyperframes-releases.txt +1 -0
  142. package/platforms/snapshots/instagram-43.sha256 +1 -0
  143. package/platforms/snapshots/instagram-43.txt +1 -0
  144. package/platforms/snapshots/instagram-47.sha256 +1 -0
  145. package/platforms/snapshots/instagram-47.txt +1 -0
  146. package/platforms/snapshots/lemmy-policy.sha256 +1 -0
  147. package/platforms/snapshots/lemmy-policy.txt +1 -0
  148. package/platforms/snapshots/linkedin-1.sha256 +1 -0
  149. package/platforms/snapshots/linkedin-1.txt +1 -0
  150. package/platforms/snapshots/linkedin-2.sha256 +1 -0
  151. package/platforms/snapshots/linkedin-2.txt +1 -0
  152. package/platforms/snapshots/linkedin-3.sha256 +1 -0
  153. package/platforms/snapshots/linkedin-3.txt +1 -0
  154. package/platforms/snapshots/linkedin-4.sha256 +1 -0
  155. package/platforms/snapshots/linkedin-4.txt +1 -0
  156. package/platforms/snapshots/mastodon-15.sha256 +1 -0
  157. package/platforms/snapshots/mastodon-15.txt +1 -0
  158. package/platforms/snapshots/mastodon-16.sha256 +1 -0
  159. package/platforms/snapshots/mastodon-16.txt +1 -0
  160. package/platforms/snapshots/mastodon-17.sha256 +1 -0
  161. package/platforms/snapshots/mastodon-17.txt +1 -0
  162. package/platforms/snapshots/medium-34.sha256 +1 -0
  163. package/platforms/snapshots/medium-34.txt +1 -0
  164. package/platforms/snapshots/medium-35.sha256 +1 -0
  165. package/platforms/snapshots/medium-35.txt +1 -0
  166. package/platforms/snapshots/medium-36.sha256 +1 -0
  167. package/platforms/snapshots/medium-36.txt +1 -0
  168. package/platforms/snapshots/newsletter-58.sha256 +1 -0
  169. package/platforms/snapshots/newsletter-58.txt +1 -0
  170. package/platforms/snapshots/newsletter-59.sha256 +1 -0
  171. package/platforms/snapshots/newsletter-59.txt +1 -0
  172. package/platforms/snapshots/newsletter-60.sha256 +1 -0
  173. package/platforms/snapshots/newsletter-60.txt +1 -0
  174. package/platforms/snapshots/newsletter-61.sha256 +1 -0
  175. package/platforms/snapshots/newsletter-61.txt +1 -0
  176. package/platforms/snapshots/newsletter-62.sha256 +1 -0
  177. package/platforms/snapshots/newsletter-62.txt +1 -0
  178. package/platforms/snapshots/openai-image-pricing.sha256 +1 -0
  179. package/platforms/snapshots/openai-image-pricing.txt +1 -0
  180. package/platforms/snapshots/playwright-releases.sha256 +1 -0
  181. package/platforms/snapshots/playwright-releases.txt +1 -0
  182. package/platforms/snapshots/producthunt-37.sha256 +1 -0
  183. package/platforms/snapshots/producthunt-37.txt +1 -0
  184. package/platforms/snapshots/producthunt-38.sha256 +1 -0
  185. package/platforms/snapshots/producthunt-38.txt +1 -0
  186. package/platforms/snapshots/producthunt-39.sha256 +1 -0
  187. package/platforms/snapshots/producthunt-39.txt +1 -0
  188. package/platforms/snapshots/reddit-20.sha256 +1 -0
  189. package/platforms/snapshots/reddit-20.txt +1 -0
  190. package/platforms/snapshots/reddit-21.sha256 +1 -0
  191. package/platforms/snapshots/reddit-21.txt +1 -0
  192. package/platforms/snapshots/reddit-22.sha256 +1 -0
  193. package/platforms/snapshots/reddit-22.txt +1 -0
  194. package/platforms/snapshots/substack-policy.sha256 +1 -0
  195. package/platforms/snapshots/substack-policy.txt +1 -0
  196. package/platforms/snapshots/threads-18.sha256 +1 -0
  197. package/platforms/snapshots/threads-18.txt +1 -0
  198. package/platforms/snapshots/threads-19.sha256 +1 -0
  199. package/platforms/snapshots/threads-19.txt +1 -0
  200. package/platforms/snapshots/tiktok-50.sha256 +1 -0
  201. package/platforms/snapshots/tiktok-50.txt +1 -0
  202. package/platforms/snapshots/tiktok-51.sha256 +1 -0
  203. package/platforms/snapshots/tiktok-51.txt +1 -0
  204. package/platforms/snapshots/x-5.sha256 +1 -0
  205. package/platforms/snapshots/x-5.txt +1 -0
  206. package/platforms/snapshots/x-6.sha256 +1 -0
  207. package/platforms/snapshots/x-6.txt +1 -0
  208. package/platforms/snapshots/x-7.sha256 +1 -0
  209. package/platforms/snapshots/x-7.txt +1 -0
  210. package/platforms/snapshots/x-8.sha256 +1 -0
  211. package/platforms/snapshots/x-8.txt +1 -0
  212. package/platforms/snapshots/x-9.sha256 +1 -0
  213. package/platforms/snapshots/x-9.txt +1 -0
  214. package/platforms/snapshots/youtube-shorts-40.sha256 +1 -0
  215. package/platforms/snapshots/youtube-shorts-40.txt +1 -0
  216. package/platforms/snapshots/youtube-shorts-41.sha256 +1 -0
  217. package/platforms/snapshots/youtube-shorts-41.txt +1 -0
  218. package/platforms/snapshots/youtube-shorts-42.sha256 +1 -0
  219. package/platforms/snapshots/youtube-shorts-42.txt +1 -0
  220. package/platforms/sources.yml +947 -0
  221. package/platforms/substack/guide.md +94 -0
  222. package/platforms/substack/pack.yml +116 -0
  223. package/platforms/threads/guide.md +93 -0
  224. package/platforms/threads/pack.yml +148 -0
  225. package/platforms/tiktok/guide.md +92 -0
  226. package/platforms/tiktok/pack.yml +129 -0
  227. package/platforms/x/guide.md +94 -0
  228. package/platforms/x/pack.yml +130 -0
  229. package/platforms/youtube-shorts/guide.md +92 -0
  230. package/platforms/youtube-shorts/pack.yml +138 -0
  231. package/providers/prices.yml +31 -0
  232. package/schemas/campaign.v2.json +26 -0
  233. package/schemas/manifest.v1.json +37 -0
  234. package/schemas/pack.schema.json +601 -0
  235. package/schemas/review.schema.json +31 -0
  236. package/skills/studio-reviewer/SKILL.md +13 -0
  237. package/skills/studio-updater/SKILL.md +8 -0
  238. package/skills/studio-video/SKILL.md +20 -0
  239. package/skills/studio-visual/SKILL.md +12 -0
  240. package/skills/studio-writer/SKILL.md +14 -0
  241. package/templates/README.md +7 -0
  242. package/templates/card.html +1 -0
  243. package/templates/carousel-closing.html +1 -0
  244. package/templates/carousel-content.html +1 -0
  245. package/templates/carousel-title.html +1 -0
  246. package/templates/code.html +1 -0
  247. package/templates/fonts/IBM-Plex-OFL.txt +93 -0
  248. package/templates/fonts/IBMPlexMono.woff2 +0 -0
  249. package/templates/fonts/IBMPlexSans.woff2 +0 -0
  250. package/templates/fonts/Space-Grotesk-OFL.txt +93 -0
  251. package/templates/fonts/SpaceGrotesk.woff2 +0 -0
  252. package/templates/poster.html +1 -0
  253. package/templates/quote.html +1 -0
  254. package/templates/thumbnail.html +1 -0
  255. package/test/fixtures/reviews/calibration.json +22 -0
  256. package/test/fixtures/reviews/grounding/cases.json +17 -0
@@ -0,0 +1,153 @@
1
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ import { UserError } from "../types.js";
6
+ export function parseAgentOutput(raw) {
7
+ try {
8
+ const value = JSON.parse(raw);
9
+ if (value && typeof value === "object" && !Array.isArray(value) && ("total_cost_usd" in value || "cost_usd" in value || ("result" in value && "usage" in value))) {
10
+ const wrapper = value;
11
+ const cost = wrapper.total_cost_usd ?? wrapper.cost_usd;
12
+ const usd = typeof cost === "number" && Number.isFinite(cost) && cost >= 0 ? cost : null;
13
+ return { text: typeof wrapper.result === "string" ? wrapper.result : raw, usd, usage: wrapper.usage };
14
+ }
15
+ }
16
+ catch { /* Plain agent output is not a wrapper. */ }
17
+ return { text: raw, usd: null };
18
+ }
19
+ function entries(root) {
20
+ const file = join(root, "ledger.jsonl");
21
+ if (!existsSync(file))
22
+ return [];
23
+ const lines = readFileSync(file, "utf8").split("\n");
24
+ return lines.filter(Boolean).map((line, index) => {
25
+ try {
26
+ return JSON.parse(line);
27
+ }
28
+ catch {
29
+ throw new UserError(`Invalid ledger line ${index + 1}; repair ${file} before continuing`);
30
+ }
31
+ });
32
+ }
33
+ function effective(root) {
34
+ const all = entries(root), settled = new Map(all.filter(e => e.type === "settled").map(e => [e.id, e]));
35
+ return all.filter(e => e.type !== "settled").map(e => {
36
+ const s = settled.get(e.id);
37
+ return s ? { ...e, usd: s.usd, usage: s.usage } : e;
38
+ });
39
+ }
40
+ export function monthToDate(root, now = new Date()) {
41
+ const month = now.toISOString().slice(0, 7);
42
+ return effective(root).filter(e => e.at.slice(0, 7) === month).reduce((sum, e) => sum + (e.usd ?? 0), 0);
43
+ }
44
+ export function projectTotal(root, projectSlug) {
45
+ return effective(root).filter(e => e.projectSlug === projectSlug).reduce((sum, e) => sum + (e.usd ?? 0), 0);
46
+ }
47
+ export function providerTotals(root, now = new Date()) {
48
+ const totals = {};
49
+ for (const e of effective(root))
50
+ if (e.at.slice(0, 7) === now.toISOString().slice(0, 7))
51
+ totals[e.provider] = (totals[e.provider] ?? 0) + (e.usd ?? 0);
52
+ return totals;
53
+ }
54
+ async function locked(root, fn) {
55
+ mkdirSync(root, { recursive: true, mode: 0o700 });
56
+ const path = join(root, "ledger.lock"), deadline = Date.now() + 10000;
57
+ let fd;
58
+ for (;;) {
59
+ try {
60
+ fd = openSync(path, "wx", 0o600);
61
+ writeFileSync(fd, String(process.pid));
62
+ break;
63
+ }
64
+ catch (err) {
65
+ if (err.code !== "EEXIST")
66
+ throw err;
67
+ const recovery = `${path}.recovery`;
68
+ try {
69
+ mkdirSync(recovery);
70
+ try {
71
+ const pid = Number(readFileSync(path, "utf8"));
72
+ let dead = false;
73
+ if (pid > 0) {
74
+ try {
75
+ process.kill(pid, 0);
76
+ }
77
+ catch (e) {
78
+ dead = e.code === "ESRCH";
79
+ }
80
+ }
81
+ if (dead || Date.now() - statSync(path).mtimeMs > 60000) {
82
+ const stale = `${path}.stale-${randomUUID()}`;
83
+ renameSync(path, stale);
84
+ unlinkSync(stale);
85
+ }
86
+ }
87
+ finally {
88
+ rmdirSync(recovery);
89
+ }
90
+ }
91
+ catch (e) {
92
+ if (e.code === "EEXIST") {
93
+ try {
94
+ if (Date.now() - statSync(recovery).mtimeMs > 60000)
95
+ rmdirSync(recovery);
96
+ }
97
+ catch (error) {
98
+ if (error.code !== "ENOENT")
99
+ throw error;
100
+ }
101
+ }
102
+ else if (e.code !== "ENOENT")
103
+ throw e;
104
+ }
105
+ if (Date.now() >= deadline)
106
+ throw new UserError("Timed out waiting for ledger lock");
107
+ await delay(20);
108
+ }
109
+ }
110
+ try {
111
+ return fn();
112
+ }
113
+ finally {
114
+ closeSync(fd);
115
+ unlinkSync(path);
116
+ }
117
+ }
118
+ function append(root, entry) { appendFileSync(join(root, "ledger.jsonl"), JSON.stringify(entry) + "\n", { mode: 0o600 }); }
119
+ export async function reserve(config, upperBoundUsd, meta) {
120
+ if (!Number.isFinite(upperBoundUsd) || upperBoundUsd <= 0)
121
+ throw new UserError("Invalid reservation amount");
122
+ return locked(config.root, () => {
123
+ if (config.budget.monthlyUsd === 0 || monthToDate(config.root) + upperBoundUsd > config.budget.monthlyUsd + 1e-12)
124
+ throw new UserError("Monthly budget exceeded or paid calls disabled");
125
+ // A zero project cap means no additional project limit; the monthly cap still applies.
126
+ if (config.budget.perProjectUsd > 0 && projectTotal(config.root, meta.projectSlug) + upperBoundUsd > config.budget.perProjectUsd + 1e-12)
127
+ throw new UserError("Project budget exceeded");
128
+ const id = randomUUID();
129
+ append(config.root, { ...meta, id, type: "reserved", at: new Date().toISOString(), usd: upperBoundUsd });
130
+ return id;
131
+ });
132
+ }
133
+ export async function settle(root, id, actualUsd, usage) {
134
+ if (actualUsd !== null && (!Number.isFinite(actualUsd) || actualUsd < 0))
135
+ throw new UserError("Invalid settlement amount");
136
+ await locked(root, () => {
137
+ const all = entries(root), original = all.find(e => e.id === id && e.type === "reserved");
138
+ if (!original || all.some(e => e.id === id && e.type === "settled"))
139
+ throw new UserError("Unknown or already settled reservation");
140
+ append(root, { ...original, type: "settled", at: new Date().toISOString(), usd: actualUsd, usage });
141
+ if (actualUsd !== null && original.usd !== null && actualUsd > original.usd)
142
+ console.warn(`Warning: settlement exceeded reservation by $${(actualUsd - original.usd).toFixed(6)} (reported $${actualUsd}, reserved $${original.usd})`);
143
+ });
144
+ }
145
+ export async function reserveAgentRun(config, run) {
146
+ return reserve(config, run.maxUsd, { projectSlug: run.projectSlug, provider: "agent", model: run.command });
147
+ }
148
+ export async function settleAgentRun(config, id, run) {
149
+ await settle(config.root, id, run.usd, run.usage);
150
+ }
151
+ export async function recordAgentRun(config, run) {
152
+ await locked(config.root, () => append(config.root, { id: randomUUID(), type: "agent", at: new Date().toISOString(), projectSlug: run.projectSlug ?? "", provider: run.provider ?? "agent", model: run.model, ms: run.ms, usage: run.usage, usd: null }));
153
+ }
@@ -0,0 +1,93 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { Ajv2020 } from 'ajv/dist/2020.js';
6
+ import { strToU8, zipSync } from 'fflate';
7
+ import { stringify } from 'yaml';
8
+ import { parseBrief } from "./brief.js";
9
+ import { UserError } from "./types.js";
10
+ const root = fileURLToPath(new URL('../', import.meta.url));
11
+ const schema = JSON.parse(readFileSync(join(root, 'schemas/campaign.v2.json'), 'utf8'));
12
+ const packageInfo = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
13
+ if (!packageInfo || typeof packageInfo !== 'object' || !('version' in packageInfo) || typeof packageInfo.version !== 'string')
14
+ throw new Error('Invalid package version');
15
+ const version = packageInfo.version;
16
+ const ajv = new Ajv2020({ allErrors: true });
17
+ ajv.addFormat('date-time', { type: 'string', validate: (s) => Number.isFinite(Date.parse(s)) });
18
+ const validate = ajv.compile(schema);
19
+ export function writeCampaignZip(project, slug, prepared, sourceFile) {
20
+ const files = {};
21
+ let total = 0;
22
+ const checkSize = (path, size) => {
23
+ if (size > 500 * 1024 ** 2)
24
+ throw new UserError(`Campaign zip entry ${path} exceeds Market Blaster's 500 MiB limit`);
25
+ if (total - (files[path]?.length ?? 0) + size > 1024 ** 3)
26
+ throw new UserError("Campaign zip exceeds Market Blaster's 1 GiB uncompressed limit");
27
+ };
28
+ const add = (path, data) => {
29
+ checkSize(path, data.length);
30
+ total += data.length - (files[path]?.length ?? 0);
31
+ files[path] = data;
32
+ };
33
+ const text = (path, content) => { add(path, strToU8(content)); };
34
+ const file = (path, source) => { checkSize(path, statSync(source).size); add(path, readFileSync(source)); };
35
+ const brief = readFileSync(join(project, 'brief.md'), 'utf8');
36
+ const sections = parseBrief(brief);
37
+ const sources = sections.map(section => ({ anchor: section.anchor, title: section.title, status: section.status ?? null, url: section.body.match(/^Source:\s*(https?:\/\/\S+)/m)?.[1] ?? null }));
38
+ if (new Set(sections.map(s => s.anchor)).size !== sections.length)
39
+ throw new UserError('Brief contains duplicate source anchors');
40
+ text('brief.md', brief);
41
+ text('sources/sources.json', JSON.stringify(sources, null, 2) + '\n');
42
+ for (const section of sections)
43
+ text(`sources/${section.anchor}.md`, section.body + '\n');
44
+ const copyMedia = (path) => {
45
+ const name = `media/${createHash('sha256').update(path).digest('hex').slice(0, 16)}/${basename(path)}`;
46
+ file(name, sourceFile(project, path));
47
+ return name;
48
+ };
49
+ const destinations = [], manual = [];
50
+ for (const { post, review, hash, pack } of prepared) {
51
+ const media = post.media.map(m => ({ path: copyMedia(m.file), alt: m.alt, kind: m.kind,
52
+ ...(m.cover === undefined ? {} : { cover: m.cover }), ...(m.lang === undefined ? {} : { lang: m.lang }), ...(m.captions === undefined ? {} : { captions: copyMedia(m.captions) }) }));
53
+ const reviewFile = join(project, 'reviews', `${post.platform}.json`);
54
+ file(`review/${post.platform}.json`, reviewFile);
55
+ if (!pack.marketBlaster) {
56
+ const folder = `handoff/${post.platform}/`;
57
+ text(`${folder}post.md`, [post.title ? `# ${post.title}\n` : '', post.body, ...(post.thread ?? []).map(t => `\n---\n\n${t}`)].join('\n') + '\n');
58
+ const guide = readFileSync(join(root, 'platforms', post.platform, 'guide.md'), 'utf8');
59
+ const checklist = guide.match(/## Checklist\s*\n([\s\S]*?)(?=\n## |$)/)?.[1]?.trim() ?? '';
60
+ const disclosures = Object.entries(post.disclosure ?? {}).map(([key, value]) => `- ${key}: ${value}`);
61
+ const policy = Object.entries(pack.disclosure).map(([key, rule]) => `- ${key}: ${typeof rule === 'string' ? rule : rule.rule}`);
62
+ text(`${folder}README.md`, [`# ${pack.name} manual handoff`, '', '- [ ] Open the platform publishing interface and select the correct account.', '- [ ] Copy post.md and attach the listed media.', '- [ ] Enter alt text, captions and disclosures; review and publish manually.', '', '## Media', ...media.map(m => `- ../../${m.path} (${m.kind}; alt: ${m.alt})${'captions' in m && m.captions ? `; captions: ../../${m.captions}` : ''}`), '', '## Disclosure', ...(disclosures.length ? disclosures : ['- None specified.']), '', '## Platform disclosure rules', ...policy, '', '## Platform notes', ...(pack.notes ?? []).map(n => `- ${n}`), '', '## Platform checklist', checklist, ''].join('\n'));
63
+ manual.push({ platform: post.platform, folder, review: { verdict: review.verdict, total: review.total } });
64
+ continue;
65
+ }
66
+ const id = pack.marketBlaster;
67
+ const postPath = pack.ai === 'none' ? null : `posts/${id}.md`;
68
+ const thread = post.thread?.length ? `handoff/${id}-thread.md` : null;
69
+ if (thread)
70
+ text(thread, post.thread.map((item, index) => `## ${index + 2}\n\n${item}`).join('\n\n') + '\n');
71
+ if (postPath)
72
+ text(postPath, `---\n${stringify({ ...(post.title === undefined ? {} : { title: post.title }), ...(post.tags === undefined ? {} : { tags: post.tags }), evidence: post.evidence, ...(post.disclosure === undefined ? {} : { disclosure: post.disclosure }), media, studio: { reviewHash: hash, verdict: review.verdict } })}---\n\n${post.body.trim()}\n`);
73
+ const mode = ['x', 'threads', 'hn', 'reddit', 'producthunt', 'lemmy', 'newsletter', 'medium', 'substack'].includes(id) || (id === 'linkedin' && media.some(m => m.kind === 'document' && m.path.toLowerCase().endsWith('.pdf'))) ? 'handoff' : 'api';
74
+ destinations.push({ id, mode, aiPolicy: pack.ai, post: postPath, ...(post.tags === undefined ? {} : { tags: post.tags }), media, thread, review: { verdict: review.verdict, total: review.total, reviewHash: hash } });
75
+ }
76
+ const reviewPath = join(project, 'review.md');
77
+ text('review/review.md', existsSync(reviewPath) ? readFileSync(reviewPath, 'utf8') : ['# Editorial review', '', ...prepared.map(({ post, review }) => `- ${post.platform}: ${review.verdict}${review.total === null ? '' : ` (${review.total}%)`}`), ''].join('\n'));
78
+ const timestamps = prepared.map(({ review }) => review.at).filter(at => typeof at === 'string' && Number.isFinite(Date.parse(at))).sort();
79
+ const manifest = { version: 2, kind: 'blast-studio-campaign', slug, title: brief.match(/^#\s+(.+)$/m)?.[1]?.trim() || slug,
80
+ generatedAt: timestamps.length ? new Date(timestamps[timestamps.length - 1]).toISOString() : '1980-01-01T00:00:00.000Z', generator: { name: 'blast-studio', version }, canonicalHome: destinations.some(destination => destination.id === 'devto') ? 'devto' : null, sources, destinations, manual };
81
+ if (!validate(manifest))
82
+ throw new UserError(`Invalid campaign manifest: ${ajv.errorsText(validate.errors)}`);
83
+ text('campaign.json', JSON.stringify(manifest, null, 2) + '\n');
84
+ if (Object.keys(files).length > 2000)
85
+ throw new UserError("Campaign zip exceeds Market Blaster's 2000 entry limit");
86
+ const sorted = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
87
+ const zip = zipSync(sorted, { level: 0, mtime: new Date(1980, 0, 1) });
88
+ const dir = join(project, 'export');
89
+ mkdirSync(dir, { recursive: true });
90
+ const path = join(dir, `${slug}.campaign.zip`);
91
+ writeFileSync(path, zip);
92
+ return path;
93
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,118 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { run as accept, confirm } from "./commands/accept.js";
4
+ import { run as auth } from "./commands/auth.js";
5
+ import { run as brief } from "./commands/brief.js";
6
+ import { run as budget } from "./commands/budget.js";
7
+ import { run as dashboard } from "./commands/dashboard.js";
8
+ import { run as doctor } from "./commands/doctor.js";
9
+ import { run as exportProject } from "./commands/export.js";
10
+ import { run as init } from "./commands/init.js";
11
+ import { run as installSkills } from "./commands/install-skills.js";
12
+ import { run as library } from "./commands/library.js";
13
+ import { run as mark } from "./commands/mark.js";
14
+ import { run as make } from "./commands/make.js";
15
+ import { run as newProject } from "./commands/new.js";
16
+ import { run as plan } from "./commands/plan.js";
17
+ import { run as render } from "./commands/render.js";
18
+ import { run as renderPreview } from "./commands/render-preview.js";
19
+ import { run as review } from "./commands/review.js";
20
+ import { run as revise } from "./commands/revise.js";
21
+ import { run as sources } from "./commands/sources.js";
22
+ import { run as status } from "./commands/status.js";
23
+ import { keychainGet } from "./keychain.js";
24
+ import { UserError } from "./types.js";
25
+ const COMMANDS = {
26
+ init: { summary: "initialize the private studio and global configuration", run: init },
27
+ doctor: { summary: "check tools, providers and budget", run: doctor },
28
+ "install-skills": { summary: "link studio skills [--with-hyperframes]", run: installSkills },
29
+ new: {
30
+ summary: "brief + plan + make + render + review: new <slug> [--idea text] [--note text] [--url url] [--pr number] [--commit sha] [--repo owner/repo|local] [--mb-brief path] [--force]",
31
+ run: newProject,
32
+ },
33
+ brief: { summary: "collect evidence: brief <slug> [--idea text] [--note text] [--url url] [--pr number] [--commit sha] [--repo owner/repo|local] [--mb-brief path] [--force]", run: brief },
34
+ plan: { summary: "choose post types, angles and hooks per platform: plan <slug>", run: plan },
35
+ make: { summary: "write posts and asset sources with the agent: make <slug>", run: make },
36
+ render: { summary: "render images, carousels, logos, diagrams and video: render <slug> [--regen] [--assets=id,...] [--platforms=id,...]", run: render },
37
+ review: { summary: "gates + platform reviewer scores: review [<slug>] [--calibrate] [--platforms=id,...] (slug required unless calibrating)", run: review },
38
+ revise: { summary: "apply review findings, re-render, re-review: revise <slug>", run: revise },
39
+ accept: { summary: "human override of scores (never gates): accept <slug> <platform> --reason <reason>", run: accept },
40
+ confirm: { summary: "record human asset rights checks: confirm <slug> <asset-id> [--trademark-checked] [--license <license>]", run: confirm },
41
+ budget: { summary: "paid generation caps: budget [show | set <usd> | set-project <usd>]", run: budget },
42
+ auth: { summary: "provider keys in the macOS Keychain: auth set <KEY> [--stdin] | auth list", run: auth },
43
+ export: { summary: "hand passed posts to Market Blaster: export <slug> [--mb <project>] [--force] [--dir]", run: exportProject },
44
+ mark: { summary: "record a manual post (Shorts, Reels, TikTok, daily.dev): mark <slug> <platform> --url U", run: mark },
45
+ status: { summary: "projects, verdicts, spend and source health: status [<slug>] [--verbose]", run: status },
46
+ library: { summary: "everything you have made: library [search <query>]", run: library },
47
+ dashboard: { summary: "local web dashboard: dashboard [--port <port>]", run: dashboard },
48
+ sources: { summary: "keep platform packs current: sources check [--only id,...] [--write] | propose [--branch] | verify <id>...", run: sources },
49
+ "render-preview": {
50
+ summary: "render one html/svg/mmd/d2 file offline: render-preview <file.html|.svg|.mmd|.d2> --size WxH --out <path>",
51
+ run: renderPreview,
52
+ },
53
+ };
54
+ export function help() {
55
+ const width = Math.max(...Object.keys(COMMANDS).map((name) => name.length));
56
+ return ["bstudio: create and review platform-ready content", "", "Usage: bstudio <command> [options]", "",
57
+ ...Object.entries(COMMANDS).map(([name, command]) => ` ${name.padEnd(width)} ${command.summary}`)].join("\n");
58
+ }
59
+ function runProgram(cmd, args, opts = {}) {
60
+ const { promise, resolve, reject } = Promise.withResolvers();
61
+ const child = execFile(cmd, args, { cwd: opts.cwd, env: opts.env, timeout: opts.timeoutMs ?? 0, maxBuffer: 64 * 1024 * 1024 }, (error, stdout, stderr) => {
62
+ if (!error)
63
+ return resolve(stdout);
64
+ const reason = error.killed && opts.timeoutMs ? `timed out after ${opts.timeoutMs / 1000}s` : `exited with ${error.code ?? error.signal}`;
65
+ const tail = [stdout, stderr].filter(Boolean).join("\n").trim().split("\n").slice(-20).join("\n");
66
+ reject(new Error(`${cmd} ${reason}${tail ? `:\n${tail}` : ""}`));
67
+ });
68
+ // Always close stdin: agent CLIs such as `omp -p` wait for EOF on a piped stdin before starting.
69
+ child.stdin?.end(opts.input ?? "");
70
+ return promise;
71
+ }
72
+ let readline;
73
+ export function realIO() {
74
+ return {
75
+ cwd: process.cwd(), env: process.env,
76
+ out: (line) => process.stdout.write(`${line}\n`), err: (line) => process.stderr.write(`${line}\n`),
77
+ isTTY: Boolean(process.stdin.isTTY),
78
+ async prompt(question) {
79
+ readline ??= createInterface({ input: process.stdin, output: process.stdout });
80
+ try {
81
+ return await readline.question(`${question} `);
82
+ }
83
+ catch (err) {
84
+ if (err.name === "AbortError")
85
+ return "";
86
+ throw err;
87
+ }
88
+ },
89
+ fetch: globalThis.fetch, run: runProgram,
90
+ keychain: process.platform === "darwin" ? (key) => keychainGet(key) : undefined,
91
+ };
92
+ }
93
+ export async function main(argv, io = realIO()) {
94
+ const [name, ...rest] = argv;
95
+ if (!name || name === "--help" || name === "-h" || name === "help") {
96
+ io.out(help());
97
+ return name ? 0 : 1;
98
+ }
99
+ const command = COMMANDS[name];
100
+ if (!command) {
101
+ io.err(`unknown command "${name}"\n\n${help()}`);
102
+ return 1;
103
+ }
104
+ try {
105
+ return await command.run(rest, io);
106
+ }
107
+ catch (err) {
108
+ if (err instanceof UserError) {
109
+ io.err(`error: ${err.message}`);
110
+ return 1;
111
+ }
112
+ throw err;
113
+ }
114
+ finally {
115
+ readline?.close();
116
+ readline = undefined;
117
+ }
118
+ }
@@ -0,0 +1,64 @@
1
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse, stringify } from 'yaml';
4
+ import { readBrief } from "../brief.js";
5
+ import { loadPack } from "../packs.js";
6
+ import { runGates } from "../review/gates.js";
7
+ import { loadConfig, projectDir } from "../config.js";
8
+ import { loadPosts } from "../posts.js";
9
+ import { PLATFORM_IDS, UserError } from "../types.js";
10
+ import { mediaContentHash, reviewHash } from "../review-hash.js";
11
+ export const run = async (args, io) => {
12
+ if (args.length !== 4 || args[2] !== '--reason' || !args[3].trim() || !PLATFORM_IDS.includes(args[1]))
13
+ throw new UserError('usage: bstudio accept <slug> <platform> --reason <reason>');
14
+ const config = loadConfig(io), dir = projectDir(config, args[0]), file = join(dir, 'reviews', `${args[1]}.json`);
15
+ let review;
16
+ try {
17
+ review = JSON.parse(readFileSync(file, 'utf8'));
18
+ }
19
+ catch {
20
+ throw new UserError('Review not found or invalid');
21
+ }
22
+ if (!Array.isArray(review.gates) || !review.gates.length || review.gates.some(g => !g.pass))
23
+ throw new UserError('Cannot accept a failed gate');
24
+ const post = loadPosts(dir).get(args[1]);
25
+ if (!post)
26
+ throw new UserError('Post not found');
27
+ const hash = reviewHash({ ...post, media: post.media.map(m => ({ path: m.file, alt: m.alt })) });
28
+ if (hash !== review.postHash || review.mediaHash !== mediaContentHash(dir, post.media))
29
+ throw new UserError('Review is stale; run review again');
30
+ const assetsDir = join(dir, 'assets');
31
+ const assets = existsSync(assetsDir) ? readdirSync(assetsDir).flatMap(id => {
32
+ const path = join(assetsDir, id, 'asset.yml');
33
+ return existsSync(path) ? [parse(readFileSync(path, 'utf8'))] : [];
34
+ }) : [];
35
+ const currentGates = runGates(post, loadPack(post.platform), assets, readBrief(dir), config, dir);
36
+ if (currentGates.some(g => !g.pass))
37
+ throw new UserError('Cannot accept a failed gate; run review again');
38
+ review.verdict = 'accepted';
39
+ review.acceptedReason = args[3].trim();
40
+ review.at = new Date().toISOString();
41
+ writeFileSync(file, JSON.stringify(review, null, 2) + '\n');
42
+ io.out(`${args[1]}: accepted`);
43
+ return 0;
44
+ };
45
+ export const confirm = async (args, io) => {
46
+ if (args.length < 3 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(args[1]))
47
+ throw new UserError('usage: bstudio confirm <slug> <asset-id> [--trademark-checked] [--license <license>]');
48
+ const trademark = args.includes('--trademark-checked'), index = args.indexOf('--license');
49
+ if ((!trademark && index < 0) || (index >= 0 && (!args[index + 1]?.trim() || args[index + 1].startsWith('--'))) || args.length !== 2 + Number(trademark) + (index >= 0 ? 2 : 0))
50
+ throw new UserError('usage: bstudio confirm <slug> <asset-id> [--trademark-checked] [--license <license>]');
51
+ const file = join(projectDir(loadConfig(io), args[0]), 'assets', args[1], 'asset.yml');
52
+ if (!existsSync(file))
53
+ throw new UserError(`Asset not found: ${args[1]}`);
54
+ const asset = parse(readFileSync(file, 'utf8'));
55
+ if (!asset || asset.id !== args[1])
56
+ throw new UserError(`Invalid asset metadata: ${args[1]}`);
57
+ if (trademark)
58
+ asset.trademarkChecked = true;
59
+ if (index >= 0)
60
+ asset.license = args[index + 1].trim();
61
+ writeFileSync(file, stringify(asset));
62
+ io.out(`${args[1]}: confirmation recorded`);
63
+ return 0;
64
+ };
@@ -0,0 +1,77 @@
1
+ import { loadConfig } from "../config.js";
2
+ import { loadEnvWithSources } from "../env.js";
3
+ import { keychainSet } from "../keychain.js";
4
+ import { UserError } from "../types.js";
5
+ async function readSecret(piped) {
6
+ if (piped) {
7
+ if (process.stdin.isTTY)
8
+ throw new UserError("--stdin requires piped input");
9
+ let text = "";
10
+ for await (const chunk of process.stdin)
11
+ text += chunk;
12
+ return text.replace(/\r?\n$/, "");
13
+ }
14
+ if (!process.stdin.isTTY)
15
+ throw new UserError("Use --stdin to read a piped value");
16
+ process.stdout.write("Value: ");
17
+ const stdin = process.stdin;
18
+ const previous = stdin.isRaw;
19
+ stdin.setRawMode(true);
20
+ stdin.resume();
21
+ try {
22
+ const { promise, resolve, reject } = Promise.withResolvers();
23
+ let value = "";
24
+ const onData = (chunk) => {
25
+ for (const char of chunk.toString("utf8")) {
26
+ if (char === "\u0003" || char === "\u0004") {
27
+ cleanup();
28
+ reject(new UserError("Input cancelled"));
29
+ return;
30
+ }
31
+ if (char === "\r" || char === "\n") {
32
+ cleanup();
33
+ resolve(value);
34
+ return;
35
+ }
36
+ if (char === "\u007f" || char === "\b")
37
+ value = value.slice(0, -1);
38
+ else
39
+ value += char;
40
+ }
41
+ };
42
+ const cleanup = () => stdin.off("data", onData);
43
+ stdin.on("data", onData);
44
+ return await promise;
45
+ }
46
+ finally {
47
+ stdin.setRawMode(previous);
48
+ stdin.pause();
49
+ process.stdout.write("\n");
50
+ }
51
+ }
52
+ export async function run(args, io, options = {}) {
53
+ const [action, ...rest] = args;
54
+ const config = loadConfig(io);
55
+ const keys = ["GEMINI_API_KEY", "OPENAI_API_KEY"];
56
+ if (action === "set") {
57
+ const key = rest[0];
58
+ if (!key || !keys.includes(key))
59
+ throw new UserError(`Unknown credential key; known: ${keys.join(", ")}`);
60
+ if (rest.length > 2 || (rest[1] && rest[1] !== "--stdin"))
61
+ throw new UserError("Usage: bstudio auth set <KEY> [--stdin]");
62
+ if ((options.platform ?? process.platform) !== "darwin")
63
+ throw new UserError("macOS Keychain is unavailable; use a studio .env file instead");
64
+ const value = await (options.input ?? readSecret)(rest[1] === "--stdin");
65
+ if (!value)
66
+ throw new UserError("Credential cannot be empty");
67
+ keychainSet(key, value, options.runner, options.platform);
68
+ io.out(`Saved ${key} in Keychain`);
69
+ return 0;
70
+ }
71
+ if (action !== "list" || rest.length)
72
+ throw new UserError("Usage: bstudio auth set <KEY> [--stdin] | list");
73
+ const { sources } = loadEnvWithSources(config.root, io.env, io.keychain, keys);
74
+ for (const key of keys)
75
+ io.out(`${key}: ${sources[key]}`);
76
+ return 0;
77
+ }
@@ -0,0 +1,117 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { parseArgs } from "node:util";
4
+ import { parse } from "yaml";
5
+ import { parseBrief } from "../brief.js";
6
+ import { loadConfig, projectDir } from "../config.js";
7
+ import { fetchText } from "../fetch-text.js";
8
+ import { UserError } from "../types.js";
9
+ function existingPath(path) {
10
+ let cursor = path;
11
+ const tail = [];
12
+ while (!existsSync(cursor)) {
13
+ const parent = dirname(cursor);
14
+ if (parent === cursor)
15
+ break;
16
+ tail.unshift(cursor.slice(parent.length + (parent.endsWith("/") ? 0 : 1)));
17
+ cursor = parent;
18
+ }
19
+ return join(realpathSync(cursor), ...tail);
20
+ }
21
+ function inGit(path) {
22
+ let cursor = existingPath(path);
23
+ for (;;) {
24
+ if (existsSync(join(cursor, ".git")))
25
+ return true;
26
+ const parent = dirname(cursor);
27
+ if (parent === cursor)
28
+ return false;
29
+ cursor = parent;
30
+ }
31
+ }
32
+ function explicitlyConfigured(io, file) {
33
+ if (io.env.BSTUDIO_HOME)
34
+ return true;
35
+ const data = parse(readFileSync(file, "utf8"));
36
+ return typeof data?.studio?.root === "string" && data.studio.root.length > 0;
37
+ }
38
+ function fence(text) {
39
+ const longest = Math.max(2, ...Array.from(text.matchAll(/`+/g), (match) => match[0].length));
40
+ const delimiter = "`".repeat(longest + 1);
41
+ return `${delimiter}untrusted\n${text.trim()}\n${delimiter}`;
42
+ }
43
+ export const run = async (args, io) => {
44
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
45
+ idea: { type: "string" }, note: { type: "string", multiple: true }, url: { type: "string", multiple: true },
46
+ pr: { type: "string" }, commit: { type: "string" }, repo: { type: "string" },
47
+ "mb-brief": { type: "string" }, force: { type: "boolean" },
48
+ } });
49
+ if (positionals.length !== 1)
50
+ throw new UserError("usage: bstudio brief <slug> [--idea text] [--note text] [--url url] [--pr N --repo owner/repo] [--commit sha --repo owner/repo|local] [--mb-brief path] [--force]");
51
+ if (values.pr && !/^\d+$/.test(values.pr))
52
+ throw new UserError("--pr must be a number");
53
+ if ((values.pr || values.commit) && !values.repo)
54
+ throw new UserError("--pr and --commit require --repo");
55
+ if (values.repo && values.repo !== "local" && !/^[\w.-]+\/[\w.-]+$/.test(values.repo))
56
+ throw new UserError("--repo must be owner/repo or local");
57
+ if (values.pr && values.repo === "local")
58
+ throw new UserError("--pr requires a GitHub owner/repo");
59
+ if (values.commit && !/^[0-9a-f]{4,64}$/i.test(values.commit))
60
+ throw new UserError("--commit must be a commit SHA");
61
+ const config = loadConfig(io);
62
+ const dir = projectDir(config, positionals[0]);
63
+ const path = join(dir, "brief.md");
64
+ if (inGit(dir) && !explicitlyConfigured(io, config.file))
65
+ throw new UserError("Project directory is inside a git repository; explicitly set studio.root or BSTUDIO_HOME to allow it");
66
+ if (existsSync(path) && !values.force)
67
+ throw new UserError(`${path} already exists; use --force to overwrite it`);
68
+ const sections = [];
69
+ const add = (title, status, body, source) => {
70
+ const safeTitle = title.replace(/[\r\n]+/g, " ").trim();
71
+ sections.push(`## [E${sections.length + 1}] ${safeTitle}\n\n${status ? `status: ${status}\n\n` : ""}${source ? `Source: ${source.replace(/[\r\n]+/g, " ")}\n\n` : ""}${fence(body)}\n`);
72
+ };
73
+ if (values.idea)
74
+ add("Idea", "claim", values.idea);
75
+ for (const note of values.note ?? [])
76
+ add("Note", "claim", note);
77
+ for (const url of values.url ?? [])
78
+ add("URL", "claim", await fetchText(url, io), url);
79
+ if (values.pr) {
80
+ const raw = await io.run("gh", ["pr", "view", values.pr, "--repo", values.repo, "--json", "number,title,body,state,mergedAt,url"], { cwd: io.cwd });
81
+ let pr;
82
+ try {
83
+ pr = JSON.parse(raw);
84
+ }
85
+ catch {
86
+ throw new UserError("gh returned invalid PR JSON");
87
+ }
88
+ const status = pr.mergedAt || pr.state?.toUpperCase() === "MERGED" ? "shipped" : "planned";
89
+ add(`PR #${values.pr}`, status, `${pr.title ?? ""}\n\n${pr.body ?? ""}`, pr.url || `${values.repo}#${values.pr}`);
90
+ }
91
+ if (values.commit) {
92
+ const raw = values.repo === "local"
93
+ ? await io.run("git", ["show", "--format=fuller", "--stat", "--no-renames", values.commit, "--"], { cwd: io.cwd })
94
+ : await io.run("gh", ["api", `repos/${values.repo}/commits/${values.commit}`], { cwd: io.cwd });
95
+ add(`Commit ${values.commit}`, "shipped", raw, `${values.repo}@${values.commit}`);
96
+ }
97
+ if (values.repo && !values.pr && !values.commit) {
98
+ const raw = values.repo === "local"
99
+ ? await io.run("git", ["log", "-1", "--format=%H%n%s%n%b"], { cwd: io.cwd })
100
+ : await io.run("gh", ["repo", "view", values.repo, "--json", "nameWithOwner,description,url"], { cwd: io.cwd });
101
+ add("Repository", undefined, raw, values.repo);
102
+ }
103
+ if (values["mb-brief"]) {
104
+ const file = resolve(io.cwd, values["mb-brief"]);
105
+ const imported = parseBrief(readFileSync(file, "utf8"));
106
+ if (!imported.length)
107
+ throw new UserError("Market Blaster brief has no evidence sections");
108
+ for (const section of imported)
109
+ add(section.title, section.status, section.body, `${file} [${section.anchor}]`);
110
+ }
111
+ if (!sections.length)
112
+ throw new UserError("Provide at least one brief input");
113
+ mkdirSync(dir, { recursive: true });
114
+ writeFileSync(path, `${sections.join("\n")}\n## Notes from the author\n\n<!-- Add context, caveats, and other details. -->\n`, { flag: values.force ? "w" : "wx" });
115
+ io.out(`Wrote ${path} (${sections.length} evidence anchors)`);
116
+ return 0;
117
+ };
@@ -0,0 +1,22 @@
1
+ import { loadConfig, writeConfigField } from "../config.js";
2
+ import { UserError } from "../types.js";
3
+ import { monthToDate, providerTotals } from "../budget/ledger.js";
4
+ export const run = async (args, io) => {
5
+ const config = loadConfig(io);
6
+ if (args.length === 0 || (args.length === 1 && args[0] === "show")) {
7
+ io.out(`Monthly cap: $${config.budget.monthlyUsd}`);
8
+ io.out(`Per-project cap: ${config.budget.perProjectUsd === 0 ? "unlimited" : `$${config.budget.perProjectUsd}`}`);
9
+ io.out(`Month to date (UTC): $${monthToDate(config.root).toFixed(4)}`);
10
+ for (const [provider, usd] of Object.entries(providerTotals(config.root)))
11
+ io.out(`${provider}: $${usd.toFixed(4)}`);
12
+ return 0;
13
+ }
14
+ if (args.length !== 2 || !["set", "set-project"].includes(args[0]) || !/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(args[1]))
15
+ throw new UserError("usage: bstudio budget [show | set <usd> | set-project <usd>]");
16
+ const amount = Number(args[1]);
17
+ if (!Number.isFinite(amount) || amount < 0)
18
+ throw new UserError("Budget must be a non-negative number");
19
+ writeConfigField(config, ["budget", args[0] === "set" ? "monthlyUsd" : "perProjectUsd"], amount);
20
+ io.out(`Budget updated: $${amount}`);
21
+ return 0;
22
+ };