#!/usr/bin/env node // One admin client for the terminal (docs/functional-parity.md WO-7, gap G3; config-schema §8b *Clients*). Everything the // Worker's admin API offers an owner or operator, signed like scripts/directory-push.mjs (config-schema §8b: the // X-Streamline-Key, timestamp, nonce and an Ed25519 signature over the request). Node 20+, no dependencies. // `node scripts/admin.mjs --help` prints the full reference (the HELP text below doubles as the documentation). // // Rules: every write is a DRY RUN unless --yes (it prints what would be sent and sends nothing; Staging on/off also asks // the Worker's own ?dryRun=1); the key, a session and any signature are never printed; refusals are shown as the Worker // words them; --json prints the Worker's answer as it came. Publishing writes (push, promote, hotfix, merge, restore, // marks) are not here: they are the publishing path's (WO-15: publish-config.mjs / the skill's publish.mjs, restore and // the hotfix's merge through scripts/restore-merge.mjs); this client only reads revisions and the environments and turns // Staging on or off. // // servercheck part 16 (scripts/servercheck-admin.mjs) drives every command in-process through main() below. import { readFileSync, existsSync } from "node:fs"; import { join, dirname, relative, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { createHash, createPrivateKey, sign, randomBytes } from "node:crypto"; const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); export const HELP = `admin.mjs: the Worker's admin API from a terminal (config-schema §8b, §8d) node scripts/admin.mjs [arguments] [options] the organization's id (meridian) http://localhost:8791 (scripts/dev.mjs) or https://streamliner.work Credentials (never printed): --key a server key file (a JWK; its "kid" names it). An owner makes one in the app: Organization → Keys → Server Keys, with the scopes the job needs and an expiry, and saves it once default _local/keys/.server-key.jwk (in the repo: the operator's key for accounts it set up) --key-id when the file has no "kid" SL_ADMIN_BEARER an owner's or admin's session token in the environment instead of a key (for the routes a key can't reach, marked [session] below; a dev Worker also takes "demo:u-priya") Options: --yes send a write (without it every write is a dry run: what would be sent, nothing sent) --json the Worker's answer as JSON (a dry run prints { dryRun, method, path, body }) --help this text People (key scope "members"): members list everyone: level, roles, sessions, suspended, who manages a field members access what they can use, by the relay's own rules (Preview as) members sessions their signed-in devices members set-level [write] only an owner changes an owner; never your own level members set-roles [write] roles a directory or the config sets answer 409 members remove [write] ends their sessions and revokes their publishing devices members signout [--device ] [write] everywhere, or one device; they stay a member streamlines people who can use one streamline, and why not suspend [--reason ] [write] key scope "members" or "directory"; blocked at once lift [write] lift a suspension (they sign in again, no invite) suspended who is suspended now Invites (key scope "invites"; the link carries a one-time code: hand it to that person only): invites list unused, unexpired, newest first (never a code) invites create --email [--access member|admin|owner] [--name ] [--user ] [--roles a,b] [write] --user : a new link for an existing person (Send a New Link…): it joins their record; --email optional then; an owner's only by an owner invites resend [write] a new code and 7 days; the old link stops working invites withdraw [write] the link stops working Record and usage: audit [--since ] [--actor ] [--user ] [--action ] [--limit 1-500] [--cursor ] the activity log (scope "members") usage summary [--user ] [--fresh] totals for 7 days, 30 days, this month (scope "usage:read") usage refusals tools the organization's APIs refused (scope "usage:read") transcripts list [--user ] [--kind ] [--since ] [--limit n] [--cursor c] (scope "transcripts:read") transcripts show [--from ] [--limit n] one chat; every read is an Activity entry Devices and keys: devices list publishing devices, pending first in the app (scope "config"); approving and revoking a device takes a publisher key (the repo's scripts/approve-device.mjs) or an owner's device keys list the organization's server keys: scopes, standing, expiry, last use (scope "config", or a session); never a private key keys revoke [write] final: anything signing with it is refused (scope "config"); making a key is an owner's, in the app (the private half is made there) credentials list which model keys are set (provider, host), never a key (scope "credentials"); setting one is the app's Vault (or the repo's scripts/set-model-key.mjs) Publishing (reads, and Staging on or off). Push, promote and hotfix: the publishing client (the skill's publish.mjs; the repo's scripts/publish-config.mjs) [--promote | --live] [--yes] (§8d); a "config:check" key dry-runs them and can never write. Restore and a hotfix's merge into Staging: the same client, with the organization's publisher key too (they sign a new manifest): --restore [--live] | --merge-hotfix [] [--settle staging|hotfix] --publisher-key [--yes], or the app's Library (History → Restore; Publish → Waiting for Staging): env status Live's and Staging's revisions, Staging on/off, hotfixes waiting env staging on|off [write] owners: key scope "config" or an owner's session; the dry run also asks the Worker (?dryRun=1) config list [--env staging] the stored files and hashes, never contents (scope "config") revisions list [--env live|staging] [--limit 1-100] [--before ] revisions show one revision: kind, author, items revisions diff field-level changes (private/ contents only to a key) presence who has local changes on which items (names only) Toll-free (key scope "config", or an owner's or admin's session; config-schema *Toll-free*; the skill's reference/tollfree.md): tollfree [--show] the block, whether the streamline is shared (in Discover, or by link: its websites only), whether its key is set (never the key), today's spend against the budget tollfree --tag the one-line embed tag for the organization's own pages tollfree [--on|--off] [--credential ] [--places embed,site,app|none] [--origin …|--any] [--remove-origin …] [--budget ] [--per-visitor burst=,hour=,day=,usd=] [--title ] [--subtitle ] [--words-out ] [--words-busy ] [--publisher-key ] [--publisher-key-id ] [write] reads the block, changes what the flags name, checks it with the config checker, and publishes the whole block back as a revision (to Staging while it is on): the Worker answers the next manifest, this signs it with the organization's publisher key (default _local/keys/.publisher.jwk; never printed) and sends it. Needs a server key, not a session. The dry run asks the Worker where it would land. --places lists the places that are on (embed: the organization's own sites; site: Toll-free AI; app: the Streamliner app). --any: any website can put this chat on its pages, and the organization's key pays for it The organization's key pays for every toll-free chat: --budget is its daily ceiling for this streamline in dollars. Web access (the web app at .streamliner.work; off until an owner turns it on; the skill's reference/web-access.md): web status on or off, who set it, and the last reach test's rows (scope "config" or "config:check", or an owner's or admin's session) web reach run the reach test now: can a browser reach each of the organization's MCP servers and sealed endpoints itself (no token is sent; at most 6 an hour; scope "config" or "config:check", or an owner's or admin's session) web on [write] owners: key scope "config" or an owner's session. Needs a reach test from the last 7 days; servers that fail it stay "In the app" for members on the web. The dry run also asks the Worker (?dryRun=1) web off [write] the same keys; every open web page stops at its next call [session] only (a key is refused by design; set SL_ADMIN_BEARER): deletion status an owner's or admin's session (config-schema §8b, org-signup) links list the organization's Discover links (§8c) links stop [write] Unpublish (stop the link) links history every version, newest first, with who published it (§8c) usage mute [write] mark a refusal Expected (a key is refused: 403 forbidden_scope) Exit status: 0 done (or a dry run), 1 the Worker refused, 2 a usage error. Examples: node scripts/admin.mjs meridian http://localhost:8791 invites list node scripts/admin.mjs meridian http://localhost:8791 members set-level u-ava admin (dry run) node scripts/admin.mjs meridian http://localhost:8791 members set-level u-ava admin --yes SL_ADMIN_BEARER=demo:u-priya node scripts/admin.mjs meridian http://localhost:8791 deletion status node scripts/admin.mjs meridian http://localhost:8791 tollfree register --on --places site,app --budget 5 (dry run) node scripts/admin.mjs meridian http://localhost:8791 web reach node scripts/admin.mjs meridian http://localhost:8791 web on --yes `; const VALUE_OPTS = new Set(["key", "key-id", "email", "access", "name", "user", "roles", "reason", "device", "since", "actor", "action", "limit", "cursor", "kind", "from", "env", "before", "credential", "places", "budget", "per-visitor", "title", "subtitle", "words-out", "words-busy", "publisher-key", "publisher-key-id"]); const LIST_OPTS = new Set(["origin", "remove-origin"]); // may be given more than once const BOOL_OPTS = new Set(["yes", "json", "help", "fresh", "on", "off", "any", "tag", "show"]); const ID = /^[A-Za-z0-9_.@-]{1,64}$/; class Usage extends Error {} const need = (v, what) => { if (v == null || v === "") throw new Usage(`missing ${what}`); return v; }; const idOf = (v, what) => { need(v, what); if (!ID.test(v)) throw new Usage(`bad ${what}: ${v}`); return v; }; const intOf = (v, what) => { need(v, what); if (!/^[1-9]\d{0,8}$/.test(v)) throw new Usage(`${what} is a revision number`); return v; }; const qs = (o) => { const p = new URLSearchParams(); for (const [k, v] of Object.entries(o)) if (v != null && v !== false) p.set(k, v === true ? "1" : String(v)); const s = p.toString(); return s ? `?${s}` : ""; }; const enc = encodeURIComponent; // ───────────────────────────── the commands ───────────────────────────── // // Each: (args, opts, A = "/v1/admin/") → { method, path, body?, write?, session?, serverDryRun?, show(answer, out) } const pad = (s, n) => String(s ?? "").padEnd(n); const when = (iso) => (iso ? String(iso).replace("T", " ").slice(0, 16) : ""); const money = (n) => (typeof n === "number" ? `$${n.toFixed(2)}` : ""); const COMMANDS = { "members list": (a, o, A) => ({ method: "GET", path: `${A}/members`, show: (j, out) => { const rows = Object.entries(j.members || {}).sort(([, x], [, y]) => (x.name || "").localeCompare(y.name || "")); for (const [id, m] of rows) { const marks = [m.suspended ? "suspended" : "", m.disabled ? "disabled" : "", m.managed && m.managed.access ? `level by ${m.managed.access}` : "", m.managed && m.managed.roles ? `roles by ${m.managed.roles}` : ""].filter(Boolean).join(", "); out(`${pad(id, 18)} ${pad(m.name, 22)} ${pad(m.access, 7)} ${pad((m.roles || []).join(","), 28)} ${m.sessions || 0} session${m.sessions === 1 ? "" : "s"}${marks ? ` (${marks})` : ""}`); } out(`${rows.length} people; roles: ${(j.roles || []).map((r) => r.id).join(", ") || "none"}`); } }), "members access": (a, o, A) => ({ method: "GET", path: `${A}/members/${idOf(a[0], "")}/access`, show: (j, out) => { out(`${j.user.name || j.user.id} (${j.user.access}${j.user.suspended ? ", suspended" : ""})`); for (const s of j.streamlines || []) out(` ${s.can ? "can " : "can't "} ${pad(s.kind, 18)} ${s.can ? (s.networks && s.networks.length ? `on ${s.networks.join(", ")}` : "") : `why: ${s.why}${s.needs ? ` (needs ${s.needs.join(" or ")})` : ""}`}`); } }), "members sessions": (a, o, A) => ({ method: "GET", path: `${A}/members/${idOf(a[0], "")}/sessions`, show: (j, out) => { for (const s of j.sessions || []) out(`${pad(s.sid, 26)} ${pad(s.device && s.device.name, 20)} ${pad(s.via, 8)} last seen ${when(s.lastSeenAt)}`); out(`${(j.sessions || []).length} sessions`); } }), "members set-level": (a, o, A) => { const user = idOf(a[0], ""), access = need(a[1], ""); if (!["member", "admin", "owner"].includes(access)) throw new Usage("the level is member, admin or owner"); return { method: "PATCH", path: `${A}/members/${user}`, body: { access }, write: true, current: { path: `${A}/members`, pick: (j) => j.members && j.members[user] && `now ${j.members[user].access}` }, show: (j, out) => out(`${j.member.id} is now ${j.member.access}`) }; }, "members set-roles": (a, o, A) => { const user = idOf(a[0], ""); if (a[1] == null) throw new Usage('missing ("" for none)'); const roles = a[1].split(",").map((s) => s.trim()).filter(Boolean); return { method: "PATCH", path: `${A}/members/${user}`, body: { roles }, write: true, current: { path: `${A}/members`, pick: (j) => j.members && j.members[user] && `now ${(j.members[user].roles || []).join(",") || "no roles"}` }, show: (j, out) => out(`${j.member.id}'s roles: ${(j.member.roles || []).join(", ") || "none"}`) }; }, "members remove": (a, o, A) => ({ method: "DELETE", path: `${A}/members/${idOf(a[0], "")}`, write: true, show: (j, out) => out(`removed ${a[0]}: ${j.ended || 0} sessions ended, ${j.devicesRevoked || 0} publishing devices revoked`) }), "members signout": (a, o, A) => ({ method: "DELETE", path: `${A}/members/${idOf(a[0], "")}/sessions${o.device ? `/${enc(o.device)}` : ""}`, write: true, show: (j, out) => out(`${a[0]}: ${j.ended || 0} session${j.ended === 1 ? "" : "s"} ended`) }), "streamlines people": (a, o, A) => ({ method: "GET", path: `${A}/streamlines/${idOf(a[0], "")}/people`, show: (j, out) => { out(`${j.name || j.kind}${j.audience ? ` (for ${j.audience})` : ""}`); for (const p of j.people || []) out(` ${p.can ? "can " : "can't "} ${pad(p.user, 18)} ${pad(p.name, 22)} ${p.can ? "" : `why: ${p.why}`}`); } }), suspend: (a, o, A) => ({ method: "PATCH", path: `${A}/revoked`, body: { users: { [idOf(a[0], "")]: o.reason ? { reason: o.reason } : {} } }, write: true, show: (j, out) => out(`${a[0]} is suspended`) }), lift: (a, o, A) => ({ method: "PATCH", path: `${A}/revoked`, body: { users: { [idOf(a[0], "")]: null } }, write: true, show: (j, out) => out(`${a[0]}'s suspension is lifted`) }), suspended: (a, o, A) => ({ method: "GET", path: `${A}/revoked`, show: (j, out) => { const u = Object.entries(j.users || {}); for (const [id, v] of u) out(`${pad(id, 18)} ${v && v.reason ? v.reason : ""}`); out(`${u.length} suspended`); } }), "invites list": (a, o, A) => ({ method: "GET", path: `${A}/invites`, show: (j, out) => { for (const v of j.invites || []) out(`${pad(v.id, 15)} ${pad(v.email || v.username || v.user, 28)} ${pad(v.access, 7)} by ${pad(v.createdBy && v.createdBy.id, 16)} expires ${when(v.expiresAt)}${v.resentAt ? " (resent)" : ""}${v.user ? ` (a new link for ${v.user})` : ""}`); out(`${(j.invites || []).length} pending`); } }), "invites create": (a, o, A) => { // #27 a new link for an existing person: --user (their record; --email binds it to their address too) const body = { ...(o.user && !o.email ? {} : { email: need(o.email, "--email") }), access: o.access || "member", ...(o.name ? { name: o.name } : {}), ...(o.user ? { user: o.user } : {}), ...(o.roles ? { roles: o.roles.split(",").filter(Boolean) } : {}) }; if (!["member", "admin", "owner"].includes(body.access)) throw new Usage("--access is member, admin or owner"); return { method: "POST", path: `${A}/invites`, body, write: true, show: (j, out) => { out(`${o.user ? `a new link for ${o.user}${body.email ? ` (${body.email})` : ""}` : `invited ${body.email}`} as ${j.access} (invite ${j.id}, expires ${when(j.expiresAt)})`); out(j.url); } }; }, "invites resend": (a, o, A) => ({ method: "POST", path: `${A}/invites/${idOf(a[0], "")}/resend`, write: true, show: (j, out) => { out(`resent ${j.id} (expires ${when(j.expiresAt)}); the old link no longer works`); out(j.url); } }), "invites withdraw": (a, o, A) => ({ method: "DELETE", path: `${A}/invites/${idOf(a[0], "")}`, write: true, show: (j, out) => out(`withdrew ${a[0]}; its link no longer works`) }), audit: (a, o, A) => ({ method: "GET", path: `${A}/audit${qs({ since: o.since, actor: o.actor, user: o.user, action: o.action, limit: o.limit, cursor: o.cursor })}`, show: (j, out) => { for (const e of j.entries || []) { const target = e.target ? Object.entries(e.target).map(([k, v]) => `${k} ${v}`).join(", ") : ""; out(`${when(e.at)} ${pad(`${e.actor.kind}:${e.actor.id}`, 26)} ${pad(e.action, 22)} ${target}${e.detail ? ` ${JSON.stringify(e.detail)}` : ""}`); } if (j.next) out(`more: --cursor ${j.next}`); } }), "usage summary": (a, o, A) => ({ method: "GET", path: `${A}/usage/summary${qs({ user: o.user, fresh: o.fresh })}`, show: (j, out) => { out(`${o.user ? `${o.user} in ` : ""}${j.account || ""}${j.generatedAt ? `, as of ${when(j.generatedAt)}` : ""}${j.costIsEstimate ? " (cost is an estimate)" : ""}`); for (const [w, s] of Object.entries(j.windows || {})) out(` ${pad(w, 4)} ${pad(`${s.calls || 0} calls`, 12)} ${pad(`${s.tokens || 0} tokens`, 18)} ${money(s.costUSD)}`); const by = (j.windows && j.windows["30d"] && j.windows["30d"].byUser) || {}; for (const [u, s] of Object.entries(by).slice(0, 10)) out(` ${pad(u, 18)} ${pad(`${s.calls} calls`, 12)} ${money(s.costUSD)}`); } }), "usage refusals": (a, o, A) => ({ method: "GET", path: `${A}/usage/refusals`, show: (j, out) => { for (const r of j.rows || []) out(`${pad(r.kind, 14)} ${pad(r.server, 14)} ${pad(r.tool, 24)} ${pad(`${r.refusals}x`, 5)} ${pad(`${r.people} people`, 10)} ${r.pattern}${r.muted ? " (expected)" : ""}`); out(`${(j.rows || []).length} rows`); } }), "usage mute": (a, o, A) => ({ method: "POST", path: `${A}/usage/refusals`, body: { mute: { kind: need(a[0], ""), server: need(a[1], ""), tool: need(a[2], "") } }, session: true, write: true, show: (j, out) => out(`${a[2]} on ${a[1]} in ${a[0]} is marked Expected`) }), "transcripts list": (a, o, A) => ({ method: "GET", path: `${A}/transcripts${qs({ user: o.user, kind: o.kind, since: o.since, limit: o.limit, cursor: o.cursor })}`, show: (j, out) => { for (const s of j.streams || []) out(`${when(s.lastAt)} ${pad(s.user, 18)} ${pad(s.kind, 14)} ${s.chat}`); out(`${(j.streams || []).length} chats (kept ${j.retentionDays || "forever"} days)${j.next ? `; more: --cursor ${j.next}` : ""}`); } }), "transcripts show": (a, o, A) => ({ method: "GET", path: `${A}/transcripts${qs({ user: idOf(a[0], ""), chat: need(a[1], ""), from: o.from, limit: o.limit })}`, show: (j, out) => { out(`${j.meta.user} · ${j.meta.kind} · ${j.meta.chat || a[1]}`); for (const e of j.events || []) out(` ${pad(e.seq, 5)} ${pad(e.type, 14)} ${typeof e.text === "string" ? e.text.slice(0, 160) : ""}`); } }), "devices list": (a, o, A) => ({ method: "GET", path: `${A}/devices`, show: (j, out) => { for (const d of j.devices || []) out(`${pad(d.id, 22)} ${pad(d.status, 9)} ${pad(d.userName || d.user, 18)} ${pad(d.label, 22)} ${d.fingerprint || ""}`); out(`${(j.devices || []).length} devices`); } }), "keys list": (a, o, A) => ({ method: "GET", path: `${A}/server-keys`, show: (j, out) => { for (const k of j.keys || []) out(`${pad(k.id, 22)} ${pad(k.standing, 8)} ${pad(k.label || (k.source === "config" ? "(setup)" : ""), 22)} ${pad((k.scopes || []).join(","), 30)} ${k.expiresAt ? `expires ${when(k.expiresAt)}` : "no expiry"}${k.lastUsedAt ? `, used ${when(k.lastUsedAt)}` : ""}`); out(`${(j.keys || []).length} keys`); } }), "keys revoke": (a, o, A) => ({ method: "DELETE", path: `${A}/server-keys/${idOf(a[0], "")}`, write: true, show: (j, out) => out(`${j.key.id} is ${j.key.standing}: anything signing with it is refused`) }), "credentials list": (a, o, A) => ({ method: "GET", path: `${A}/credentials`, show: (j, out) => { for (const c of j.credentials || []) out(`${pad(c.ref, 20)} ${pad(c.provider, 17)} ${pad(c.host || "", 24)} …${c.last4} set ${when(c.setAt)} by ${c.setBy && c.setBy.id}${c.checked === false ? " (not checked)" : ""}`); for (const n of j.needed || []) { const have = (j.credentials || []).find((c) => c.ref === n.ref); if (!have) out(`${pad(n.ref, 20)} missing: needed by ${n.streamlines.join(", ")}${n.host ? ` (a ${n.provider} key for ${n.host})` : ""}`); else if (n.host && have.host && n.host !== have.host) out(`${pad(n.ref, 20)} saved for ${have.host}, but ${n.streamlines.join(", ")} call ${n.host}: save it again for the new address`); } } }), "env status": (a, o, A) => ({ method: "GET", path: `${A}/env`, show: (j, out) => showEnv(j, out) }), "env staging": (a, o, A) => { const v = need(a[0], "on|off"); if (v !== "on" && v !== "off") throw new Usage("env staging on|off"); return { method: "PUT", path: `${A}/env/staging`, body: { on: v === "on" }, write: true, serverDryRun: true, show: (j, out) => showEnv(j, out) }; }, "config list": (a, o, A) => ({ method: "GET", path: `${A}/config${qs({ env: o.env })}`, show: (j, out) => { for (const f of j.files || []) out(`${pad(f.path, 44)} ${pad(f.bytes, 8)} ${String(f.sha256 || "").slice(0, 12)}`); out(`${(j.files || []).length} files${j.manifest ? `, manifest v${j.manifest.version}` : ""}${j.revision ? `, revision ${j.revision}` : ""}`); } }), "revisions list": (a, o, A) => ({ method: "GET", path: `${A}/revisions${qs({ env: o.env, limit: o.limit, before: o.before })}`, show: (j, out) => { for (const r of j.revisions || []) out(`${pad(r.revision, 5)} ${pad(r.environment, 8)} ${pad(r.kind, 9)} ${when(r.published)} ${pad(r.author && (r.author.name || r.author.id), 18)} ${(r.items || []).join(", ")}${r.title ? ` "${r.title}"` : ""}`); if (j.next) out(`more: --before ${j.next}`); } }), "revisions show": (a, o, A) => ({ method: "GET", path: `${A}/revisions/${intOf(a[0], "")}`, show: (j, out) => { out(`revision ${j.revision} on ${j.environment}: ${j.kind}${j.title ? ` "${j.title}"` : ""}, by ${j.author && (j.author.name || j.author.id)}, ${when(j.published)}, parent ${j.parent ?? "none"}`); if ((j.items || []).length) out(`items: ${j.items.join(", ")}`); for (const m of j.marks || []) out(`marked ${m.tested ? "tested" : "not tested"}: ${m.item} by ${m.name}`); } }), "revisions diff": (a, o, A) => ({ method: "GET", path: `${A}/revisions/${intOf(a[0], "")}/diff/${intOf(a[1], "")}`, show: (j, out) => { out(`revision ${j.from} → ${j.to}`); for (const f of j.files || []) { out(`${f.change} ${f.path}${f.item ? ` (${f.item})` : ""}${f.private ? " (private: contents only to a key)" : ""}`); for (const op of f.ops || []) out(` ${op.op} ${op.pointer || "/"}${"after" in op ? ` = ${JSON.stringify(op.after).slice(0, 100)}` : ""}`); for (const l of f.lines || []) out(` ${l}`); } if (!(j.files || []).length) out("no differences"); } }), presence: (a, o, A) => ({ method: "GET", path: `${A}/presence`, show: (j, out) => { for (const p of j.people || []) out(`${pad(p.name || p.user, 20)} ${(p.items || []).map((i) => i.item || i).join(", ")}`); out(`${(j.people || []).length} people with local changes`); } }), "deletion status": (a, o, A) => ({ method: "GET", path: `${A}/deletion`, session: true, show: (j, out) => out(j.deletion ? `scheduled by ${j.deletion.by && (j.deletion.by.name || j.deletion.by.id)} on ${when(j.deletion.scheduledAt)}; deletes ${when(j.deletion.deletesAt)}` : "not scheduled") }), "links list": (a, o, A, t) => ({ method: "GET", path: `/v1/directory/mine?tenant=${enc(t)}`, session: true, show: (j, out) => { for (const l of j.listings || []) out(`${pad(l.id, 16)} ${pad(l.name, 26)} v${l.version} ${l.link} by ${l.sharedBy && l.sharedBy.name}`); out(`${(j.listings || []).length} links; sharing ${j.organization && j.organization.sharing}`); } }), "links history": (a, o, A, t) => ({ method: "GET", path: `/v1/directory/listings/${idOf(a[0], "")}/history?tenant=${enc(t)}`, session: true, show: (j, out) => { for (const v of j.versions || []) out(`v${pad(v.version, 4)} ${pad(v.label || "", 8)} ${pad(when(v.published), 18)} by ${(v.publishedBy && v.publishedBy.name) || "(not recorded)"}${v.releaseNotes ? ` ${v.releaseNotes.slice(0, 60)}` : ""}`); out(`${(j.versions || []).length} versions of ${j.name || a[0]}${j.stopped ? `; stopped by ${j.stopped.by && j.stopped.by.name}` : ""}`); } }), "links stop": (a, o, A, t) => ({ method: "DELETE", path: `/v1/directory/listings/${idOf(a[0], "")}?tenant=${enc(t)}`, session: true, write: true, show: (j, out) => out(`${a[0]} is no longer shared`) }), // [web] web access (server/src/webaccess.js; docs/plans/web-client-phase1-plan.md §4.3): a server call, never config. "web status": (a, o, A) => ({ method: "GET", path: `${A}/web`, show: (j, out) => showWeb(j, out) }), "web reach": (a, o, A) => ({ method: "POST", path: `${A}/web/reach`, show: (j, out) => showReach(j.reach, out) }), "web on": (a, o, A) => ({ method: "PUT", path: `${A}/web`, body: { access: true }, write: true, serverDryRun: true, show: (j, out) => showWebSet(j, out) }), "web off": (a, o, A) => ({ method: "PUT", path: `${A}/web`, body: { access: false }, write: true, serverDryRun: true, show: (j, out) => showWebSet(j, out) }), // [tollfree] #192 (docs/plans/tollfree-streamline.md): the one `tollfree` block in a streamline's private agent file, // read and written whole through the admin route (the app, the Concierge and the mirror change the same block). With no // change flag it reads; with one it reads, changes what the flags name, checks, and publishes the whole block back as a // revision (config-schema §4.5.2, §8d): the Worker never signs, so it answers the next manifest (?dryRun=1), this client // signs it with the organization's publisher key and sends { tollfree, manifest, baseRevision }. tollfree: (a, o, A) => { const kind = idOf(a[0], ""), path = `${A}/streamlines/${kind}/tollfree`; if (o.on && o.off) throw new Usage("--on or --off, not both"); if (o.any && o.origin) throw new Usage("--origin or --any, not both"); if (!TOLLFREE_FLAGS.some((f) => o[f] != null && o[f] !== false)) return { method: "GET", path, show: (j, out) => showTollfree(kind, j, o, out, o.tag) }; return { method: "PUT", path, write: true, run: (ctx) => writeTollfree(kind, path, A, o, ctx) }; }, }; // ───────────────────────────── toll-free ───────────────────────────── const TOLLFREE_FLAGS = ["on", "off", "credential", "places", "origin", "any", "remove-origin", "budget", "per-visitor", "title", "subtitle", "words-out", "words-busy"]; const PLACES = ["embed", "site", "app"]; const PLACE_NAMES = { embed: "your sites", site: "Toll-free AI", app: "the Streamliner app" }; // What the Worker applies when a field is left out (config-schema *Toll-free*), shown so the person sees the real limits. const TOLLFREE_SHOWN = { places: { embed: false, site: true, app: true }, dailyUSD: 5, perVisitor: { burst: 6, hour: 40, day: 150, dailyUSD: 0.1 } }; const VISITOR_KEYS = { burst: "burst", hour: "hour", day: "day", usd: "dailyUSD" }; const ANY_SITE = "any website can put this chat on its pages, and your key pays for it"; const amount = (v, what) => { if (!/^\d+(\.\d+)?$/.test(String(v))) throw new Usage(`${what} is a number (${what === "--budget" ? "dollars a day" : "burst=6,hour=40,day=150,usd=0.10"})`); return Number(v); }; const usd = (n) => (typeof n !== "number" ? "" : Number.isInteger(Math.round(n * 1e6) / 1e4) ? `$${n.toFixed(2)}` : `$${n}`); /// The block the flags make from the current one (a copy; the current block is never changed). function applyTollfree(cur, o) { const b = JSON.parse(JSON.stringify(cur || { enabled: false })); if (o.on) b.enabled = true; if (o.off) b.enabled = false; if (o.credential != null) { // the name of a model key sealed on the account, never a key (and a key-shaped value is never echoed back) if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(o.credential) || /^(sk-|gsk_|AKIA)/.test(o.credential)) throw new Usage("--credential is the name of a model key set on the account (like anthropic-main), never the key itself"); b.credentialRef = o.credential; } if (o.places != null) { const want = o.places === "none" ? [] : o.places.split(",").map((x) => x.trim()).filter(Boolean); for (const p of want) if (!PLACES.includes(p)) throw new Usage(`--places lists embed, site and app (or none), not "${p}"`); b.places = Object.fromEntries(PLACES.map((p) => [p, want.includes(p)])); } if (o.any || o.origin || o["remove-origin"] || o.title != null || o.subtitle != null) b.embed = { ...(b.embed || {}) }; if (o.any) b.embed.origins = "any"; if (o.origin) { const now = Array.isArray(b.embed.origins) ? b.embed.origins : []; b.embed.origins = [...now, ...o.origin.filter((x, i, all) => !now.includes(x) && all.indexOf(x) === i)]; } for (const x of o["remove-origin"] || []) { if (b.embed.origins === "any") throw new Usage("embedding is open to any website now: list the sites it may be on with --origin instead"); if (!Array.isArray(b.embed.origins) || !b.embed.origins.includes(x)) throw new Usage(`${x} isn't one of the sites listed`); b.embed.origins = b.embed.origins.filter((y) => y !== x); } if (o.title != null) b.embed.title = o.title; if (o.subtitle != null) b.embed.subtitle = o.subtitle; if (o.budget != null || o["per-visitor"] != null) b.limits = { ...(b.limits || {}) }; if (o.budget != null) b.limits.dailyUSD = amount(o.budget, "--budget"); if (o["per-visitor"] != null) { b.limits.perVisitor = { ...(b.limits.perVisitor || {}) }; for (const part of o["per-visitor"].split(",").map((x) => x.trim()).filter(Boolean)) { const [k, v] = part.split("="); if (!VISITOR_KEYS[k]) throw new Usage(`--per-visitor takes burst=, hour=, day= and usd=, not "${k}"`); b.limits.perVisitor[VISITOR_KEYS[k]] = amount(v, "--per-visitor"); } } if (o["words-out"] != null || o["words-busy"] != null) b.words = { ...(b.words || {}) }; if (o["words-out"] != null) b.words.outOfAllowance = o["words-out"]; if (o["words-busy"] != null) b.words.busy = o["words-busy"]; return b; } /// What changed, one line per field: "~ /limits/dailyUSD 5 → 8". function leafDiff(a, b, at = "") { const obj = (v) => v && typeof v === "object" && !Array.isArray(v); if (obj(a) && obj(b)) return [...new Set([...Object.keys(a), ...Object.keys(b)])].flatMap((k) => leafDiff(a[k], b[k], `${at}/${k}`)); if (JSON.stringify(a) === JSON.stringify(b)) return []; const show = (v) => JSON.stringify(v).slice(0, 120); return [a === undefined ? `+ ${at} ${show(b)}` : b === undefined ? `- ${at}` : `~ ${at} ${show(a)} → ${show(b)}`]; } /// The config checker's own toll-free rules (runtime/configcheck.js checkTollfree, the ones the Worker's PUT runs): the /// checker beside this script (the repo's scripts/), the skill zip's scripts/vendor/, or a checkout above the current /// folder. → { problems: [text], notes: [text] }, or a Usage error when there is no checker to run. let foundCheck; async function tollfreeCheck(io) { if (io.checkTollfree) return io.checkTollfree; // a test's stand-in if (foundCheck) return foundCheck; const here = dirname(fileURLToPath(import.meta.url)), c = [join(here, "configcheck.mjs"), join(here, "vendor/scripts/configcheck.mjs")]; for (let d = resolve(process.cwd()); ; d = dirname(d)) { c.push(join(d, "scripts/configcheck.mjs")); if (dirname(d) === d) break; } const f = c.find((p) => existsSync(p)); if (!f) throw new Usage("no config checker here to check the block with: run it from the skill's folder as the zip unpacks it (scripts/vendor/), or inside a Streamliner checkout"); const lib = (await import(pathToFileURL(f).href)).checker(); return (foundCheck = (b, opts) => lib.checkTollfree(b, opts)); } async function checkTollfreeHere(block, got, { io, base }) { const notes = []; if (got.keyPresent === false && block.enabled) notes.push(`no model key "${block.credentialRef || ""}" is set on the account yet: set it in the app's Vault before visitors chat`); const check = await tollfreeCheck(io); const demo = /^http:\/\/(localhost|127\.0\.0\.1)(:|$)/.test(base); const issues = [...(check(block, { demo, ...(got.listed === false ? { listed: false } : {}), ...(got.linkOnly ? { linkOnly: true } : {}) }) || [])]; const line = (x) => `${x.pointer || "/"}: ${x.message}${x.fix ? ` (fix: ${x.fix})` : ""}`; return { problems: issues.filter((x) => !x.warning).map(line), notes: [...notes, ...issues.filter((x) => x.warning).map(line)] }; } const jcs = (v) => v === null || typeof v !== "object" ? JSON.stringify(v) : Array.isArray(v) ? "[" + v.map(jcs).join(",") + "]" : "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + jcs(v[k])).join(",") + "}"; /// The Worker's next manifest, signed with the publisher key the way sign-config.mjs signs one (Ed25519 over its JCS /// bytes without `signature`). → the manifest's text. export function signDraftManifest(draft, jwk, keyId) { const { signature, ...unsigned } = draft; const key = createPrivateKey({ key: { kty: "OKP", crv: "Ed25519", d: jwk.d, x: jwk.x }, format: "jwk" }); return JSON.stringify({ ...unsigned, signature: { alg: "Ed25519", keyId, sig: sign(null, Buffer.from(jcs(unsigned)), key).toString("base64url") } }, null, 2) + "\n"; } /// tollfree with a change flag: GET, change, check here, the Worker's prepare (?dryRun=1: nothing written, the next /// manifest to sign); with --yes, sign it and send { tollfree, manifest, baseRevision }. 409 behind (someone published /// meanwhile) reads everything again once. → the exit status. async function writeTollfree(kind, path, A, o, { send, refusal, out, err, io, base, account, bearer, read, exists }) { const usage = (m) => { err(`admin tollfree: ${m}\n(node scripts/admin.mjs --help)`); return 2; }; let pub = null; if (o.yes) { if (bearer) return usage("a toll-free change is published as a signed revision: it takes the server key (--key) and the organization's publisher key (--publisher-key), not a session"); const file = o["publisher-key"] || join(ROOT, "_local/keys", `${account}.publisher.jwk`); if (!exists(file)) return usage(`no publisher key at ${relative(process.cwd(), file) || file}: the change is a new revision, and its manifest is signed with one of the organization's publisher keys (--publisher-key )`); let jwk; try { jwk = JSON.parse(read(file)); } catch { return usage(`${file} isn't a JWK`); } if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || !jwk.d) return usage("the publisher key is an Ed25519 private JWK"); pub = jwk; } for (let attempt = 0; ; attempt++) { const g = await send("GET", path); if (!g.ok) return refusal(g); let block, c; try { block = applyTollfree(g.j.tollfree, o); c = await checkTollfreeHere(block, g.j, { io, base }); } catch (e) { if (e instanceof Usage) return usage(e.message); throw e; } if (attempt === 0) for (const n of c.notes) err(`note: ${n}`); if (c.problems.length) { for (const x of c.problems) err(` ${x}`); err("admin tollfree: the config checker refused it; nothing sent"); return 2; } const lines = leafDiff(g.j.tollfree || {}, block); if (!lines.length) { out("nothing to change"); return 0; } const p = await send("PUT", `${path}?dryRun=1`, { tollfree: block }); if (!o.yes) { if (o.json) { out(JSON.stringify({ dryRun: true, method: "PUT", path, body: { tollfree: block }, worker: { status: p.status, ...p.j } }, null, 2)); return p.ok ? 0 : 1; } out(`dry run: would publish PUT ${path} (the whole block, the manifest signed with the publisher key)`); for (const l of lines) out(` ${l}`); if (!p.ok) return refusal(p); out(` lands on ${where(p.j.env)} as revision ${p.j.nextRevision} (now ${p.j.baseRevision ?? "none"})`); out("nothing sent; add --yes to sign and send it"); return 0; } if (!p.ok) return refusal(p); if (p.j.unchanged) { out("nothing to change"); return 0; } if (!p.j.manifest) { err(`admin tollfree: ${where(p.j.env)} has no manifest to sign yet: publish the organization's config first`); return 1; } let keyId = o["publisher-key-id"] || pub.kid || (p.j.manifest.nextKeys || []).find((k) => k.pub === pub.x)?.keyId; if (!keyId) { const e = await send("GET", `${A}/config/enrolment.json${p.j.env === "staging" ? "?env=staging" : ""}`); keyId = e.ok ? (e.j.keys || []).find((k) => k.pub === pub.x)?.keyId : null; } if (!keyId) return usage(`that key isn't one of ${account}'s publisher keys (enrolment.json or the manifest's nextKeys): use the organization's publisher key, or --publisher-key-id `); const r = await send("PUT", path, { tollfree: block, manifest: signDraftManifest(p.j.manifest, pub, keyId), baseRevision: p.j.baseRevision }); if (r.status === 409 && r.j.error === "behind" && attempt === 0) { err(`note: ${where(p.j.env)} moved to revision ${r.j.current ?? "?"} meanwhile: reading the block again`); continue; } if (r.status === 409 && r.j.error === "unchanged") { out("nothing to change"); return 0; } if (r.status === 428) { err("refused: 428 signature_needed: the Worker didn't take the manifest as signed (nothing written)"); return 1; } if (r.status === 400 && r.j.error === "bad_manifest_signature") { err(`refused: 400 bad_manifest_signature: the publisher key isn't the organization's (key id ${keyId})`); return 1; } if (!r.ok) return refusal(r); if (o.json) { out(JSON.stringify(r.j, null, 2)); return 0; } out(`${kind}: saved as revision ${r.j.revision} on ${r.j.env === "staging" ? "Staging (promote it to make it Live)" : "Live"}`); showTollfree(kind, { ...g.j, tollfree: r.j.tollfree }, o, out, false); return 0; } } const where = (env) => (env === "staging" ? "Staging" : "Live"); /// The block in words. `tagOnly`: just the embed tag (so it can be piped into a page). function showTollfree(kind, j, o, out, tagOnly) { const t = j.tollfree; const tag = () => out(j.embedTag || `no embed tag: ${j.listed === false ? `${kind} isn't shared yet (share it by link, or publish it to Discover)` : "turn toll-free on with the embed place (--on --places embed,…) first"}`); if (tagOnly) return tag(); if (!t) out(`${kind}: not toll-free`); else { const pl = { ...TOLLFREE_SHOWN.places, ...(t.places || {}) }, L = t.limits || {}, V = { ...TOLLFREE_SHOWN.perVisitor, ...(L.perVisitor || {}) }; out(`${kind}: toll-free ${t.enabled ? "on" : "off"}; paid by ${t.credentialRef ? `the model key "${t.credentialRef}"${j.keyPresent === false ? " (not set on the account yet)" : j.keyPresent ? " (set)" : ""}` : "no model key named (--credential )"}`); out(` places: ${PLACES.map((p) => `${PLACE_NAMES[p]} ${pl[p] ? "on" : "off"}`).join(", ")}`); const origins = t.embed && t.embed.origins; if (pl.embed || origins) out(` embedded on: ${origins === "any" ? `any website (${ANY_SITE})` : Array.isArray(origins) && origins.length ? origins.join(", ") : "no sites listed yet (--origin )"}`); if (t.embed && (t.embed.title || t.embed.subtitle)) out(` embed title: ${t.embed.title || ""}${t.embed.subtitle ? ` · ${t.embed.subtitle}` : ""}`); out(` budget: ${usd(L.dailyUSD ?? TOLLFREE_SHOWN.dailyUSD)} a day`); out(` each visitor: ${V.burst} in 10 seconds, ${V.hour} an hour, ${V.day} a day, up to ${usd(V.dailyUSD)} a day`); if (t.words && t.words.outOfAllowance) out(` out of free questions: "${t.words.outOfAllowance}"`); if (t.words && t.words.busy) out(` busy: "${t.words.busy}"`); } if (j.env) out(` changes land on: ${where(j.env)}${j.live && j.env === "staging" ? ` (Live has it ${j.live.enabled ? "on" : "off"})` : ""}`); if (j.today) out(` today: ${usd(j.today.usedUSD || 0)} of ${usd(j.today.limitUSD)}`); if (j.listed != null) out(!j.listed ? " not shared: toll-free needs a link (its websites only) or a Discover listing" : j.linkOnly ? ` shared by link only${j.listing ? ` (${j.listing})` : ""}: toll-free on its named websites only, not Toll-free AI or the app` : ` listed publicly in Discover${j.listing ? ` (${j.listing})` : ""}`); if (o.tag) tag(); } // ───────────────────────────── web access ───────────────────────────── function showWeb(j, out) { out(`Web access: ${j.access ? "on" : "off"}${j.setBy ? ` (set by ${j.setBy.kind === "server" ? `the key ${j.setBy.id}` : j.setBy.id}, ${when(j.setAt)})` : ""}; the web app is ${j.address || (j.appHost ? `https://${j.appHost}` : ".streamliner.work")}`); if (!j.reach) out("Reach test: never run (web reach); turning web access on needs one from the last 7 days"); else showReach(j.reach, out); } function showReach(r, out) { if (!r) return; out(`Reach test: ${when(r.at)}${r.by ? ` by ${r.by.id}` : ""}${r.fresh === false ? " (older than 7 days: run web reach again before turning it on)" : ""}; ${r.ok} reachable, ${r.failing} not`); for (const x of r.rows || []) out(` ${x.ok ? "ok " : "no "} ${pad(x.type === "sealed" ? `form ${x.id}` : x.id, 22)} ${pad((x.streamlines || []).join(","), 22)} ${x.ok ? (Object.values(x.steps || {}).includes("same-origin") ? "Streamliner's own host" : x.url) : `${x.url}: ${x.why}`}`); if (r.failing) out(" Servers that aren't reachable stay \"In the app\" for members on the web; docs/mcp-authors.md §12 says what to allow."); } function showWebSet(j, out) { out(`${j.dryRun ? "Would turn" : j.unchanged ? "Already" : "Turned"} web access ${j.access ? "on" : "off"}`); if (j.access && (j.failing || []).length) out(` in the app only, not reachable from a browser: ${j.failing.map((x) => x.id).join(", ")}`); } function showEnv(j, out) { out(`Live: revision ${j.live && j.live.revision != null ? j.live.revision : "none"}${j.live && j.live.restoredFrom != null ? ` (restored from ${j.live.restoredFrom})` : ""}`); const s = j.staging || {}; out(s.on ? `Staging: on, revision ${s.revision}${s.aheadOfLive ? `, ${s.aheadOfLive} ahead of Live` : ""}${(s.hotfixPending || []).length ? `; hotfixes waiting to merge: ${s.hotfixPending.map((h) => h.revision).join(", ")}` : ""}` : "Staging: off"); if (j.dryRun) out("(the Worker checked it and would accept it; this is still the state now)"); } // ───────────────────────────── the request ───────────────────────────── /// Sign "streamline.admin.v1||||||" (config-schema §8b). export function signedHeaders({ account, method, path, bytes, keyId, privateKey, now = Date.now() }) { const ts = String(Math.floor(now / 1000)), nonce = randomBytes(18).toString("base64url"); const bodyHash = createHash("sha256").update(bytes).digest("hex"); const signature = sign(null, Buffer.from(`streamline.admin.v1|${account}|${method}|${path}|${bodyHash}|${ts}|${nonce}`), privateKey).toString("base64url"); return { "X-Streamline-Key": keyId, "X-Streamline-Timestamp": ts, "X-Streamline-Nonce": nonce, "X-Streamline-Signature": signature }; } function parse(argv) { const pos = [], o = {}; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "-h") { o.help = true; continue; } if (a.startsWith("--")) { const n = a.slice(2); if (BOOL_OPTS.has(n)) o[n] = true; else if (VALUE_OPTS.has(n)) { if (i + 1 >= argv.length) throw new Usage(`${a} needs a value`); o[n] = argv[++i]; } else if (LIST_OPTS.has(n)) { if (i + 1 >= argv.length) throw new Usage(`${a} needs a value`); (o[n] ||= []).push(argv[++i]); } else throw new Usage(`unknown option ${a}`); } else pos.push(a); } return { pos, o }; } /// The client. `io`: { fetch, out(line), err(line), env, readFile, exists } (servercheck passes its in-memory Worker's fetch). /// → the exit status. export async function main(argv, io = {}) { const out = io.out || ((s) => console.log(s)), err = io.err || ((s) => console.error(s)); const env = io.env || process.env, doFetch = io.fetch || fetch, read = io.readFile || ((p) => readFileSync(p, "utf8")), exists = io.exists || existsSync; let parsed; try { parsed = parse(argv); } catch (e) { err(`admin: ${e.message}\n(node scripts/admin.mjs --help)`); return 2; } const { pos, o } = parsed; if (o.help || pos[0] === "help" || !pos.length) { out(HELP); return o.help || pos[0] === "help" ? 0 : 2; } const [account, baseArg, ...rest] = pos; if (!/^[a-z0-9-]{3,40}$/.test(account || "")) { err(`admin: bad account "${account}"\n(node scripts/admin.mjs --help)`); return 2; } if (!/^https?:\/\/[^\s/]+/.test(baseArg || "")) { err("admin: the second argument is the Worker's base URL (http://localhost:8791, https://streamliner.work)"); return 2; } const base = baseArg.replace(/\/$/, ""); const name = COMMANDS[`${rest[0]} ${rest[1]}`] ? `${rest[0]} ${rest[1]}` : rest[0]; const make = COMMANDS[name]; if (!make) { err(`admin: unknown command "${rest.join(" ")}"\n(node scripts/admin.mjs --help)`); return 2; } const args = rest.slice(name.split(" ").length); let cmd; try { cmd = make(args, o, `/v1/admin/${account}`, account); } catch (e) { if (e instanceof Usage) { err(`admin ${name}: ${e.message}\n(node scripts/admin.mjs --help)`); return 2; } throw e; } // Credentials: a session from SL_ADMIN_BEARER, else the server key. Neither is ever printed. const bearer = (env.SL_ADMIN_BEARER || "").trim(); let key = null; if (cmd.session && !bearer) { err(`admin ${name}: this route takes an owner's or admin's session, never a server key: set SL_ADMIN_BEARER.`); return 2; } if (!bearer) { const file = o.key || join(ROOT, "_local/keys", `${account}.server-key.jwk`); if (!exists(file)) { err(`admin: no server key at ${relative(process.cwd(), file) || file} (--key : an owner makes one in the app, Organization → Keys → Server Keys; or SL_ADMIN_BEARER)`); return 2; } let jwk; try { jwk = JSON.parse(read(file)); } catch { err(`admin: ${file} isn't a JWK`); return 2; } const keyId = o["key-id"] || jwk.kid; if (!keyId) { err("admin: which key? --key-id (the id the account knows the public key by)"); return 2; } key = { keyId, privateKey: createPrivateKey({ key: { kty: "OKP", crv: "Ed25519", d: jwk.d, x: jwk.x }, format: "jwk" }) }; } const send = async (method, path, body) => { const bytes = body == null ? "" : JSON.stringify(body); const headers = { "Content-Type": "application/json", ...(bearer ? { Authorization: `Bearer ${bearer}` } : signedHeaders({ account, method, path, bytes, ...key })) }; const res = await doFetch(base + path, { method, headers, body: method === "GET" || method === "HEAD" ? undefined : bytes }); const text = await res.text(); let j; try { j = text ? JSON.parse(text) : {}; } catch { j = { error: "not_json", message: text.slice(0, 200) }; } return { status: res.status, ok: res.ok, j }; }; const refusal = (r) => { if (o.json) out(JSON.stringify({ status: r.status, ...r.j }, null, 2)); else err(`refused: ${r.status} ${r.j.error || ""}${r.j.message ? `: ${r.j.message}` : ""}${r.j.field ? ` (field ${r.j.field}${r.j.source ? `, set by the ${r.j.source}` : ""})` : ""}`); if (!o.json) for (const i of Array.isArray(r.j.issues) ? r.j.issues : []) err(` ${i.pointer || "/"}: ${i.message || i.code}${i.fix ? ` (fix: ${i.fix})` : ""}`); return 1; }; // A command that runs its own steps (tollfree: read, change, check, prepare, sign, send). if (cmd.run) return cmd.run({ send, refusal, out, err, io, base, account, bearer, read, exists }); if (cmd.write && !o.yes) { const what = `${cmd.method} ${cmd.path}${cmd.body ? ` ${JSON.stringify(cmd.body)}` : ""}`; let now = null, preview = null; if (cmd.current) { const r = await send("GET", cmd.current.path).catch(() => null); now = r && r.ok ? cmd.current.pick(r.j) : null; } if (cmd.serverDryRun) preview = await send(cmd.method, cmd.path + (cmd.path.includes("?") ? "&" : "?") + "dryRun=1", cmd.body); if (o.json) { out(JSON.stringify({ dryRun: true, method: cmd.method, path: cmd.path, ...(cmd.body ? { body: cmd.body } : {}), ...(preview ? { worker: { status: preview.status, ...preview.j } } : {}) }, null, 2)); return preview && !preview.ok ? 1 : 0; } out(`dry run: would send ${what}${now ? ` (${now})` : ""}`); if (preview) { if (!preview.ok) return refusal(preview); cmd.show(preview.j, (s) => out(` ${s}`)); } out("nothing sent; add --yes to send it"); return 0; } const r = await send(cmd.method, cmd.path, cmd.body); if (!r.ok) return refusal(r); if (o.json) out(JSON.stringify(r.j, null, 2)); else cmd.show(r.j, out); return 0; } export const COMMAND_NAMES = Object.keys(COMMANDS); if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) process.exitCode = await main(process.argv.slice(2));