sinatra.dev 0.3.1 → 0.4.0
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.
- package/README.md +245 -13
- package/dist/client.js +75 -10
- package/dist/commands.js +613 -6
- package/dist/index.js +308 -16
- package/dist/oauth.js +6 -2
- package/dist/prompt.js +10 -6
- package/dist/version.js +4 -0
- package/package.json +1 -1
package/dist/commands.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/** The CLI's decisions that don't touch the terminal: what was asked for, and what to send. */
|
|
2
2
|
import { parseArgs } from "node:util";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
3
4
|
import { ApiError, createClient } from "./client.js";
|
|
4
5
|
import { ConfigError, DEFAULT_API_URL, DEFAULT_APP_URL } from "./config.js";
|
|
5
6
|
import { DEFAULT_FOLLOW_TIMEOUT_MS } from "./follow.js";
|
|
@@ -23,6 +24,10 @@ export class UsageError extends Error {
|
|
|
23
24
|
* never a word of a prompt, which is shorter.
|
|
24
25
|
*/
|
|
25
26
|
const TASK_ID = /^[a-z0-9][a-z0-9_-]{19,63}$/;
|
|
27
|
+
const SUBSCRIPTIONS_USAGE = "Usage: sinatra subscriptions [list | connect <codex|claude|xai|cursor> | remove <id>] [--json] [-w <id>]. Paste Claude's authorization code at the hidden prompt or through stdin, never on the command line.";
|
|
28
|
+
const CONNECT_USAGE = "Usage: sinatra connect <github|linear|slack|telegram> [-w <id>] [--timeout <minutes>] [--json]. Authorization happens in your browser; never supply secrets on the command line.";
|
|
29
|
+
const WORKSPACE_CREATE_USAGE = 'Usage: sinatra workspace create "<name>" [--json]. Quote a name with spaces.';
|
|
30
|
+
const REPO_USAGE = "Usage: sinatra repo <owner/name> config [preflight --file <json>] | override set --file <json> | override clear [--yes] | secrets [list | set <name> --host <host> | rotate <name> | update <name> | delete <name> --yes] | env | capability-requests | review-external-prs [inherit|on|off] [-w <id>] [--json]. Secret values belong only at the hidden prompt or on stdin, never in arguments or flags.";
|
|
26
31
|
/**
|
|
27
32
|
* What the arguments ask for. A command word counts only in the shape that command takes, so
|
|
28
33
|
* `sinatra stop retrying on 429` or `sinatra logout the user on expiry` start tasks instead of
|
|
@@ -35,11 +40,104 @@ export function parseCommand(positionals) {
|
|
|
35
40
|
if (!first)
|
|
36
41
|
return { name: "help" };
|
|
37
42
|
const usage = (message) => ({ name: "usage", message });
|
|
43
|
+
if (first === "workspace" && rest[0] === "review-external-prs") {
|
|
44
|
+
if (rest.length === 1)
|
|
45
|
+
return { name: "workspace-pr-review" };
|
|
46
|
+
if (rest.length === 2 && (rest[1] === "on" || rest[1] === "off")) {
|
|
47
|
+
return { name: "workspace-pr-review", value: rest[1] === "on" };
|
|
48
|
+
}
|
|
49
|
+
return usage("Usage: sinatra workspace review-external-prs [on|off] [-w <id>] [--json]");
|
|
50
|
+
}
|
|
51
|
+
if (first === "repos")
|
|
52
|
+
return rest.length === 0 ? { name: "repos" } : usage("Usage: sinatra repos [-w <id>] [--json]");
|
|
53
|
+
if (first === "repo") {
|
|
54
|
+
const [repoName, section, action, secretName] = rest;
|
|
55
|
+
if (!repoName || !/^[\w.-]+\/[\w.-]+$/.test(repoName))
|
|
56
|
+
return usage(REPO_USAGE);
|
|
57
|
+
if (section === "review-external-prs") {
|
|
58
|
+
if (rest.length === 2)
|
|
59
|
+
return { name: "repo", repoName, action: "review-external-prs" };
|
|
60
|
+
if (rest.length === 3 && (action === "inherit" || action === "on" || action === "off")) {
|
|
61
|
+
return { name: "repo", repoName, action: "review-external-prs", value: action };
|
|
62
|
+
}
|
|
63
|
+
return usage(REPO_USAGE);
|
|
64
|
+
}
|
|
65
|
+
if (rest.length === 2 && ["config", "env", "capability-requests"].includes(section)) {
|
|
66
|
+
return { name: "repo", repoName, action: section };
|
|
67
|
+
}
|
|
68
|
+
if (rest.length === 3 && section === "config" && action === "preflight")
|
|
69
|
+
return { name: "repo", repoName, action: "preflight" };
|
|
70
|
+
if (rest.length === 3 && section === "override" && (action === "set" || action === "clear"))
|
|
71
|
+
return { name: "repo", repoName, action: action === "set" ? "override-set" : "override-clear" };
|
|
72
|
+
if (section === "secrets") {
|
|
73
|
+
if (rest.length === 2 || (rest.length === 3 && action === "list"))
|
|
74
|
+
return { name: "repo", repoName, action: "secrets-list" };
|
|
75
|
+
if (rest.length === 4 && ["set", "rotate", "update", "delete"].includes(action) && secretName) {
|
|
76
|
+
return { name: "repo", repoName, action: `secrets-${action}`, secretName };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return usage(REPO_USAGE);
|
|
80
|
+
}
|
|
81
|
+
if (first === "connect") {
|
|
82
|
+
if (rest.length === 1 && ["github", "linear", "slack", "telegram"].includes(rest[0])) {
|
|
83
|
+
return { name: "connect", integration: rest[0] };
|
|
84
|
+
}
|
|
85
|
+
return usage(CONNECT_USAGE);
|
|
86
|
+
}
|
|
87
|
+
if (first === "billing") {
|
|
88
|
+
if (rest.length === 0)
|
|
89
|
+
return { name: "billing", action: "status" };
|
|
90
|
+
if (rest.length === 1 && (rest[0] === "upgrade" || rest[0] === "portal"))
|
|
91
|
+
return { name: "billing", action: rest[0] };
|
|
92
|
+
return usage("Usage: sinatra billing [upgrade --plan <pro|team|scale> | portal]");
|
|
93
|
+
}
|
|
94
|
+
if (first === "members" || first === "invite" || first === "requests" || (first === "workspace" && rest[0] === "leave")) {
|
|
95
|
+
if (first === "workspace" && rest.length === 1)
|
|
96
|
+
return { name: "access", action: "leave" };
|
|
97
|
+
if (first === "members" && rest.length === 1 && rest[0] === "list")
|
|
98
|
+
return { name: "access", action: "list" };
|
|
99
|
+
if (first === "invite" && rest.length === 1 && rest[0] !== "resend" && rest[0] !== "revoke")
|
|
100
|
+
return { name: "access", action: "invite", target: rest[0] };
|
|
101
|
+
const action = rest[0];
|
|
102
|
+
if (rest.length === 2 && ((first === "invite" && (action === "resend" || action === "revoke")) ||
|
|
103
|
+
(first === "requests" && (action === "approve" || action === "deny")) ||
|
|
104
|
+
(first === "members" && (action === "role" || action === "remove" || action === "transfer"))))
|
|
105
|
+
return { name: "access", action: action, target: rest[1] };
|
|
106
|
+
return usage("Invalid workspace access command. Run `sinatra --help` for usage.");
|
|
107
|
+
}
|
|
108
|
+
if (first === "model") {
|
|
109
|
+
if (rest.length === 0 || (rest.length === 1 && rest[0] === "get"))
|
|
110
|
+
return { name: "model", action: "get" };
|
|
111
|
+
if (rest.length === 1 && rest[0] === "clear")
|
|
112
|
+
return { name: "model", action: "clear" };
|
|
113
|
+
if (rest.length === 2 && rest[0] === "set")
|
|
114
|
+
return { name: "model", action: "set", model: rest[1] };
|
|
115
|
+
return usage("Usage: sinatra model [get | set <model> --engine <engine> [--effort <effort>] | clear]");
|
|
116
|
+
}
|
|
117
|
+
if (first === "keys") {
|
|
118
|
+
if (rest.length === 0 || (rest.length === 1 && rest[0] === "list"))
|
|
119
|
+
return { name: "keys", action: "list" };
|
|
120
|
+
if (rest.length === 2 && (rest[0] === "add" || rest[0] === "remove") && (rest[1] === "anthropic" || rest[1] === "openrouter")) {
|
|
121
|
+
return { name: "keys", action: rest[0], provider: rest[1] };
|
|
122
|
+
}
|
|
123
|
+
return usage("Usage: sinatra keys [list | add <anthropic|openrouter> | remove <anthropic|openrouter>]. Never put a key in arguments or flags; paste it at the hidden prompt or pipe it on stdin.");
|
|
124
|
+
}
|
|
38
125
|
// More than a word after the command word (`stop retrying on 429`, `show "me why it fails"`).
|
|
39
126
|
const prose = rest.length >= 2 || (rest.length === 1 && /\s/.test(rest[0]));
|
|
40
127
|
switch (first) {
|
|
41
128
|
case "start":
|
|
42
129
|
return rest.length > 0 ? { name: "start", prompt: rest.join(" ").trim() } : usage('Usage: sinatra start "<what to do>"');
|
|
130
|
+
case "subscriptions":
|
|
131
|
+
if (rest.length === 0 || (rest.length === 1 && rest[0] === "list"))
|
|
132
|
+
return { name: "subscriptions", action: "list" };
|
|
133
|
+
if (rest.length === 2 && rest[0] === "connect" && ["codex", "claude", "xai", "cursor"].includes(rest[1])) {
|
|
134
|
+
return { name: "subscriptions", action: "connect", provider: rest[1] };
|
|
135
|
+
}
|
|
136
|
+
if (rest.length === 2 && rest[0] === "remove" && rest[1].trim()) {
|
|
137
|
+
return { name: "subscriptions", action: "remove", connectionId: rest[1] };
|
|
138
|
+
}
|
|
139
|
+
// Unlike natural-language task shortcuts, subscription mistakes must never spend a task.
|
|
140
|
+
return usage(SUBSCRIPTIONS_USAGE);
|
|
43
141
|
case "help":
|
|
44
142
|
case "version":
|
|
45
143
|
if (rest.length === 0)
|
|
@@ -48,6 +146,8 @@ export function parseCommand(positionals) {
|
|
|
48
146
|
case "login":
|
|
49
147
|
case "logout":
|
|
50
148
|
case "whoami":
|
|
149
|
+
case "account":
|
|
150
|
+
case "email-preferences":
|
|
51
151
|
case "tasks":
|
|
52
152
|
case "tickets":
|
|
53
153
|
if (rest.length === 0)
|
|
@@ -59,6 +159,12 @@ export function parseCommand(positionals) {
|
|
|
59
159
|
return usage(`Usage: sinatra ${first}`);
|
|
60
160
|
break;
|
|
61
161
|
case "workspace":
|
|
162
|
+
if (rest.length === 1 && rest[0] === "show")
|
|
163
|
+
return { name: "workspace-show" };
|
|
164
|
+
// One quoted name. Anything else is a mistake to explain, never a workspace or a task.
|
|
165
|
+
if (rest[0] === "create") {
|
|
166
|
+
return rest.length === 2 && rest[1].trim() ? { name: "workspace-create", workspaceName: rest[1] } : usage(WORKSPACE_CREATE_USAGE);
|
|
167
|
+
}
|
|
62
168
|
if (rest.length === 0)
|
|
63
169
|
return { name: "workspace" };
|
|
64
170
|
if (!prose)
|
|
@@ -94,10 +200,22 @@ const OPTIONS = {
|
|
|
94
200
|
query: { type: "string", short: "q" },
|
|
95
201
|
file: { type: "string", short: "f", multiple: true },
|
|
96
202
|
title: { type: "string", short: "t" },
|
|
203
|
+
model: { type: "string", short: "m" },
|
|
204
|
+
engine: { type: "string" },
|
|
205
|
+
effort: { type: "string" },
|
|
97
206
|
workspace: { type: "string", short: "w" },
|
|
207
|
+
role: { type: "string" },
|
|
208
|
+
plan: { type: "string" },
|
|
209
|
+
host: { type: "string", multiple: true },
|
|
210
|
+
header: { type: "string" },
|
|
211
|
+
prefix: { type: "string" },
|
|
212
|
+
"capability-request": { type: "string" },
|
|
213
|
+
yes: { type: "boolean", short: "y" },
|
|
98
214
|
"no-wait": { type: "boolean" },
|
|
99
215
|
timeout: { type: "string" },
|
|
100
216
|
json: { type: "boolean" },
|
|
217
|
+
"setup-reminders": { type: "string" },
|
|
218
|
+
"task-alerts": { type: "string" },
|
|
101
219
|
status: { type: "string" },
|
|
102
220
|
limit: { type: "string", short: "n" },
|
|
103
221
|
"api-url": { type: "string" },
|
|
@@ -110,18 +228,176 @@ const OPTIONS = {
|
|
|
110
228
|
const APPLIES_TO = {
|
|
111
229
|
repo: ["start", "tickets"],
|
|
112
230
|
query: ["tickets"],
|
|
113
|
-
file: ["start", "reply"],
|
|
231
|
+
file: ["start", "reply", "repo"],
|
|
114
232
|
title: ["start"],
|
|
115
|
-
|
|
233
|
+
model: ["start"],
|
|
234
|
+
workspace: ["start", "reply", "show", "workspace-show", "workspace-pr-review", "tasks", "stop", "tickets", "delegate", "login", "access", "subscriptions", "model", "keys", "billing", "connect", "repos", "repo"],
|
|
116
235
|
"no-wait": ["start", "reply"],
|
|
117
|
-
timeout: ["start", "reply"],
|
|
118
|
-
json: ["whoami", "tasks", "show", "start", "reply", "tickets"],
|
|
236
|
+
timeout: ["start", "reply", "connect"],
|
|
237
|
+
json: ["whoami", "account", "email-preferences", "tasks", "show", "workspace-show", "workspace-create", "workspace-pr-review", "start", "reply", "tickets", "access", "subscriptions", "model", "keys", "billing", "connect", "repos", "repo"],
|
|
238
|
+
"setup-reminders": ["email-preferences"],
|
|
239
|
+
"task-alerts": ["email-preferences"],
|
|
119
240
|
status: ["tasks"],
|
|
120
241
|
limit: ["tasks"],
|
|
121
242
|
"api-url": ["login"],
|
|
122
243
|
token: ["login"],
|
|
123
|
-
"no-browser": ["login"],
|
|
244
|
+
"no-browser": ["login", "subscriptions"],
|
|
245
|
+
role: ["access"],
|
|
246
|
+
yes: ["access", "model", "keys", "repo"],
|
|
247
|
+
engine: ["model"],
|
|
248
|
+
effort: ["model"],
|
|
249
|
+
plan: ["billing"],
|
|
250
|
+
host: ["repo"],
|
|
251
|
+
header: ["repo"],
|
|
252
|
+
prefix: ["repo"],
|
|
253
|
+
"capability-request": ["repo"],
|
|
124
254
|
};
|
|
255
|
+
function requiresConfirmation(command) {
|
|
256
|
+
return (command.name === "access" && ["revoke", "remove", "transfer", "leave"].includes(command.action))
|
|
257
|
+
|| (command.name === "model" && command.action === "clear")
|
|
258
|
+
|| (command.name === "keys" && command.action === "remove")
|
|
259
|
+
|| (command.name === "repo" && (command.action === "override-clear" || command.action === "secrets-delete"));
|
|
260
|
+
}
|
|
261
|
+
/** Refusals fail closed before the caller sends a workspace mutation. */
|
|
262
|
+
export async function confirmWorkspaceMutation(command, options) {
|
|
263
|
+
if (!requiresConfirmation(command) || options.yes)
|
|
264
|
+
return;
|
|
265
|
+
if (!options.interactive)
|
|
266
|
+
throw new UsageError("This action requires confirmation. Run at a terminal or pass --yes.");
|
|
267
|
+
const action = command.name === "access"
|
|
268
|
+
? `${command.action}${command.target ? ` ${command.target}` : ""}`
|
|
269
|
+
: command.name === "keys" && command.action === "remove"
|
|
270
|
+
? `remove ${command.provider} key`
|
|
271
|
+
: command.name === "repo"
|
|
272
|
+
? `${command.action} in ${command.repoName}${"secretName" in command ? ` (${command.secretName})` : ""}`
|
|
273
|
+
: "clear model default";
|
|
274
|
+
const answer = await options.ask(printable(`Confirm ${action} in workspace ${options.workspaceId}? [y/N] `));
|
|
275
|
+
if (!/^(y|yes)$/i.test(answer.trim()))
|
|
276
|
+
throw new UsageError("Cancelled. Nothing changed.");
|
|
277
|
+
}
|
|
278
|
+
/** Keys enter through an injected hidden prompt/stdin reader, never through command arguments. */
|
|
279
|
+
export async function addWorkspaceModelKey(client, workspaceId, provider, readSecret) {
|
|
280
|
+
let apiKey;
|
|
281
|
+
try {
|
|
282
|
+
apiKey = (await readSecret("API key (hidden): ")).trim();
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
throw new UsageError("Couldn't read the API key. Paste it at the hidden prompt or pipe it on stdin.");
|
|
286
|
+
}
|
|
287
|
+
if (!apiKey)
|
|
288
|
+
throw new UsageError("No API key supplied. Nothing changed.");
|
|
289
|
+
return client.addModelKey(workspaceId, provider, apiKey);
|
|
290
|
+
}
|
|
291
|
+
/** Only an absent provider key is a successful no-op; an inaccessible workspace is still an error. */
|
|
292
|
+
export async function removeWorkspaceModelKey(client, workspaceId, provider) {
|
|
293
|
+
try {
|
|
294
|
+
const result = await client.removeModelKey(workspaceId, provider);
|
|
295
|
+
return { result, message: `${provider} key removed.` };
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
if (!(error instanceof ApiError) || error.status !== 404 || error.code !== "model_key_not_found")
|
|
299
|
+
throw error;
|
|
300
|
+
return { result: {}, message: `No ${provider} key is configured in this workspace.` };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** Execute repo commands through the same workspace overview used by workspace show. */
|
|
304
|
+
export async function runRepo(client, workspaceId, inv, io) {
|
|
305
|
+
const { command } = inv;
|
|
306
|
+
const overview = await client.getWorkspace(workspaceId);
|
|
307
|
+
if (command.name === "repos") {
|
|
308
|
+
if (inv.json)
|
|
309
|
+
io.out(`${JSON.stringify(overview.repos, null, 2)}\n`);
|
|
310
|
+
else if (overview.repos.length === 0)
|
|
311
|
+
io.out(`No repositories available (${overview.repoCatalog}).\n`);
|
|
312
|
+
else
|
|
313
|
+
for (const repo of overview.repos)
|
|
314
|
+
io.out(printable(`${repo.name} (${repo.id})${repo.shortDescription ? ` ${repo.shortDescription}` : ""}\n`));
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
const repo = overview.repos.find((row) => row.name.toLowerCase() === command.repoName.toLowerCase());
|
|
318
|
+
if (!repo)
|
|
319
|
+
throw new UsageError("Repository is not available in this workspace. Run `sinatra repos` to see accessible repositories.");
|
|
320
|
+
await confirmWorkspaceMutation(command, { yes: inv.yes ?? false, interactive: io.interactive, workspaceId, ask: io.ask });
|
|
321
|
+
let result;
|
|
322
|
+
switch (command.action) {
|
|
323
|
+
case "review-external-prs":
|
|
324
|
+
result = await client.repoRequest(workspaceId, repo.id, "review-external-prs", command.value === undefined ? "GET" : "PUT", command.value === undefined ? undefined : { reviewExternalPrs: command.value });
|
|
325
|
+
break;
|
|
326
|
+
case "config":
|
|
327
|
+
result = await client.repoRequest(workspaceId, repo.id, "sinatrarc");
|
|
328
|
+
break;
|
|
329
|
+
case "preflight":
|
|
330
|
+
case "override-set": {
|
|
331
|
+
let fragment;
|
|
332
|
+
try {
|
|
333
|
+
fragment = JSON.parse(await readFile(inv.files[0], "utf8"));
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
throw new UsageError("Couldn't read the fragment. --file must name a readable JSON file.");
|
|
337
|
+
}
|
|
338
|
+
result = await client.repoRequest(workspaceId, repo.id, command.action === "preflight" ? "config-preflight" : "user-override", command.action === "preflight" ? "POST" : "PUT", { fragment });
|
|
339
|
+
break;
|
|
340
|
+
}
|
|
341
|
+
case "override-clear":
|
|
342
|
+
result = await client.repoRequest(workspaceId, repo.id, "user-override", "DELETE");
|
|
343
|
+
break;
|
|
344
|
+
case "secrets-list":
|
|
345
|
+
result = await client.repoRequest(workspaceId, repo.id, "secrets");
|
|
346
|
+
break;
|
|
347
|
+
case "secrets-set":
|
|
348
|
+
case "secrets-rotate": {
|
|
349
|
+
let value;
|
|
350
|
+
try {
|
|
351
|
+
value = (await io.askSecret("Secret value (hidden): ")).replace(/\r?\n$/, "");
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
throw new UsageError("Couldn't read the secret. Paste it at the hidden prompt or pipe it on stdin.");
|
|
355
|
+
}
|
|
356
|
+
if (!value)
|
|
357
|
+
throw new UsageError("No secret supplied. Nothing changed.");
|
|
358
|
+
result = await client.repoRequest(workspaceId, repo.id, `secrets/${encodeURIComponent(command.secretName)}`, "PUT", { ...inv.secretMetadata, value });
|
|
359
|
+
break;
|
|
360
|
+
}
|
|
361
|
+
case "secrets-update":
|
|
362
|
+
case "secrets-delete":
|
|
363
|
+
try {
|
|
364
|
+
result = command.action === "secrets-update"
|
|
365
|
+
? await client.repoRequest(workspaceId, repo.id, `secrets/${encodeURIComponent(command.secretName)}`, "PATCH", inv.secretMetadata)
|
|
366
|
+
: await client.repoRequest(workspaceId, repo.id, `secrets/${encodeURIComponent(command.secretName)}`, "DELETE");
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
// The repo was already resolved above, so a 404 here is the secret.
|
|
370
|
+
if (error instanceof ApiError && error.status === 404 && error.code === "not_found")
|
|
371
|
+
throw new ApiError(404, "secret_not_found");
|
|
372
|
+
throw error;
|
|
373
|
+
}
|
|
374
|
+
break;
|
|
375
|
+
case "env":
|
|
376
|
+
result = await client.repoRequest(workspaceId, repo.id, "environment");
|
|
377
|
+
break;
|
|
378
|
+
case "capability-requests":
|
|
379
|
+
result = await client.repoRequest(workspaceId, repo.id, "capability-requests");
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
if (inv.json)
|
|
383
|
+
io.out(`${JSON.stringify(result, null, 2)}\n`);
|
|
384
|
+
else if (command.action === "override-clear" || command.action === "secrets-delete") {
|
|
385
|
+
io.out(command.action === "override-clear" ? "Repository override cleared.\n" : "Repository secret deleted.\n");
|
|
386
|
+
}
|
|
387
|
+
else
|
|
388
|
+
io.out(printable(`${describeRepoResponse(result)}\n`));
|
|
389
|
+
}
|
|
390
|
+
/** Keep nested config/environment responses readable without dropping server-owned fields. */
|
|
391
|
+
function describeRepoResponse(value, indent = "") {
|
|
392
|
+
if (value === null)
|
|
393
|
+
return "none";
|
|
394
|
+
if (Array.isArray(value))
|
|
395
|
+
return value.length ? value.map((item) => `${indent}- ${describeRepoResponse(item, `${indent} `)}`).join("\n") : "none";
|
|
396
|
+
if (typeof value === "object")
|
|
397
|
+
return Object.entries(value)
|
|
398
|
+
.map(([key, item]) => `${indent}${key}: ${describeRepoResponse(item, `${indent} `)}`).join("\n") || "Done.";
|
|
399
|
+
return String(value);
|
|
400
|
+
}
|
|
125
401
|
/**
|
|
126
402
|
* How `sinatra login` gets its credential. Asked for explicitly, that way; otherwise the browser
|
|
127
403
|
* at a terminal, and a pasted token when stdin is piped (`sinatra login < token-file`), which
|
|
@@ -141,6 +417,15 @@ export function parseInvocation(argv) {
|
|
|
141
417
|
return parseArgs({ args: argv, allowPositionals: true, options: OPTIONS });
|
|
142
418
|
}
|
|
143
419
|
catch (error) {
|
|
420
|
+
// parseArgs can quote an entire unknown option, including a pasted secret after `=`.
|
|
421
|
+
if (argv.includes("repo"))
|
|
422
|
+
throw new UsageError(REPO_USAGE);
|
|
423
|
+
if (argv.includes("connect"))
|
|
424
|
+
throw new UsageError(CONNECT_USAGE);
|
|
425
|
+
if (argv.includes("subscriptions"))
|
|
426
|
+
throw new UsageError(SUBSCRIPTIONS_USAGE);
|
|
427
|
+
if (argv.includes("keys"))
|
|
428
|
+
throw new UsageError("Invalid keys options. Never put a key in arguments or flags; paste it at the hidden prompt or pipe it on stdin.");
|
|
144
429
|
throw new UsageError(`${argumentProblem(error, argv)}\nRun \`sinatra --help\` for usage.`);
|
|
145
430
|
}
|
|
146
431
|
})();
|
|
@@ -165,6 +450,9 @@ export function parseInvocation(argv) {
|
|
|
165
450
|
}
|
|
166
451
|
}
|
|
167
452
|
}
|
|
453
|
+
if (values["no-browser"] && command.name === "subscriptions" && command.action !== "connect") {
|
|
454
|
+
throw new UsageError("--no-browser only applies to `sinatra subscriptions connect <provider>`.");
|
|
455
|
+
}
|
|
168
456
|
if (values.token && values["no-browser"]) {
|
|
169
457
|
throw new UsageError("--token pastes a token and --no-browser signs in through a browser: pick one.");
|
|
170
458
|
}
|
|
@@ -185,18 +473,78 @@ export function parseInvocation(argv) {
|
|
|
185
473
|
throw new UsageError("--timeout takes a number of minutes, more than 0.");
|
|
186
474
|
timeoutMs = minutes * 60_000;
|
|
187
475
|
}
|
|
476
|
+
if (command.name === "repo") {
|
|
477
|
+
const needsFile = command.action === "preflight" || command.action === "override-set";
|
|
478
|
+
if (needsFile ? values.file?.length !== 1 : values.file !== undefined)
|
|
479
|
+
throw new UsageError(needsFile ? "This action requires exactly one --file <json> containing the fragment." : "--file only applies to config preflight or override set.");
|
|
480
|
+
const metadata = values.host !== undefined || values.header !== undefined || values.prefix !== undefined;
|
|
481
|
+
if (metadata && !["secrets-set", "secrets-rotate", "secrets-update"].includes(command.action))
|
|
482
|
+
throw new UsageError("Secret metadata flags only apply to secrets set, rotate or update.");
|
|
483
|
+
if (values["capability-request"] !== undefined && !["secrets-set", "secrets-rotate"].includes(command.action))
|
|
484
|
+
throw new UsageError("--capability-request only applies to secrets set or rotate.");
|
|
485
|
+
if (command.action === "secrets-set" && !values.host?.some((host) => host.trim()))
|
|
486
|
+
throw new UsageError("New secrets require --host <host> (repeatable). Use secrets rotate to retain existing hosts.");
|
|
487
|
+
if (command.action === "secrets-update" && !metadata)
|
|
488
|
+
throw new UsageError("secrets update requires --host, --header or --prefix.");
|
|
489
|
+
}
|
|
490
|
+
if (command.name === "model") {
|
|
491
|
+
if (command.action === "set" && !values.engine?.trim())
|
|
492
|
+
throw new UsageError("model set requires --engine <engine>; use the engine/model pairing from the dashboard's model catalog.");
|
|
493
|
+
if (command.action !== "set" && (values.engine !== undefined || values.effort !== undefined))
|
|
494
|
+
throw new UsageError("--engine and --effort apply only to model set.");
|
|
495
|
+
}
|
|
496
|
+
if (command.name === "access") {
|
|
497
|
+
const needsRole = ["invite", "approve", "role"].includes(command.action);
|
|
498
|
+
if (needsRole && values.role !== "member" && values.role !== "admin")
|
|
499
|
+
throw new UsageError("--role must be member or admin.");
|
|
500
|
+
if (!needsRole && values.role !== undefined)
|
|
501
|
+
throw new UsageError("--role doesn't apply to this access action.");
|
|
502
|
+
}
|
|
503
|
+
if (values.yes !== undefined && command.name !== "help" && command.name !== "version" && !requiresConfirmation(command)) {
|
|
504
|
+
throw new UsageError("--yes doesn't apply to this action.");
|
|
505
|
+
}
|
|
506
|
+
const emailPreferences = {};
|
|
507
|
+
for (const [flag, field] of [["setup-reminders", "setupReminders"], ["task-alerts", "taskAlerts"]]) {
|
|
508
|
+
const value = values[flag];
|
|
509
|
+
if (value === undefined)
|
|
510
|
+
continue;
|
|
511
|
+
if (value !== "on" && value !== "off")
|
|
512
|
+
throw new UsageError(`--${flag} takes on or off.`);
|
|
513
|
+
emailPreferences[field] = value === "on";
|
|
514
|
+
}
|
|
515
|
+
if (command.name === "billing") {
|
|
516
|
+
if (command.action === "upgrade") {
|
|
517
|
+
if (values.plan !== "pro" && values.plan !== "team" && values.plan !== "scale")
|
|
518
|
+
throw new UsageError("Billing upgrade requires --plan pro, team or scale.");
|
|
519
|
+
}
|
|
520
|
+
else if (values.plan !== undefined)
|
|
521
|
+
throw new UsageError("--plan only applies to billing upgrade.");
|
|
522
|
+
}
|
|
188
523
|
return {
|
|
189
524
|
command,
|
|
190
525
|
files: values.file ?? [],
|
|
191
526
|
wait,
|
|
192
527
|
timeoutMs,
|
|
193
528
|
json: values.json ?? false,
|
|
529
|
+
emailPreferences,
|
|
194
530
|
pasteToken: values.token ?? false,
|
|
195
531
|
noBrowser: values["no-browser"] ?? false,
|
|
532
|
+
...(command.name === "repo" ? { secretMetadata: {
|
|
533
|
+
...(values.host !== undefined ? { hosts: values.host } : {}),
|
|
534
|
+
...(values.header !== undefined ? { header: values.header } : {}),
|
|
535
|
+
...(values.prefix !== undefined ? { prefix: values.prefix } : {}),
|
|
536
|
+
...(values["capability-request"] !== undefined ? { capabilityRequestId: values["capability-request"] } : {}),
|
|
537
|
+
} } : {}),
|
|
538
|
+
...(values.role === "member" || values.role === "admin" ? { role: values.role } : {}),
|
|
539
|
+
...(values.yes !== undefined ? { yes: values.yes } : {}),
|
|
196
540
|
...(values.repo !== undefined ? { repo: values.repo } : {}),
|
|
197
541
|
...(values.query !== undefined ? { query: values.query } : {}),
|
|
198
542
|
...(values.title !== undefined ? { title: values.title } : {}),
|
|
543
|
+
...(values.model !== undefined ? { model: values.model } : {}),
|
|
544
|
+
...(values.engine !== undefined ? { engine: values.engine } : {}),
|
|
545
|
+
...(values.effort !== undefined ? { effort: values.effort } : {}),
|
|
199
546
|
...(values.workspace !== undefined ? { workspace: values.workspace } : {}),
|
|
547
|
+
...(values.plan === "pro" || values.plan === "team" || values.plan === "scale" ? { plan: values.plan } : {}),
|
|
200
548
|
...(values.status !== undefined ? { status: values.status } : {}),
|
|
201
549
|
...(limit !== undefined ? { limit } : {}),
|
|
202
550
|
...(values["api-url"] !== undefined ? { apiUrl: values["api-url"] } : {}),
|
|
@@ -275,6 +623,133 @@ export async function startTask(client, workspaceId, body, repos, notice) {
|
|
|
275
623
|
}
|
|
276
624
|
return { started: await client.startTask(workspaceId, body), repo: null };
|
|
277
625
|
}
|
|
626
|
+
function subscriptionFailure(status) {
|
|
627
|
+
if (status === "denied")
|
|
628
|
+
return new UsageError("Subscription authorization was denied. Run connect again to try again.");
|
|
629
|
+
if (status === "expired")
|
|
630
|
+
return new UsageError("Subscription authorization expired. Run connect again.");
|
|
631
|
+
return new UsageError("Subscription connection failed. Run connect again, or reconnect on your Sinatra Account page.");
|
|
632
|
+
}
|
|
633
|
+
/** Never print provider errors or response bodies: they can contain authorization credentials. */
|
|
634
|
+
function subscriptionApiFailure(error) {
|
|
635
|
+
if (error instanceof ApiError) {
|
|
636
|
+
if (error.status === 409 && error.code === "device_auth_not_enabled") {
|
|
637
|
+
let settingsUrl;
|
|
638
|
+
if (typeof error.detail.settingsUrl === "string" && !/[\s\u0000-\u001f\u007f-\u009f]/u.test(error.detail.settingsUrl)) {
|
|
639
|
+
try {
|
|
640
|
+
const url = new URL(error.detail.settingsUrl);
|
|
641
|
+
if (["https:", "http:"].includes(url.protocol) && !url.username && !url.password)
|
|
642
|
+
settingsUrl = url.href;
|
|
643
|
+
}
|
|
644
|
+
catch { /* An unsafe or malformed URL must not reach the terminal. */ }
|
|
645
|
+
}
|
|
646
|
+
return new UsageError(`Enable device-code login in your ChatGPT security settings${settingsUrl ? `: ${settingsUrl}` : ""}, then run \`sinatra subscriptions connect codex\` again.`);
|
|
647
|
+
}
|
|
648
|
+
if (["denied", "expired", "failed"].includes(String(error.detail.status)))
|
|
649
|
+
return subscriptionFailure(error.detail.status);
|
|
650
|
+
if (error.status === 401)
|
|
651
|
+
return new UsageError("Your Sinatra sign-in was refused. Run `sinatra login` again.");
|
|
652
|
+
if (error.status === 403)
|
|
653
|
+
return new UsageError("You don't have access to manage these subscriptions.");
|
|
654
|
+
if (error.status === 404)
|
|
655
|
+
return new UsageError("The workspace, subscription, or provider isn't available to your account.");
|
|
656
|
+
if (error.status === 429)
|
|
657
|
+
return new UsageError("Too many subscription requests. Try again later.");
|
|
658
|
+
}
|
|
659
|
+
return new UsageError("The subscription request couldn't be completed. Try again, or use your Sinatra Account page.");
|
|
660
|
+
}
|
|
661
|
+
/** Subscription commands have their own failure boundary, so no raw API or transport error escapes. */
|
|
662
|
+
export async function subscriptions(command, deps) {
|
|
663
|
+
const { client, workspaceId, out } = deps;
|
|
664
|
+
const emit = (value) => out(`${JSON.stringify(value, null, 2)}\n`);
|
|
665
|
+
try {
|
|
666
|
+
if (command.action === "list") {
|
|
667
|
+
const result = await client.listSubscriptions(workspaceId);
|
|
668
|
+
if (deps.json)
|
|
669
|
+
return emit(result);
|
|
670
|
+
if (result.connections.length === 0)
|
|
671
|
+
out("No subscriptions connected.\n");
|
|
672
|
+
for (const connection of result.connections) {
|
|
673
|
+
const status = connection.needsReconnect ? "needs reconnect" : connection.connected ? "connected" : "disconnected";
|
|
674
|
+
out(printable(`${connection.id} ${connection.provider} ${connection.label ?? connection.email ?? ""} ${status}${connection.primary ? " (primary)" : ""}\n`));
|
|
675
|
+
}
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (command.action === "remove") {
|
|
679
|
+
await client.removeSubscription(workspaceId, command.connectionId);
|
|
680
|
+
if (deps.json)
|
|
681
|
+
emit({ removed: true, id: command.connectionId });
|
|
682
|
+
else
|
|
683
|
+
out("Subscription removed.\n");
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
const result = await connectSubscription(command.provider, deps);
|
|
687
|
+
// Only the public outcome is printed, never pending bindings or the pasted completion code.
|
|
688
|
+
if (deps.json)
|
|
689
|
+
emit({ provider: command.provider, status: "connected", email: result.email ?? null });
|
|
690
|
+
else
|
|
691
|
+
out(printable(`Connected ${command.provider}${result.email ? ` (${result.email})` : ""}.\n`));
|
|
692
|
+
}
|
|
693
|
+
catch (error) {
|
|
694
|
+
if (error instanceof UsageError)
|
|
695
|
+
throw error;
|
|
696
|
+
throw subscriptionApiFailure(error);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
async function connectSubscription(provider, deps) {
|
|
700
|
+
const { client, workspaceId, notice } = deps;
|
|
701
|
+
const handoff = async (url, userCode) => {
|
|
702
|
+
notice(printable(`Open this URL to connect ${provider}:\n${url}\n${userCode ? `Verification code: ${userCode}\n` : ""}`));
|
|
703
|
+
if (deps.openBrowser && !await deps.openBrowser(url).catch(() => false))
|
|
704
|
+
notice("Couldn't open a browser. Open the URL above yourself.\n");
|
|
705
|
+
};
|
|
706
|
+
if (provider === "claude") {
|
|
707
|
+
const started = await client.startSubscription(workspaceId, provider);
|
|
708
|
+
await handoff(started.authorizeUrl);
|
|
709
|
+
const code = (await deps.askSecret("Claude authorization code (hidden): ")).trim();
|
|
710
|
+
if (!code)
|
|
711
|
+
throw new UsageError("No authorization code given. Run `sinatra subscriptions connect claude` again.");
|
|
712
|
+
const result = await client.completeSubscription(workspaceId, { code, state: started.state, pendingToken: started.pendingToken });
|
|
713
|
+
if (result.status !== "connected")
|
|
714
|
+
throw subscriptionFailure(result.status);
|
|
715
|
+
return result;
|
|
716
|
+
}
|
|
717
|
+
const now = deps.now ?? Date.now;
|
|
718
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
719
|
+
const deadline = now() + (deps.timeoutMs ?? 15 * 60_000);
|
|
720
|
+
let interval;
|
|
721
|
+
let body;
|
|
722
|
+
if (provider === "codex") {
|
|
723
|
+
const started = await client.startSubscription(workspaceId, provider);
|
|
724
|
+
await handoff(started.verificationUrl, started.userCode);
|
|
725
|
+
interval = started.interval;
|
|
726
|
+
body = { deviceAuthId: started.deviceAuthId, userCode: started.userCode, pollToken: started.pollToken };
|
|
727
|
+
}
|
|
728
|
+
else if (provider === "xai") {
|
|
729
|
+
const started = await client.startSubscription(workspaceId, provider);
|
|
730
|
+
await handoff(started.verificationUrl, started.userCode);
|
|
731
|
+
interval = started.interval;
|
|
732
|
+
body = { deviceCode: started.deviceCode, pollToken: started.pollToken };
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
const started = await client.startSubscription(workspaceId, provider);
|
|
736
|
+
await handoff(started.loginUrl);
|
|
737
|
+
interval = started.interval;
|
|
738
|
+
body = { pollToken: started.pollToken };
|
|
739
|
+
}
|
|
740
|
+
const intervalMs = Number.isFinite(interval) && interval > 0 ? Math.max(1_000, interval * 1_000) : 5_000;
|
|
741
|
+
while (now() < deadline) {
|
|
742
|
+
await sleep(Math.min(intervalMs, deadline - now()));
|
|
743
|
+
if (now() >= deadline)
|
|
744
|
+
break;
|
|
745
|
+
const result = await client.pollSubscription(workspaceId, provider, body);
|
|
746
|
+
if (result.status === "connected")
|
|
747
|
+
return result;
|
|
748
|
+
if (result.status !== "pending")
|
|
749
|
+
throw subscriptionFailure(result.status);
|
|
750
|
+
}
|
|
751
|
+
throw new UsageError("Timed out waiting for subscription authorization. Run connect again.");
|
|
752
|
+
}
|
|
278
753
|
async function pastedToken(deps) {
|
|
279
754
|
// The sign-in page sends a signed-in visitor straight on, and a signed-out one there after signing in.
|
|
280
755
|
deps.out(deps.apiUrl === DEFAULT_API_URL
|
|
@@ -328,8 +803,10 @@ async function loginWorkspace(workspaces, deps) {
|
|
|
328
803
|
}
|
|
329
804
|
if (workspaces.length === 1)
|
|
330
805
|
return workspaces[0].id;
|
|
331
|
-
if (workspaces.length === 0)
|
|
806
|
+
if (workspaces.length === 0) {
|
|
807
|
+
out('You don\'t have a workspace yet. Create one with: sinatra workspace create "<name>"\n');
|
|
332
808
|
return undefined;
|
|
809
|
+
}
|
|
333
810
|
if (!deps.interactive) {
|
|
334
811
|
// Piped stdin has nothing left after the token: asking would only read end-of-input.
|
|
335
812
|
out("No default workspace saved: you belong to more than one. Set one with `sinatra workspace <id>`, or log in with --workspace <id>.\n");
|
|
@@ -446,12 +923,44 @@ export function explain(error, context = {}) {
|
|
|
446
923
|
return "Sinatra saved your message but couldn't hand it over yet. Don't send it again: it goes out first with your next message to this task.";
|
|
447
924
|
case "unreachable": return "Sinatra couldn't be reached; try again shortly.";
|
|
448
925
|
}
|
|
926
|
+
// The server's reason names API routes; say it in commands. Connecting GitHub doesn't lift the limit.
|
|
927
|
+
if (refusal.code === "workspace_limit") {
|
|
928
|
+
return "You already created a workspace without GitHub, and each person can create one that way. Use that workspace " +
|
|
929
|
+
"(`sinatra whoami` lists it; `sinatra workspace <id>` makes it the default), and connect GitHub to it with " +
|
|
930
|
+
"`sinatra connect github` if it isn't yet. To make another workspace, install the Sinatra GitHub App on another " +
|
|
931
|
+
"account or organization from the dashboard's Add a workspace.";
|
|
932
|
+
}
|
|
449
933
|
// A refusal the server explained itself (delegation's are the dashboard's own words).
|
|
450
934
|
if (typeof error.detail.reason === "string")
|
|
451
935
|
return printable(error.detail.reason);
|
|
452
936
|
switch (refusal.code) {
|
|
937
|
+
case "invalid_model_selection": return "That engine/model/effort selection isn't in Sinatra's catalog. Check the dashboard's model settings.";
|
|
938
|
+
case "actor_not_authorized":
|
|
939
|
+
return "Your workspace role doesn't allow this action. Only the owner can change the workspace default; owners and admins can manage model keys and repository secrets.";
|
|
940
|
+
case "unsupported_provider": return "Supported key providers are anthropic and openrouter.";
|
|
941
|
+
case "key_validation_failed":
|
|
942
|
+
return "Sinatra couldn't validate that API key. Check the key and its provider, then try again.";
|
|
943
|
+
case "provider_unreachable": return "The model provider couldn't be reached to validate the key. Try again shortly.";
|
|
944
|
+
case "invalid_body": return "The request is invalid. Check the supplied configuration or metadata; enter secret values only through the hidden prompt or stdin.";
|
|
945
|
+
case "internal_error": return "Sinatra couldn't save the change. Check the workspace's current settings before trying again.";
|
|
946
|
+
case "no_customer": return "This workspace has no billing account yet. Run `sinatra billing upgrade --plan <pro|team|scale>` first.";
|
|
947
|
+
case "customer_missing": return "Your billing account needs to be reconnected. Start a new subscription with `sinatra billing upgrade --plan <pro|team|scale>`.";
|
|
948
|
+
case "billing_disabled": return "Billing is disabled on this Sinatra installation. Contact your administrator.";
|
|
949
|
+
case "plans_not_configured": return "Paid billing plans are not configured on this installation. Contact your administrator.";
|
|
453
950
|
case "invalid_prompt": return "The message is empty or too long.";
|
|
454
951
|
case "invalid_repo": return "That repository isn't connected to this workspace (see the dashboard's Repositories page).";
|
|
952
|
+
case "repo_not_found": return "That repository isn't available in this workspace. Run `sinatra repos` to list accessible repositories.";
|
|
953
|
+
case "secret_not_found": return "That repository secret doesn't exist. Use secrets set with --host to create it.";
|
|
954
|
+
case "invalid_secret_hosts": return "Supply at least one valid allowed host with --host; hosts must authorize the intended target.";
|
|
955
|
+
case "invalid_secret_header": return "That proxy header isn't valid. Check --header.";
|
|
956
|
+
case "invalid_secret_prefix": return "That proxy prefix isn't valid. Check --prefix.";
|
|
957
|
+
case "invalid_secret_name": return "That secret name isn't valid. Use the naming rules shown in the dashboard.";
|
|
958
|
+
case "invalid_secret_value": return "That secret value isn't valid. Enter a nonempty value through the hidden prompt or stdin.";
|
|
959
|
+
case "secret_cap_exceeded": return "This repository has reached its secret limit.";
|
|
960
|
+
case "capability_request_not_found": return "That capability request isn't available for this repository.";
|
|
961
|
+
case "capability_target_not_authorized": return "The allowed hosts don't authorize the capability request's target. Update --host.";
|
|
962
|
+
case "repo_environments_not_enabled": return "Repository environments aren't enabled for this workspace.";
|
|
963
|
+
case "invalid_model": return "Sinatra doesn't offer that model (see docs.sinatra.dev/docs/configuration/models).";
|
|
455
964
|
case "invalid_status": return "That isn't a task status (some are: pending, implementing, replied, pr_open, completed, failed).";
|
|
456
965
|
case "invalid_limit": return "--limit takes a whole number from 1 to 100.";
|
|
457
966
|
case "not_an_api_task": return "That task wasn't started from the API or CLI, so it has no conversation here; reply where it started.";
|
|
@@ -460,3 +969,101 @@ export function explain(error, context = {}) {
|
|
|
460
969
|
default: return `Sinatra refused: ${error.code} (HTTP ${error.status}).`;
|
|
461
970
|
}
|
|
462
971
|
}
|
|
972
|
+
/** Execute billing without mixing machine-readable output with browser notices. */
|
|
973
|
+
export async function runBilling(client, workspaceId, invocation, deps) {
|
|
974
|
+
const { action } = invocation.command;
|
|
975
|
+
if (action === "status") {
|
|
976
|
+
const status = await client.planStatus(workspaceId);
|
|
977
|
+
if (invocation.json) {
|
|
978
|
+
deps.out(`${JSON.stringify(status)}\n`);
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
const lines = [`Plan: ${status.capacity?.plan ?? status.plan}`];
|
|
982
|
+
if (status.capacity)
|
|
983
|
+
lines.push(`Capacity: ${status.capacity.running} running, ${status.capacity.queued} queued`);
|
|
984
|
+
if (status.byokConfigured !== undefined)
|
|
985
|
+
lines.push(`Own provider credentials: ${status.byokConfigured ? "configured" : "not configured"}`);
|
|
986
|
+
const sub = status.subscription;
|
|
987
|
+
lines.push(`Subscription: ${sub?.status ?? "none"}`);
|
|
988
|
+
if (sub?.trialEndsAt)
|
|
989
|
+
lines.push(`Trial ends: ${sub.trialEndsAt}`);
|
|
990
|
+
if (sub?.currentPeriodEnd)
|
|
991
|
+
lines.push(`Current period ends: ${sub.currentPeriodEnd}`);
|
|
992
|
+
if (sub?.cancelAtPeriodEnd)
|
|
993
|
+
lines.push(`Cancels at period end${sub.endsAt ? `: ${sub.endsAt}` : ""}`);
|
|
994
|
+
if (sub?.pastDueSinceAt)
|
|
995
|
+
lines.push(`Payment past due since: ${sub.pastDueSinceAt}`);
|
|
996
|
+
if (sub?.actionRequiredHostedInvoiceUrl)
|
|
997
|
+
lines.push(`Payment action required: ${sub.actionRequiredHostedInvoiceUrl}`);
|
|
998
|
+
deps.out(printable(`${lines.join("\n")}\n`));
|
|
999
|
+
return;
|
|
1000
|
+
}
|
|
1001
|
+
if (action === "upgrade" && !invocation.plan)
|
|
1002
|
+
throw new UsageError("Billing upgrade requires --plan pro, team or scale.");
|
|
1003
|
+
const result = action === "upgrade"
|
|
1004
|
+
? await client.billingCheckout(workspaceId, invocation.plan)
|
|
1005
|
+
: await client.billingPortal(workspaceId);
|
|
1006
|
+
const url = new URL(result.url);
|
|
1007
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
1008
|
+
throw new UsageError("Sinatra returned an invalid billing URL.");
|
|
1009
|
+
if (invocation.json) {
|
|
1010
|
+
deps.out(`${JSON.stringify(result)}\n`);
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
deps.out(printable(`Open billing in your browser:\n${result.url}\n`));
|
|
1014
|
+
// The URL is already printed, so failed desktop integration never loses the handoff.
|
|
1015
|
+
await deps.openBrowser(result.url).catch(() => false);
|
|
1016
|
+
}
|
|
1017
|
+
/**
|
|
1018
|
+
* `sinatra workspace create`: the first workspace becomes the default, so the next command needs
|
|
1019
|
+
* no -w; an existing default is kept. The config is read again after the request, which may have
|
|
1020
|
+
* refreshed the sign-in and rotated the tokens the caller's copy holds.
|
|
1021
|
+
*/
|
|
1022
|
+
export async function runWorkspaceCreate(client, invocation, deps) {
|
|
1023
|
+
const { workspace } = await client.createWorkspace(invocation.command.workspaceName);
|
|
1024
|
+
const latest = (await deps.read()) ?? deps.fallback;
|
|
1025
|
+
const madeDefault = !latest.workspaceId;
|
|
1026
|
+
if (madeDefault)
|
|
1027
|
+
await deps.write({ ...latest, workspaceId: workspace.id });
|
|
1028
|
+
const { out } = deps;
|
|
1029
|
+
if (invocation.json) {
|
|
1030
|
+
out(`${JSON.stringify({ workspace, defaultWorkspaceId: madeDefault ? workspace.id : latest.workspaceId }, null, 2)}\n`);
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
out(printable(`Created workspace ${workspace.name} (${workspace.id}). You're its owner.\n`));
|
|
1034
|
+
out(madeDefault
|
|
1035
|
+
? "It's your default workspace.\n"
|
|
1036
|
+
: printable(`Your default workspace is still ${latest.workspaceId}; switch with: sinatra workspace ${workspace.id}\n`));
|
|
1037
|
+
out(printable(`Connect GitHub next: sinatra connect github${madeDefault ? "" : ` -w ${workspace.id}`}\n`));
|
|
1038
|
+
}
|
|
1039
|
+
/** Browser authorization is observed through the existing workspace overview, never a new status API. */
|
|
1040
|
+
export async function runConnect(client, workspaceId, invocation, deps) {
|
|
1041
|
+
const { integration } = invocation.command;
|
|
1042
|
+
const result = await client.integrationConnect(workspaceId, integration);
|
|
1043
|
+
if (invocation.json) {
|
|
1044
|
+
deps.out(`${JSON.stringify(result)}\n`);
|
|
1045
|
+
return;
|
|
1046
|
+
}
|
|
1047
|
+
const url = new URL(result.url);
|
|
1048
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
1049
|
+
throw new UsageError("Sinatra returned an invalid integration URL.");
|
|
1050
|
+
deps.out(printable(`Connect ${integration} in your browser:\n${result.url}\n`));
|
|
1051
|
+
await deps.openBrowser(result.url).catch(() => false);
|
|
1052
|
+
const now = deps.now ?? Date.now;
|
|
1053
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
1054
|
+
const deadline = now() + invocation.timeoutMs;
|
|
1055
|
+
while (now() < deadline) {
|
|
1056
|
+
const overview = await client.getWorkspace(workspaceId);
|
|
1057
|
+
const connected = integration === "telegram"
|
|
1058
|
+
? overview.telegram.connected === true
|
|
1059
|
+
: overview[integration].status === "connected" && (integration !== "linear" || overview.linear.needsReconnect === false);
|
|
1060
|
+
if (connected) {
|
|
1061
|
+
deps.out(printable(`${integration} connected.\n`));
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
const remaining = deadline - now();
|
|
1065
|
+
if (remaining > 0)
|
|
1066
|
+
await sleep(Math.min(2_000, remaining));
|
|
1067
|
+
}
|
|
1068
|
+
throw new UsageError(`Timed out waiting for ${integration} to connect after ${invocation.timeoutMs / 60_000} minutes. Finish authorization in your browser, then check with \`sinatra workspace show\`.`);
|
|
1069
|
+
}
|