@b3os/cli 0.0.1 → 0.1.3

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 (76) hide show
  1. package/README.md +71 -34
  2. package/bin/b3os.js +13 -3
  3. package/dist/commands/_common.d.ts +49 -0
  4. package/dist/commands/_common.js +174 -0
  5. package/dist/commands/_common.js.map +1 -0
  6. package/dist/commands/actions.d.ts +43 -0
  7. package/dist/commands/actions.js +184 -0
  8. package/dist/commands/actions.js.map +1 -0
  9. package/dist/commands/api.d.ts +24 -0
  10. package/dist/commands/api.js +14 -8
  11. package/dist/commands/api.js.map +1 -1
  12. package/dist/commands/auth.d.ts +58 -0
  13. package/dist/commands/auth.js +215 -19
  14. package/dist/commands/auth.js.map +1 -1
  15. package/dist/commands/bench.d.ts +22 -0
  16. package/dist/commands/bench.js +19 -7
  17. package/dist/commands/bench.js.map +1 -1
  18. package/dist/commands/connect.d.ts +52 -0
  19. package/dist/commands/connect.js +221 -0
  20. package/dist/commands/connect.js.map +1 -0
  21. package/dist/commands/infer.d.ts +47 -0
  22. package/dist/commands/infer.js +152 -0
  23. package/dist/commands/infer.js.map +1 -0
  24. package/dist/commands/init.d.ts +45 -0
  25. package/dist/commands/init.js +267 -0
  26. package/dist/commands/init.js.map +1 -0
  27. package/dist/commands/keys.d.ts +42 -0
  28. package/dist/commands/keys.js +70 -38
  29. package/dist/commands/keys.js.map +1 -1
  30. package/dist/commands/manifest.d.ts +13 -0
  31. package/dist/commands/manifest.js +117 -0
  32. package/dist/commands/manifest.js.map +1 -0
  33. package/dist/commands/mcp.d.ts +65 -0
  34. package/dist/commands/mcp.js +167 -50
  35. package/dist/commands/mcp.js.map +1 -1
  36. package/dist/commands/render.d.ts +119 -0
  37. package/dist/commands/render.js +294 -0
  38. package/dist/commands/render.js.map +1 -0
  39. package/dist/commands/requests.d.ts +34 -0
  40. package/dist/commands/requests.js +63 -0
  41. package/dist/commands/requests.js.map +1 -0
  42. package/dist/commands/routine.d.ts +53 -1
  43. package/dist/commands/routine.js +246 -110
  44. package/dist/commands/routine.js.map +1 -1
  45. package/dist/commands/sandbox.d.ts +130 -0
  46. package/dist/commands/sandbox.js +327 -55
  47. package/dist/commands/sandbox.js.map +1 -1
  48. package/dist/commands/vision.d.ts +196 -0
  49. package/dist/commands/vision.js +478 -0
  50. package/dist/commands/vision.js.map +1 -0
  51. package/dist/commands/webhooks.d.ts +20 -0
  52. package/dist/commands/webhooks.js +76 -0
  53. package/dist/commands/webhooks.js.map +1 -0
  54. package/dist/ctx.d.ts +80 -6
  55. package/dist/ctx.js +233 -24
  56. package/dist/ctx.js.map +1 -1
  57. package/dist/main.d.ts +4 -1
  58. package/dist/main.js +72 -40
  59. package/dist/main.js.map +1 -1
  60. package/dist/manifest/load.d.ts +143 -0
  61. package/dist/manifest/load.js +279 -0
  62. package/dist/manifest/load.js.map +1 -0
  63. package/dist/manifest/plan.d.ts +52 -0
  64. package/dist/manifest/plan.js +628 -0
  65. package/dist/manifest/plan.js.map +1 -0
  66. package/dist/registry.d.ts +19 -0
  67. package/dist/registry.js +52 -0
  68. package/dist/registry.js.map +1 -0
  69. package/dist/suggest.d.ts +9 -0
  70. package/dist/suggest.js +51 -0
  71. package/dist/suggest.js.map +1 -0
  72. package/package.json +12 -9
  73. package/schemas/b3os.v0.schema.json +244 -0
  74. package/dist/commands/web.d.ts +0 -4
  75. package/dist/commands/web.js +0 -205
  76. package/dist/commands/web.js.map +0 -1
