benignswarm 0.12.92 → 0.12.94

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.
@@ -1,57 +1,178 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join } from "node:path";
4
5
  import { configRoot } from "./config.js";
5
6
  import { CliError } from "./errors.js";
6
- import { watcherPlists } from "./install.js";
7
- /**
8
- * Which agent each Antigravity conversation belongs to, on this machine. Antigravity's hooks are
9
- * configured per workspace, and one workspace often hosts several Antigravity agents (ester has
10
- * four), so the hook cannot take its identity from the workspace: it looks up the conversationId
11
- * every event carries. A conversation nobody bound gets nothing, never another agent's messages.
12
- */
13
- const file = () => join(configRoot(), "antigravity.json");
14
- const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
15
- function read() {
16
- if (!existsSync(file()))
17
- return { conversations: {} };
7
+ export function antigravityTotalTokens(usage) {
8
+ if (!usage)
9
+ return null;
10
+ if (typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens) && usage.total_tokens >= 0)
11
+ return usage.total_tokens;
12
+ return (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0) + (usage.thinking_tokens ?? 0) + (usage.cache_read_tokens ?? 0);
13
+ }
14
+ export const antigravityLog = (ref) => join(configRoot(), "logs", `antigravity.${ref.replace("/", ".")}.jsonl`);
15
+ export const antigravityConversationDb = (id, home = homedir()) => join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
16
+ const shq = (s) => (/^[\w./=:@-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
17
+ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritable = []) {
18
+ if (sandbox === "read-only")
19
+ throw new CliError("unsupported", "Antigravity has no read-only permission mode; use workspace-write or danger-full-access");
20
+ if (sandbox === "danger-full-access")
21
+ return ["--dangerously-skip-permissions"];
22
+ if (sandbox !== "workspace-write")
23
+ throw new CliError("usage", `unknown sandbox ${sandbox}`);
24
+ if (!/^[a-z0-9.-]+(?::\d+)?$/i.test(apiHost))
25
+ throw new CliError("usage", "the BenignSwarm API host is invalid for Antigravity sandbox permissions");
26
+ const dirs = [...new Set([dirname(cwd), b9sHome, ...extraWritable])];
27
+ return [
28
+ "--sandbox", "--settings",
29
+ JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow: [`read_url(${apiHost})`, "read_url(github.com)"] } }),
30
+ ...dirs.flatMap((dir) => ["--add-dir", dir]),
31
+ ];
32
+ }
33
+ export function antigravityTurnArgs(prompt, model, effort, timeoutSeconds, settings, conversation) {
34
+ return ["-p", prompt, "--output-format", "json", "--model", model, ...(effort ? ["--effort", effort] : []), "--print-timeout", `${timeoutSeconds}s`, ...(conversation ? ["--conversation", conversation] : []), ...settings];
35
+ }
36
+ export function antigravityResultError(result, raw, exitCode, expectedConversation) {
37
+ if (!result)
38
+ return raw.trim().slice(-500) || `agy exited ${exitCode ?? "without a result"} and did not return JSON`;
39
+ if (expectedConversation && result.conversation_id !== expectedConversation) {
40
+ return `agy resumed conversation ${expectedConversation} but returned ${result.conversation_id ?? "no conversation id"}; refusing to adopt a new conversation`;
41
+ }
42
+ if (result.status !== "SUCCESS") {
43
+ const detail = typeof result.error === "string" ? result.error : result.error ? JSON.stringify(result.error) : "";
44
+ return `agy turn ended with status ${result.status ?? "missing"}${detail ? `: ${detail}` : ""}`.slice(0, 500);
45
+ }
46
+ if (exitCode !== null && exitCode !== 0)
47
+ return `agy exited ${exitCode}`;
48
+ if (!result.conversation_id)
49
+ return "agy returned SUCCESS without a conversation_id";
50
+ return null;
51
+ }
52
+ export function parseAntigravityJson(output) {
53
+ const text = output.trim();
54
+ if (!text)
55
+ return null;
18
56
  try {
19
- return JSON.parse(readFileSync(file(), "utf8"));
57
+ const value = JSON.parse(text);
58
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
20
59
  }
21
60
  catch {
22
- throw new CliError("bad_antigravity_map", `${file()} is not valid JSON`, "Remove it and run: bschat antigravity sync");
61
+ return null;
23
62
  }
24
63
  }