@@ -0,0 +1,628 @@
1
+ // `b3os apply --dry-run` (b3os.yaml v0, design preview): what an apply would do, read from the API as it is now.
2
+ // The plan only reads. Its one POST is /v1/routines/validate, which compiles a definition and stores nothing.
3
+ // Everything else is a GET through the PlanReader below, which has no method that writes.
4
+ import { B3OSError } from "@b3os/sdk";
5
+ import { packCalls, packTriggers } from "./load.js";
6
+ export const SYMBOL = {
7
+ create: "+",
8
+ update: "~",
9
+ ok: "=",
10
+ gap: "?",
11
+ problem: "!",
12
+ unchecked: "-",
13
+ };
14
+ /** At most this many items are read from a list (connections, profiles). */
15
+ const LIST_CAP = 500;
16
+ async function collect(it) {
17
+ const out = [];
18
+ for await (const x of it) {
19
+ out.push(x);
20
+ if (out.length >= LIST_CAP)
21
+ break;
22
+ }
23
+ return out;
24
+ }
25
+ function split(id) {
26
+ const i = id.indexOf("/");
27
+ return [id.slice(0, i), id.slice(i + 1)];
28
+ }
29
+ export function readerFor(b3) {
30
+ return {
31
+ principal: () => b3.keys.getCurrentKey(),
32
+ limits: () => b3.limits.getLimits(),
33
+ models: () => b3.infer.listModels(),
34
+ pack: (id, version) => {
35
+ const [ns, name] = split(id);
36
+ return b3.actions.getPack(ns, name, version ? { version } : undefined);
37
+ },
38
+ connections: (pack) => collect(b3.vault.listConnections({ limit: 100, ...(pack ? { pack } : {}) })),
39
+ templates: () => b3.sandboxes.listTemplates(),
40
+ profiles: () => collect(b3.vision.listProfiles({ limit: 100 })),
41
+ routine: (name) => b3.routines.getRoutine(name),
42
+ version: (name, n) => b3.routines.getVersion(name, String(n)),
43
+ validate: (definition) => b3.routines.validateRoutine(definition),
44
+ };
45
+ }
46
+ /** A 403's missing scope, for an `unchecked` line. */
47
+ function forbidden(e) {
48
+ if (!(e instanceof B3OSError) || e.status !== 403)
49
+ return null;
50
+ const scope = e.problem?.required_scope;
51
+ return typeof scope === "string" ? `the key lacks ${scope}` : "the key may not read this";
52
+ }
53
+ const notFound = (e) => e instanceof B3OSError && e.status === 404;
54
+ /**
55
+ * Scopes a credential holds that never come through a wildcard: `*` and `<product>:*` do not grant them
56
+ * (packages/spec/common.yaml `not_in_wildcards`).
57
+ */
58
+ const NOT_IN_WILDCARDS = new Set(["vision:profiles:export"]);
59
+ /**
60
+ * Whether a scope list grants `needed`, as the edge decides it (apps/edge/src/lib/scopes.ts grants): `*`, the exact
61
+ * name, or `<product>:*`, except a not_in_wildcards scope, which only its own name grants.
62
+ */
63
+ export function grants(granted, needed) {
64
+ const list = [...granted];
65
+ if (NOT_IN_WILDCARDS.has(needed))
66
+ return list.includes(needed);
67
+ const i = needed.indexOf(":");
68
+ const product = `${i < 0 ? needed : needed.slice(0, i)}:*`;
69
+ return list.some((g) => g === "*" || g === needed || g === product);
70
+ }
71
+ /** JSON with sorted keys, for comparing definitions regardless of key order. */
72
+ export function canonical(v) {
73
+ if (Array.isArray(v))
74
+ return `[${v.map(canonical).join(",")}]`;
75
+ if (v && typeof v === "object")
76
+ return `{${Object.keys(v)
77
+ .filter((k) => v[k] !== undefined)
78
+ .sort()
79
+ .map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`)
80
+ .join(",")}}`;
81
+ return JSON.stringify(v);
82
+ }
83
+ /** The top-level fields that differ between two definitions (`$schema` is ignored). */
84
+ export function changedFields(a, b) {
85
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
86
+ keys.delete("$schema");
87
+ return [...keys].filter((k) => canonical(a[k]) !== canonical(b[k])).sort();
88
+ }
89
+ const mib = (n) => `${n} MiB`;
90
+ /** A cached read: each list is fetched at most once per plan, and a 403 is remembered as the reason. */
91
+ function once(f) {
92
+ let p;
93
+ return () => {
94
+ p ??= f().then((value) => ({ value }), (e) => {
95
+ const why = forbidden(e);
96
+ if (why)
97
+ return { denied: why };
98
+ throw e;
99
+ });
100
+ return p;
101
+ };
102
+ }
103
+ function matchConnection(list, ref) {
104
+ return ref.startsWith("conn_") ? list.find((c) => c.id === ref) : list.find((c) => c.label === ref);
105
+ }
106
+ /** "conn_… (slack-bot), active" with the end user it belongs to, when it has a subject. */
107
+ const connText = (c) => `${c.id}${c.label ? ` (${c.label})` : ""}, ${c.status}${c.subject !== null ? `, end user ${c.subject}` : ""}`;
108
+ /**
109
+ * The connection a step that leaves the key out and names no `subject` uses: the project's newest one for the pack
110
+ * and key without a `subject`, so an end user's connection is used only when named (docs-site/actions/call.mdx
111
+ * #connections; crates/b3os-routines/src/engine/exec.rs pack_step). A step that names a `subject` uses that end
112
+ * user's newest connection instead, never this one.
113
+ */
114
+ function defaultConnection(forKey) {
115
+ return forKey
116
+ .filter((c) => c.subject === null)
117
+ .sort((a, b) => b.created_at.localeCompare(a.created_at) || b.id.localeCompare(a.id))[0];
118
+ }
119
+ /** The file's routine steps and action triggers by the pack they use. */
120
+ function callersByPack(routines) {
121
+ const out = new Map();
122
+ const push = (pack, c) => out.set(pack, [...(out.get(pack) ?? []), c]);
123
+ for (const r of routines) {
124
+ if (!r.definition)
125
+ continue;
126
+ const name = r.name ?? r.file;
127
+ for (const c of packCalls(r.definition))
128
+ push(c.pack, { at: `${name}/${c.step}`, trigger: false, key: c.key, subject: c.subject, binds: c.binds });
129
+ for (const t of packTriggers(r.definition))
130
+ push(t.pack, { at: `${name}/${t.id}`, trigger: true, key: t.key, subject: false, binds: t.binds });
131
+ }
132
+ return out;
133
+ }
134
+ /**
135
+ * Whether a caller needs the connection `key`: a run binds the keys of the step's action and a publish the keys of
136
+ * the trigger, as the pack lists them. A caller the pack does not list (another version) counts for every key.
137
+ */
138
+ function needs(c, key, pack) {
139
+ const listed = (c.trigger ? pack.triggers : pack.actions)?.find((x) => x.key === c.key)?.connections;
140
+ return Array.isArray(listed) ? listed.includes(key) : true;
141
+ }
142
+ /** "step", "trigger" or "step and trigger", for the kinds in `list`. */
143
+ function kinds(list) {
144
+ const t = list.filter((c) => c.trigger).length;
145
+ return t === list.length ? "trigger" : t ? "step and trigger" : "step";
146
+ }
147
+ /**
148
+ * "step a/x names", "steps a/x and b/y name", "trigger a/t takes" or "step a/x and trigger a/t take" (at most three
149
+ * named). A trigger cannot name a subject, so a list with one says "take".
150
+ */
151
+ function callersName(list) {
152
+ const kind = kinds(list);
153
+ const mixed = kind === "step and trigger";
154
+ const names = list.map((c) => (mixed ? `${c.trigger ? "trigger" : "step"} ${c.at}` : c.at));
155
+ const shown = names.length > 3 ? [...names.slice(0, 3), `${names.length - 3} more`] : names;
156
+ const text = shown.length > 1 ? `${shown.slice(0, -1).join(", ")} and ${shown.at(-1)}` : shown[0];
157
+ const noun = mixed ? "" : `${kind}${list.length > 1 ? "s" : ""} `;
158
+ const verb = kind === "step" ? "name" : "take";
159
+ return `${noun}${text} ${list.length === 1 ? `${verb}s` : verb}`;
160
+ }
161
+ /** Whether `host` is one of `bound` (exact, or under a `*.` wildcard). */
162
+ function covers(bound, host) {
163
+ const h = host.replace(/:\d+$/, "");
164
+ return bound.some((b) => b === h || (b.startsWith("*.") && h.endsWith(b.slice(1))));
165
+ }
166
+ /** Build the plan. `loaded` must carry a manifest (loadManifest found no errors). */
167
+ export async function buildPlan(loaded, api, baseUrl) {
168
+ const m = loaded.manifest;
169
+ const items = [];
170
+ // A 403 on one of an item's reads leaves the rest of it checked, not all of it: such an item is "not checked"
171
+ // (a problem found by the reads that worked stays a problem).
172
+ const add = ({ denied, ...i }) => {
173
+ const partly = denied && i.action !== "problem" && i.action !== "unchecked";
174
+ const item = partly ? { ...i, action: "unchecked", detail: `partly checked: ${i.detail}` } : i;
175
+ items.push(item.notes?.length ? item : { ...item, notes: undefined });
176
+ };
177
+ const principal = once(() => api.principal());
178
+ const limits = once(() => api.limits());
179
+ const models = once(() => api.models());
180
+ const templates = once(() => api.templates());
181
+ const profiles = once(() => api.profiles());
182
+ const allConnections = once(() => api.connections());
183
+ // ---- project and credential
184
+ const who = await principal();
185
+ const scopes = new Set(who.value?.scopes ?? []);
186
+ const can = (s) => !who.value || grants(scopes, s);
187
+ if (m.project && who.value && who.value.project_id !== m.project)
188
+ add({
189
+ block: "project",
190
+ name: m.project,
191
+ action: "problem",
192
+ detail: `the credential in use belongs to ${who.value.project_id}, not ${m.project}`,
193
+ });
194
+ // ---- infer
195
+ for (const d of m.infer?.models ?? []) {
196
+ const r = await models();
197
+ if (r.denied) {
198
+ add({ block: "infer", name: d.id, action: "unchecked", detail: `could not list models: ${r.denied}` });
199
+ continue;
200
+ }
201
+ const list = r.value?.data ?? [];
202
+ const found = list.find((x) => x.id === d.id);
203
+ if (!found) {
204
+ add({
205
+ block: "infer",
206
+ name: d.id,
207
+ action: "problem",
208
+ detail: `not served by this node (it serves ${list.map((x) => x.id).join(", ") || "no models"})`,
209
+ });
210
+ continue;
211
+ }
212
+ const info = found.b3os;
213
+ const problems = [];
214
+ if (d.kind && info.kind !== d.kind)
215
+ problems.push(`is a ${info.kind} model, not ${d.kind}`);
216
+ for (const need of d.needs ?? [])
217
+ if (!info[need])
218
+ problems.push(`does not support ${need}`);
219
+ if (d.min_context_tokens && (info.context_length ?? 0) < d.min_context_tokens)
220
+ problems.push(`has a context of ${info.context_length ?? "unknown"} tokens, under ${d.min_context_tokens}`);
221
+ const caps = ["tools", "json_schema", "image_input"].filter((k) => info[k]);
222
+ add({
223
+ block: "infer",
224
+ name: d.id,
225
+ action: problems.length ? "problem" : "ok",
226
+ detail: problems.length
227
+ ? problems.join("; ")
228
+ : `served: ${info.kind}${info.alias_of ? ` (alias of ${info.alias_of})` : ""}, context ${info.context_length ?? "unknown"} tokens${caps.length ? `, ${caps.join(", ")}` : ""}`,
229
+ });
230
+ }
231
+ // ---- actions
232
+ const callers = callersByPack(loaded.routines);
233
+ for (const d of m.actions?.packs ?? []) {
234
+ const calls = callers.get(d.id) ?? [];
235
+ let pack;
236
+ try {
237
+ pack = await api.pack(d.id, d.version);
238
+ }
239
+ catch (e) {
240
+ const why = forbidden(e);
241
+ if (why) {
242
+ add({ block: "actions", name: d.id, action: "unchecked", detail: `could not read the pack: ${why}` });
243
+ continue;
244
+ }
245
+ if (notFound(e)) {
246
+ add({
247
+ block: "actions",
248
+ name: d.id,
249
+ action: "problem",
250
+ detail: d.version ? `version ${d.version} is not on this node` : "not on this node",
251
+ });
252
+ continue;
253
+ }
254
+ throw e;
255
+ }
256
+ const notes = [];
257
+ let problem = false;
258
+ let denied = false;
259
+ const keys = new Map(pack.connections.map((c) => [c.key, c]));
260
+ for (const k of Object.keys(d.connections ?? {}))
261
+ if (!keys.has(k)) {
262
+ problem = true;
263
+ notes.push(`connection key ${k}: the pack has no such key (it has ${[...keys.keys()].join(", ") || "none"})`);
264
+ }
265
+ if (keys.size) {
266
+ let stored;
267
+ try {
268
+ stored = await api.connections(d.id);
269
+ }
270
+ catch (e) {
271
+ const why = forbidden(e);
272
+ if (!why)
273
+ throw e;
274
+ denied = true;
275
+ notes.push(`connections not checked: ${why}`);
276
+ }
277
+ if (stored)
278
+ for (const c of pack.connections) {
279
+ const ref = d.connections?.[c.key];
280
+ const forKey = stored.filter((x) => x.key === c.key);
281
+ const reconnect = `reconnect it (b3os connect ${d.id})`;
282
+ if (ref) {
283
+ const hit = matchConnection(forKey, ref);
284
+ if (!hit) {
285
+ problem = true;
286
+ notes.push(`connection ${c.key}: no stored ${d.id} connection ${ref.startsWith("conn_") ? "" : "labelled "}${ref}`);
287
+ }
288
+ else if (hit.status !== "active") {
289
+ problem = true;
290
+ notes.push(`connection ${c.key}: ${connText(hit)}: its token could not be refreshed; ${reconnect}`);
291
+ }
292
+ else
293
+ notes.push(`connection ${c.key}: ${connText(hit)}`);
294
+ continue;
295
+ }
296
+ const used = defaultConnection(forKey);
297
+ const endUsers = forKey.filter((x) => x.subject !== null).length;
298
+ // The steps and action triggers that need this key and leave it to the run (or, for a trigger, to the
299
+ // publish), and of those the ones without a subject: only these use the newest connection without a
300
+ // subject, so only these make a missing or expired one a problem. A trigger never has a subject.
301
+ const users = calls.filter((x) => needs(x, c.key, pack));
302
+ const open = users.filter((x) => !x.binds.includes(c.key));
303
+ const bare = open.filter((x) => !x.subject);
304
+ if (!bare.length) {
305
+ const usedText = used ? connText(used) : "none is stored";
306
+ if (!users.length)
307
+ notes.push(`connection ${c.key}: not bound here, and no step or trigger in this file needs it; a call that names no subject would use the newest one without a subject (${usedText})`);
308
+ else if (!open.length)
309
+ notes.push(`connection ${c.key}: each ${kinds(users)} that needs it binds it itself (not checked here)`);
310
+ else
311
+ notes.push(`connection ${c.key}: not bound here; each ${kinds(users)} that needs it names a subject${open.length < users.length ? ` or binds ${c.key} itself` : ""}, so a run uses that end user's newest connection, never one without a subject (${endUsers ? `${endUsers} stored with a subject` : "none stored with a subject yet"})`);
312
+ continue;
313
+ }
314
+ const who = callersName(bare);
315
+ // A trigger binds at publish: with one among them, the publish is what uses the connection, or fails.
316
+ const atPublish = bare.some((x) => x.trigger);
317
+ const kind = kinds(bare);
318
+ const uses = kind === "step" ? "a run uses" : kind === "trigger" ? "the publish binds" : "the publish and a run use";
319
+ if (used && used.status !== "active") {
320
+ problem = true;
321
+ notes.push(`connection ${c.key}: not bound here; ${who} no subject, so ${uses} the newest one without a subject, ${connText(used)}: ${reconnect}`);
322
+ }
323
+ else if (used)
324
+ notes.push(`connection ${c.key}: not bound here; ${who} no subject, so ${uses} the newest one without a subject (${used.id})`);
325
+ else if (c.optional)
326
+ notes.push(`connection ${c.key}: optional, none stored without a subject`);
327
+ else if (endUsers) {
328
+ problem = true;
329
+ notes.push(`connection ${c.key}: only end users' connections are stored (${endUsers}, each with a subject), and ${who} none, so ${atPublish ? "the publish" : "a run"} fails with connection_required; ${atPublish ? "bind one here or store one without a subject" : "bind one here, store one without a subject, or give the step a subject"}`);
330
+ }
331
+ else {
332
+ problem = true;
333
+ notes.push(`connection ${c.key}: none stored, and ${who} no subject (b3os connect ${d.id})`);
334
+ }
335
+ }
336
+ }
337
+ const v = d.version ?? pack.version;
338
+ add({
339
+ block: "actions",
340
+ name: d.id,
341
+ action: problem ? "problem" : "ok",
342
+ detail: `${v}${d.version ? "" : " (latest)"} on the node, ${pack.actions.length} actions; packs need no install step`,
343
+ notes,
344
+ denied,
345
+ });
346
+ }
347
+ // ---- sandboxes
348
+ const sandboxLimit = async (id) => {
349
+ const r = await limits();
350
+ return r.value?.items.find((x) => x.id === id)?.limit;
351
+ };
352
+ for (const d of m.sandboxes ?? []) {
353
+ const r = await templates();
354
+ if (r.denied) {
355
+ add({ block: "sandboxes", name: d.name, action: "unchecked", detail: `could not list templates: ${r.denied}` });
356
+ continue;
357
+ }
358
+ const t = r.value?.data.find((x) => x.id === d.template || x.name === d.template);
359
+ if (!t) {
360
+ add({
361
+ block: "sandboxes",
362
+ name: d.name,
363
+ action: "problem",
364
+ detail: `template ${d.template} is not on this node (it has ${(r.value?.data ?? []).map((x) => x.name).join(", ")})`,
365
+ });
366
+ continue;
367
+ }
368
+ const vcpu = d.vcpu ?? t.defaults.vcpu;
369
+ const mem = d.memory_mib ?? t.defaults.memory_mib;
370
+ const disk = d.disk_gib ?? t.defaults.disk_gib;
371
+ const problems = [];
372
+ const over = async (id, value, unit) => {
373
+ const max = await sandboxLimit(id);
374
+ if (typeof max === "number" && value > max)
375
+ problems.push(`${value} ${unit} is over your limit of ${max} (${id})`);
376
+ };
377
+ await over("sandboxes.vcpu_max", vcpu, "vCPU");
378
+ await over("sandboxes.memory_max", mem, "MiB");
379
+ await over("sandboxes.disk_max", disk, "GiB");
380
+ const notes = [];
381
+ const limitsDenied = (await limits()).denied;
382
+ if (limitsDenied)
383
+ notes.push(`limits not checked: ${limitsDenied}`);
384
+ const warmSize = t.size_classes.some((c) => c.vcpu === vcpu && c.memory_mib === mem);
385
+ notes.push(warmSize
386
+ ? "a size this node keeps started: a create claims a waiting microVM"
387
+ : "not a size this node keeps started: each create restores one on demand");
388
+ add({
389
+ block: "sandboxes",
390
+ name: d.name,
391
+ action: problems.length ? "problem" : "ok",
392
+ detail: problems.length
393
+ ? problems.join("; ")
394
+ : `${t.name}, ${vcpu} vCPU, ${mib(mem)}, ${disk} GiB; created by your code at run time, nothing to apply`,
395
+ notes,
396
+ denied: Boolean(limitsDenied),
397
+ });
398
+ if (d.warm !== undefined)
399
+ add({
400
+ block: "sandboxes",
401
+ name: `${d.name} warm`,
402
+ action: "gap",
403
+ detail: `warm: ${d.warm} is not declarable in this beta; the node sizes its warm pools`,
404
+ });
405
+ }
406
+ // ---- vision and render pools
407
+ const pool = async (block, d) => {
408
+ const notes = [];
409
+ let missing = false;
410
+ let denied = false;
411
+ if (d.profile) {
412
+ if (block === "render")
413
+ notes.push("render jobs cannot load a profile yet: they answer 501 not_implemented");
414
+ else {
415
+ const r = await profiles();
416
+ if (r.denied) {
417
+ denied = true;
418
+ notes.push(`profile not checked: ${r.denied}`);
419
+ }
420
+ else {
421
+ const p = r.value?.find((x) => x.id === d.profile || x.name === d.profile);
422
+ if (p)
423
+ notes.push(`profile ${p.name}: ${p.id}, ${p.status}`);
424
+ else {
425
+ missing = true;
426
+ notes.push(`profile ${d.profile}: not stored in this organization`);
427
+ }
428
+ }
429
+ }
430
+ }
431
+ add({
432
+ block,
433
+ name: d.name,
434
+ action: missing ? "problem" : "gap",
435
+ detail: `${d.browsers} browsers is not declarable in this beta; the node sizes its browser pools`,
436
+ notes,
437
+ denied,
438
+ });
439
+ };
440
+ for (const d of m.vision?.pools ?? [])
441
+ await pool("vision", d);
442
+ for (const d of m.render?.pools ?? [])
443
+ await pool("render", d);
444
+ // ---- routines
445
+ for (const r of loaded.routines)
446
+ await routineItem(r, api, add, can);
447
+ // ---- external resources
448
+ for (const d of m.resources ?? []) {
449
+ const notes = [];
450
+ let action = "ok";
451
+ let denied = false;
452
+ if (d.connection) {
453
+ const r = await allConnections();
454
+ if (r.denied) {
455
+ denied = true;
456
+ notes.push(`connection not checked: ${r.denied}`);
457
+ }
458
+ else {
459
+ const c = matchConnection(r.value ?? [], d.connection);
460
+ if (!c) {
461
+ action = "problem";
462
+ notes.push(`connection ${d.connection}: not stored in this project`);
463
+ }
464
+ else {
465
+ notes.push(`connection ${d.connection}: ${connText(c)}`);
466
+ if (c.status !== "active") {
467
+ action = "problem";
468
+ notes.push("its token could not be refreshed, so requests do not get a credential; reconnect it");
469
+ }
470
+ const missing = d.kind === "http" ? (d.hosts ?? []).filter((h) => !covers(c.hosts, h)) : [];
471
+ if (missing.length) {
472
+ action = "problem";
473
+ notes.push(`the connection is not bound to ${missing.join(", ")}, so requests there do not get it`);
474
+ }
475
+ }
476
+ }
477
+ }
478
+ for (const u of d.used_by ?? [])
479
+ if (u.startsWith("sandbox/") && d.kind !== "http")
480
+ notes.push(`${u} would get the credential as a sandbox secret from the connection`);
481
+ add({
482
+ block: "resources",
483
+ name: d.name,
484
+ action,
485
+ detail: `external ${d.engine ? `${d.engine} ` : ""}${d.kind}: B3OS does not run it${d.hosts?.length ? ` (${d.hosts.join(", ")})` : ""}`,
486
+ notes,
487
+ denied,
488
+ });
489
+ }
490
+ const summary = { create: 0, update: 0, ok: 0, gap: 0, problem: 0, unchecked: 0 };
491
+ for (const i of items)
492
+ summary[i.action]++;
493
+ return {
494
+ object: "plan",
495
+ format: "b3os.yaml v0 (design preview)",
496
+ manifest: loaded.file,
497
+ name: m.name,
498
+ base_url: baseUrl,
499
+ project_id: who.value?.project_id ?? null,
500
+ dry_run: true,
501
+ items,
502
+ summary,
503
+ };
504
+ }
505
+ async function routineItem(r, api, add, can) {
506
+ if (!r.definition || !r.name)
507
+ return;
508
+ const name = r.name;
509
+ const notes = [];
510
+ let valid;
511
+ let denied = false;
512
+ try {
513
+ valid = await api.validate(r.definition);
514
+ }
515
+ catch (e) {
516
+ const why = forbidden(e);
517
+ if (!why)
518
+ throw e;
519
+ denied = true;
520
+ notes.push(`not compiled: ${why}`);
521
+ }
522
+ if (valid && !valid.valid) {
523
+ const shown = valid.diagnostics
524
+ .filter((d) => d.severity === "error")
525
+ .slice(0, 5)
526
+ .map((d) => `${d.pointer || "/"} ${d.code}: ${d.detail}`);
527
+ add({
528
+ block: "routines",
529
+ name,
530
+ action: "problem",
531
+ detail: `${r.file} does not compile (${valid.diagnostics.length} ${valid.diagnostics.length === 1 ? "diagnostic" : "diagnostics"})`,
532
+ notes: shown,
533
+ });
534
+ return;
535
+ }
536
+ if (valid)
537
+ notes.push(`compiles: ${valid.steps ?? "?"} steps`);
538
+ if (!can("routines:write"))
539
+ notes.push("this key could not publish it: an apply needs routines:write");
540
+ let current;
541
+ try {
542
+ current = await api.routine(name);
543
+ }
544
+ catch (e) {
545
+ if (notFound(e)) {
546
+ add({
547
+ block: "routines",
548
+ name,
549
+ action: "create",
550
+ detail: `new routine from ${r.file}, version 1`,
551
+ notes,
552
+ denied,
553
+ });
554
+ return;
555
+ }
556
+ const why = forbidden(e);
557
+ if (why) {
558
+ add({ block: "routines", name, action: "unchecked", detail: `could not read the routine: ${why}`, notes });
559
+ return;
560
+ }
561
+ throw e;
562
+ }
563
+ const n = current.version.number;
564
+ let active;
565
+ try {
566
+ active = await api.version(name, n);
567
+ }
568
+ catch (e) {
569
+ const why = forbidden(e);
570
+ if (!why)
571
+ throw e;
572
+ add({ block: "routines", name, action: "unchecked", detail: `could not read version ${n}: ${why}`, notes });
573
+ return;
574
+ }
575
+ if (current.status === "paused")
576
+ notes.push(`paused (${current.paused_reason ?? "manual"}): triggers stay stopped`);
577
+ const changed = changedFields(r.definition, (active.definition ?? {}));
578
+ if (!active.definition || changed.length) {
579
+ const t = current.triggers.length;
580
+ if (t)
581
+ notes.push(`${t} ${t === 1 ? "trigger switches" : "triggers switch"} to the new version at once`);
582
+ add({
583
+ block: "routines",
584
+ name,
585
+ action: "update",
586
+ detail: `publish version ${n + 1} (version ${n} is active)${changed.length ? `; changed: ${changed.join(", ")}` : ""}`,
587
+ notes,
588
+ denied,
589
+ });
590
+ }
591
+ else
592
+ add({ block: "routines", name, action: "ok", detail: `unchanged: version ${n} is active`, notes, denied });
593
+ }
594
+ /** The plan as text, one line per item, notes indented under it. */
595
+ export function formatPlan(p) {
596
+ const lines = [
597
+ `b3os.yaml v0 design preview: dry run of ${p.name} (${p.manifest}) against ${p.base_url}${p.project_id ? `, project ${p.project_id}` : ""}`,
598
+ "Nothing was created or changed.",
599
+ "",
600
+ ];
601
+ const blocks = ["project", "infer", "actions", "sandboxes", "vision", "render", "routines", "resources"];
602
+ const w = Math.max(8, ...p.items.map((i) => i.name.length));
603
+ for (const b of blocks) {
604
+ const list = p.items.filter((i) => i.block === b);
605
+ if (!list.length)
606
+ continue;
607
+ lines.push(b);
608
+ for (const i of list) {
609
+ lines.push(` ${SYMBOL[i.action]} ${i.name.padEnd(w)} ${i.detail}`);
610
+ for (const n of i.notes ?? [])
611
+ lines.push(` ${" ".repeat(w)} ${n}`);
612
+ }
613
+ lines.push("");
614
+ }
615
+ const s = p.summary;
616
+ const parts = [
617
+ s.create ? `${s.create} to create` : "",
618
+ s.update ? `${s.update} to update` : "",
619
+ s.ok ? `${s.ok} in place` : "",
620
+ s.gap ? `${s.gap} not declarable yet` : "",
621
+ s.problem ? `${s.problem} ${s.problem === 1 ? "problem" : "problems"}` : "",
622
+ s.unchecked ? `${s.unchecked} not checked` : "",
623
+ ].filter(Boolean);
624
+ lines.push(`Plan: ${parts.join(", ") || "nothing declared"}.`);
625
+ lines.push("+ create ~ update = in place ? not declarable in this beta ! problem - not checked");
626
+ return lines.join("\n");
627
+ }
628
+ //# sourceMappingURL=plan.js.map