25
- export function bindConversation(conversationId, ref) {
26
- if (!UUID.test(conversationId))
27
- throw new CliError("usage", `"${conversationId}" is not an Antigravity conversation id (a UUID)`);
28
- const m = read();
29
- m.conversations[conversationId.toLowerCase()] = ref;
30
- mkdirSync(dirname(file()), { recursive: true });
31
- writeFileSync(file(), JSON.stringify(m, null, 2) + "\n");
32
- }
33
- export function conversationAgent(conversationId) {
34
- return read().conversations[conversationId.toLowerCase()] ?? null;
35
- }
36
- /** The conversation an Antigravity wake command addresses (`agentapi send-message ... <id>`), if any. */
37
- export function conversationOfExec(exec) {
38
- return /agentapi\b/.test(exec) ? UUID.exec(exec)?.[0]?.toLowerCase() ?? null : null;
39
- }
40
- /** Binds every conversation an installed Antigravity watcher wakes to the agent it runs as. */
41
- export function syncFromWatchers() {
42
- const out = [];
43
- for (const w of watcherPlists()) {
44
- const r = spawnSync("plutil", ["-convert", "json", "-o", "-", w.path], { encoding: "utf8" });
45
- if (r.status !== 0)
46
- continue;
47
- const args = JSON.parse(r.stdout).ProgramArguments ?? [];
48
- const exec = args[args.indexOf("--exec") + 1] ?? "";
49
- const as = args[args.indexOf("--as") + 1];
50
- const conv = conversationOfExec(exec);
51
- if (conv && as && args.includes("--as")) {
52
- bindConversation(conv, as);
53
- out.push({ conversation: conv, agent: as });
64
+ export function recordAntigravityTurn(path, record) {
65
+ mkdirSync(dirname(path), { recursive: true });
66
+ appendFileSync(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
67
+ }
68
+ /** Explicit markers let commands launched by this turn inherit only this harness's sandbox workaround. */
69
+ export function antigravityTurnEnv(sandbox) {
70
+ return { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox };
71
+ }
72
+ export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConversation, run = spawnSync, envOverride = {}) {
73
+ const started = new Date().toISOString();
74
+ const model = args[args.indexOf("--model") + 1];
75
+ const effortIndex = args.indexOf("--effort");
76
+ const effort = effortIndex >= 0 ? args[effortIndex + 1] : undefined;
77
+ const result = run(bin, args, { encoding: "utf8", timeout: 24 * 60 * 60_000, maxBuffer: 8 * 1024 * 1024, cwd, env: { ...process.env, BSCHAT_AGENT: agent, ...(model ? { BSCHAT_MODEL: model } : {}), ...(effort ? { BSCHAT_EFFORT: effort } : {}), ...envOverride } });
78
+ const output = result.stdout ?? "";
79
+ const parsed = parseAntigravityJson(output);
80
+ const record = {
81
+ started_at: started,
82
+ finished_at: new Date().toISOString(),
83
+ exit_code: result.status,
84
+ ...(expectedConversation ? { expected_conversation: expectedConversation } : {}),
85
+ ...(model ? { model } : {}),
86
+ ...(parsed ? { result: parsed } : { raw: [output, result.stderr].filter(Boolean).join("\n").slice(-4000) }),
87
+ };
88
+ recordAntigravityTurn(logPath, record);
89
+ const error = antigravityResultError(parsed, output || result.stderr || "", result.status, expectedConversation);
90
+ if (result.error || error) {
91
+ const detail = result.error?.message ?? error;
92
+ throw new CliError("agy_failed", `agy turn failed${expectedConversation ? ` for conversation ${expectedConversation}` : ""}: ${detail}; output logged at ${logPath}`);
93
+ }
94
+ return { conversation: parsed.conversation_id, record, output };
95
+ }
96
+ export function antigravityResumeCommand(bin, session, model, effort, timeoutSeconds, settings, logPath) {
97
+ const tmp = `${logPath}.pending`;
98
+ const err = `${logPath}.stderr`;
99
+ const base = [bin, "-p", "{text}", "--output-format", "json", "--model", model, ...(effort ? ["--effort", effort] : []), "--print-timeout", `${timeoutSeconds}s`, "--conversation", session, ...settings].map((arg) => arg === "{text}" ? arg : shq(arg)).join(" ");
100
+ const script = `const fs=require('node:fs');const [tmp,err,log,status,started,expected,model]=process.argv.slice(1);const raw=fs.readFileSync(tmp,'utf8');const stderr=fs.readFileSync(err,'utf8');let result;try{result=JSON.parse(raw)}catch{}const record={started_at:started,finished_at:new Date().toISOString(),exit_code:Number(status),expected_conversation:expected,model,...(result?{result}:{raw:(raw+'\\n'+stderr).slice(-4000)})};fs.appendFileSync(log,JSON.stringify(record)+'\\n',{mode:0o600});fs.rmSync(tmp,{force:true});fs.rmSync(err,{force:true});`;
101
+ const node = `${shq(process.execPath)} -e ${shq(script)} ${shq(tmp)} ${shq(err)} ${shq(logPath)} "$agy_status" "$agy_started" ${shq(session)} ${shq(model)}`;
102
+ return `agy_started=$(date -u +%Y-%m-%dT%H:%M:%SZ); ${base} > ${shq(tmp)} 2> ${shq(err)}; agy_status=$?; ${node}; exit "$agy_status"`;
103
+ }
104
+ function agyRecords(path) {
105
+ if (!existsSync(path))
106
+ return [];
107
+ return readFileSync(path, "utf8").split("\n").flatMap((line) => {
108
+ try {
109
+ return [JSON.parse(line)];
110
+ }
111
+ catch {
112
+ return [];
54
113
  }
114
+ });
115
+ }
116
+ function antigravityError(record, session) {
117
+ if (!record)
118
+ return "agy has not recorded a completed turn";
119
+ return antigravityResultError(record.result ?? null, record.raw ?? "", record.exit_code, record.expected_conversation ?? session);
120
+ }
121
+ export function isAntigravityCommand(args) {
122
+ const first = /^(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(args.trim());
123
+ const executable = first?.[1] ?? first?.[2] ?? first?.[3];
124
+ return executable !== undefined && basename(executable) === "agy";
125
+ }
126
+ export function antigravityProcesses(session, psOutput) {
127
+ const output = psOutput ?? spawnSync("ps", ["-axo", "pid=,args="], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 }).stdout ?? "";
128
+ const found = [];
129
+ for (const line of output.split("\n")) {
130
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
131
+ if (!match || Number(match[1]) === process.pid || !isAntigravityCommand(match[2]))
132
+ continue;
133
+ if (new RegExp(`(?:^|\\s)--conversation\\s+['\"]?${session.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")}['\"]?(?:\\s|$)`).test(match[2]))
134
+ found.push({ pid: Number(match[1]), args: match[2] });
55
135
  }
56
- return out;
136
+ return found;
137
+ }
138
+ export function antigravityProbe(session, ref, logPath = antigravityLog(ref), conversationPath = antigravityConversationDb(session), processes = antigravityProcesses) {
139
+ const last = () => agyRecords(logPath).at(-1);
140
+ return {
141
+ label: "Antigravity", what: `conversation ${session}`,
142
+ phase() {
143
+ if (!existsSync(conversationPath))
144
+ return { missing: `no Antigravity conversation database ${conversationPath}; cannot tell whether conversation ${session} is running` };
145
+ const running = processes(session).length > 0;
146
+ const lastRecord = last();
147
+ const at = statSync(conversationPath).mtime.toISOString();
148
+ return { running, startedAt: at, lastEventAt: at, lastError: running ? null : antigravityError(lastRecord, session), lastErrorAt: lastRecord?.finished_at ?? null };
149
+ },
150
+ startedSince(ms) { return existsSync(conversationPath) && statSync(conversationPath).mtimeMs >= ms - 5_000; },
151
+ turnError() { return antigravityError(last(), session); },
152
+ turnOutput() { const result = last()?.result; return (result?.response ?? last()?.raw ?? "").slice(-800); },
153
+ turnTokens() { return antigravityTotalTokens(last()?.result?.usage); },
154
+ limitUntil: () => null,
155
+ isLimit: (error) => !!error && /usage limit|quota|resource exhausted/i.test(error),
156
+ };
157
+ }
158
+ export function antigravityUsage(path, since, until) {
159
+ const from = Date.parse(since), to = Date.parse(until);
160
+ const rows = agyRecords(path).filter((record) => Date.parse(record.started_at) >= from && Date.parse(record.started_at) <= to && record.result?.usage);
161
+ if (!rows.length)
162
+ return null;
163
+ const totals = { input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 };
164
+ for (const { result } of rows) {
165
+ const usage = result.usage;
166
+ const cached = usage.cache_read_tokens ?? 0;
167
+ totals.input += (usage.input_tokens ?? 0) + cached;
168
+ totals.cached_input += cached;
169
+ totals.output += usage.output_tokens ?? 0;
170
+ totals.reasoning += usage.thinking_tokens ?? 0;
171
+ totals.total += antigravityTotalTokens(usage) ?? 0;
172
+ }
173
+ return totals;
174
+ }
175
+ export function appendAntigravityRawResult(path, output, exitCode, expectedConversation) {
176
+ const result = parseAntigravityJson(output);
177
+ recordAntigravityTurn(path, { started_at: new Date().toISOString(), finished_at: new Date().toISOString(), exit_code: exitCode, ...(expectedConversation ? { expected_conversation: expectedConversation } : {}), ...(result ? { result } : { raw: output.slice(-4000) }) });
57
178
  }
package/dist/args.js CHANGED
@@ -2,8 +2,8 @@ import { parseArgs } from "node:util";
2
2
  import { CliError } from "./errors.js";
3
3
  // These options accept comma-separated collections, so repeating them should
4
4
  // append another collection instead of discarding earlier values.
5
- export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks"];
6
- export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks"];
5
+ export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "writable-root", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks", "confirm-causes"];
6
+ export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "max-budget-usd", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes"];
7
7
  export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted", "no-source", "allow-lower-tier"];
8
8
  export function parse(argv) {
9
9
  const options = {};
@@ -25,7 +25,15 @@ export function parse(argv) {
25
25
  }
26
26
  const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
27
27
  const flags = values;
28
- return { positionals, flags: Object.fromEntries(Object.entries(flags).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : v])) };
28
+ const repeatValues = {};
29
+ for (const [key, value] of Object.entries(flags))
30
+ if (Array.isArray(value))
31
+ repeatValues[key] = value;
32
+ return {
33
+ positionals,
34
+ flags: Object.fromEntries(Object.entries(flags).map(([k, v]) => [k, Array.isArray(v) ? v.join(",") : v])),
35
+ repeated: repeatValues,
36
+ };
29
37
  }
30
38
  catch (e) {
31
39
  if (e instanceof CliError)
@@ -37,6 +45,9 @@ export function str(flags, k) {
37
45
  const v = flags[k];
38
46
  return typeof v === "string" ? v : undefined;
39
47
  }
48
+ export function repeated(parsed, k) {
49
+ return parsed.repeated?.[k] ?? [];
50
+ }
40
51
  export function bool(flags, k) {
41
52
  return flags[k] === true;
42
53
  }
package/dist/brief.js CHANGED
@@ -49,7 +49,7 @@ export function formatRecoveryBrief(brief) {
49
49
  lines.push("Questions waiting on you:");
50
50
  lines.push(...(brief.questions.length ? brief.questions.map((q) => ` ${q.project} WU #${q.number} (${q.age_minutes ?? 0} min ago): ${q.question} — ${q.next}`) : [" none"]));
51
51
  lines.push("Units:");
52
- lines.push(...(brief.units.length ? brief.units.map((u) => ` [${u.state}] ${u.project} WU #${u.number} ${u.title}${scope(u.base_scope, u.scope_amendments, u.scope_amendments_omitted)} — ${u.next}`) : [" none"]));
52
+ lines.push(...(brief.units.length ? brief.units.map((u) => ` [${u.state}] ${u.project} WU #${u.number} ${u.title}${scope(u.base_scope, u.scope_amendments, u.scope_amendments_omitted)}${u.recovery ? `\n Recovery: ${u.recovery.available ? `available (${u.recovery.size ?? "?"} bytes, sha256 ${u.recovery.sha256 ?? "?"})` : "not verified"}${u.recovery.expires_at ? `, expires ${u.recovery.expires_at}` : ""}${u.recovery.manifest?.skipped.length ? `, ${u.recovery.manifest.skipped.length} regenerable path(s) skipped` : ""}${u.recovery.manifest?.omitted.length ? `, ${u.recovery.manifest.omitted.length} file(s) remain uncaptured` : ""}; restore: b9s wu recovery restore ${u.number}` : ""} — ${u.next}`) : [" none"]));
53
53
  lines.push("Reviews waiting on you:");
54
54
  lines.push(...(brief.reviews.length ? brief.reviews.map((r) => ` ${r.project} ${r.slice ? `slice ${r.slice}` : `WU #${r.number}`} ${r.title}${scope(r.base_scope, r.scope_amendments, r.scope_amendments_omitted)} — ${r.next}`) : [" none"]));
55
55
  lines.push("Open asks:");
package/dist/client.js CHANGED
@@ -39,6 +39,26 @@ export class Client {
39
39
  h["x-bschat-machine"] = this.machineIdentity;
40
40
  return h;
41
41
  }
42
+ async raw(method, path, body, extraHeaders = {}) {
43
+ let response;
44
+ try {
45
+ response = await fetch(this.url + path, { method, headers: { ...this.headers(), ...extraHeaders }, body });
46
+ }
47
+ catch (e) {
48
+ throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
49
+ }
50
+ noteServerVersions(response.headers, this.agentName);
51
+ if (!response.ok) {
52
+ const text = await response.text();
53
+ let json = { error: `http_${response.status}`, message: text.slice(0, 500) };
54
+ try {
55
+ json = JSON.parse(text);
56
+ }
57
+ catch { /* keep response text */ }
58
+ throw new CliError(json.error, json.message);
59
+ }
60
+ return response;
61
+ }
42
62
  /**
43
63
  * opts.retries: how many times to retry on a network failure or a 5xx. Only safe for calls
44
64
  * that are idempotent on the server (posts carry a client_id for exactly this reason).