sinatra.dev 0.3.1 → 0.5.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/dist/commands.js CHANGED
@@ -1,9 +1,10 @@
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";
6
- import { revokeSignIn } from "./oauth.js";
7
+ import { revokeSignIn, SignInError } from "./oauth.js";
7
8
  /**
8
9
  * A ticket reference as a person pastes it: `ENG-123`, a Linear issue URL, `owner/name#12` or a
9
10
  * GitHub issue URL. Null for anything else.
@@ -23,6 +24,134 @@ 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
+ // Connectors are unlisted: this is the only place the group's usage is said, and USAGE never names it.
30
+ const CONNECTORS_USAGE = "Usage: sinatra connectors [list | connect <connector> [--project <ref>] [--name <label>] [--token] [--accept] | disconnect <connection-id> [--yes]] [-w <id>] [--json]. --project is needed only by services that take a project reference. Without --token or --accept, a service you can sign in to gives a link to the dashboard, where a workspace owner or admin signs in and accepts the warning; --token, or --accept to accept the terms without a prompt, pastes a token instead, for a service that takes one. Paste a token at the hidden prompt or pipe it on stdin, never on the command line.";
31
+ const WORKSPACE_CREATE_USAGE = 'Usage: sinatra workspace create "<name>" [--json]. Quote a name with spaces.';
32
+ 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.";
33
+ /** The help text. Unlisted command groups stay out of it. */
34
+ export const USAGE = `Usage:
35
+ sinatra login [--api-url <url>] [-w <id>] [--no-browser | --token]
36
+ Sign in through your browser (-w: the default workspace)
37
+ --no-browser Print the sign-in URL instead of opening it (the browser
38
+ must still be on this computer)
39
+ --token Paste a personal access token instead (also when stdin
40
+ is piped: sinatra login < token-file)
41
+ sinatra [start] "<what to do>" Start a task and follow it
42
+ -r, --repo <owner/name> Repository (default: this checkout's GitHub remote)
43
+ -f, --file <path> Attach a text file (repeatable, 80KB total)
44
+ -t, --title <title> Task title (default: the prompt's first line)
45
+ -m, --model <model> Model for every agent, such as openai-codex/gpt-6.1-sol
46
+ (default: the repository's or workspace's model)
47
+ --timeout <minutes> Stop following after this long (default 30)
48
+ --no-wait Start it and return
49
+ --json With --no-wait: print the started task as JSON
50
+ sinatra reply <task-id> "<message>" Follow up on a task, then follow it
51
+ (takes -f, --timeout, --no-wait, --json like start)
52
+ sinatra show <task-id> [--json] Print a task and its conversation
53
+ sinatra tasks [--status <status>] [-n, --limit <n>] [--json]
54
+ List the workspace's recent tasks (20 unless -n)
55
+ sinatra stop <task-id> Stop a task's running agent
56
+ sinatra tickets [-q <text>] [-r <owner/name>] [--json]
57
+ Open Linear and GitHub issues you could delegate: yours,
58
+ then the team's unassigned (-q: search, -r: repo first)
59
+ sinatra delegate <ticket> Hand Sinatra a Linear or GitHub issue as you: ENG-123,
60
+ owner/name#12, or the issue's URL
61
+ sinatra subscriptions [list] [--json] List your subscription connections in this workspace
62
+ sinatra subscriptions connect <codex|claude|xai|cursor> [--json] [--no-browser]
63
+ Print the verification URL/code and open your browser;
64
+ wait up to 15 minutes for device approval. Claude asks
65
+ for a hidden authorization code (or reads it from stdin).
66
+ Never pass an authorization code on the command line.
67
+ With --json, handoff and prompts go to stderr.
68
+ sinatra subscriptions remove <id> [--json]
69
+ Remove one of your subscription connections
70
+ sinatra whoami [--json] Who you're logged in as, and your workspaces
71
+ sinatra account [--json] Your account, memberships and linked identities
72
+ sinatra email-preferences [--json] Read your email preferences
73
+ --setup-reminders <on|off> Change setup reminder emails
74
+ --task-alerts <on|off> Change task alert emails (omitted flags stay unchanged)
75
+ sinatra workspace [<id>] List your workspaces, or make one the default
76
+ sinatra repos [-w <id>] [--json] List the workspace's accessible repositories
77
+ sinatra repo <owner/name> config Read effective repository config and provenance
78
+ sinatra repo <owner/name> config preflight --file <json>
79
+ Preflight a draft override fragment from a JSON file
80
+ sinatra repo <owner/name> override set --file <json>
81
+ Save your repository override fragment
82
+ sinatra repo <owner/name> override clear [--yes]
83
+ Clear your override (confirmation required)
84
+ sinatra repo <owner/name> secrets [list]
85
+ List secret metadata, never plaintext values
86
+ sinatra repo <owner/name> secrets set <name> --host <host>
87
+ sinatra repo <owner/name> secrets rotate <name>
88
+ Read a value at a hidden prompt or from stdin;
89
+ never pass secret values in arguments or flags
90
+ sinatra repo <owner/name> secrets update <name>
91
+ PATCH metadata without changing the secret value
92
+ --host <host> Allowed host (repeatable; replaces hosts on update)
93
+ --header <header> --prefix <prefix> Optional proxy metadata for set, rotate or update
94
+ --capability-request <id> Fulfill a capability request with set or rotate
95
+ sinatra repo <owner/name> secrets delete <name> [--yes]
96
+ Delete a secret (confirmation required)
97
+ sinatra repo <owner/name> env Read the feature-gated repository environment
98
+ sinatra repo <owner/name> capability-requests
99
+ Read repository capability requests
100
+ sinatra repo <owner/name> review-external-prs [inherit|on|off]
101
+ Read or set external PR reviews (writes: owner/admin)
102
+ All repos/repo commands take -w and --json
103
+ sinatra model [get] [--json] Show the workspace's saved default (members)
104
+ sinatra model set <model> --engine <engine> [--effort <effort>]
105
+ Save a catalog engine/model/effort pairing (owner only)
106
+ sinatra model clear [--yes] Restore automatic selection (owner only; confirmation required)
107
+ sinatra keys [list] [--json] List configured providers, never key values (members)
108
+ sinatra keys add <anthropic|openrouter> Paste a key at a hidden prompt, or pipe stdin
109
+ sinatra keys remove <anthropic|openrouter> [--yes]
110
+ Remove a key (owners/admins; confirmation required)
111
+ Model and keys commands take -w and --json
112
+ sinatra billing [-w <id>] [--json] Show plan, capacity and subscription status
113
+ sinatra billing upgrade --plan <pro|team|scale> [-w <id>] [--json]
114
+ Open checkout (workspace owner only)
115
+ sinatra billing portal [-w <id>] [--json]
116
+ Open billing management (workspace owner only)
117
+ sinatra connect <github|linear|slack|telegram> [-w <id>] [--timeout <minutes>] [--json]
118
+ Print the authorization URL, open your browser and wait
119
+ for connection (--json returns only the URL response)
120
+ Browser commands always print the URL; --json returns
121
+ only the response without opening a browser
122
+ sinatra members list [--json] List members, pending invites and access requests
123
+ sinatra invite <email> --role <role> Invite a member or admin
124
+ sinatra invite resend <invite-id> Resend an invitation
125
+ sinatra invite revoke <invite-id> Revoke an invitation (confirmation required)
126
+ sinatra requests approve <request-id> --role <role>
127
+ sinatra requests deny <request-id> Resolve an access request
128
+ sinatra members role <membership-id> --role <role>
129
+ sinatra members remove <membership-id> Remove a member (confirmation required)
130
+ sinatra members transfer <membership-id>
131
+ Transfer ownership (confirmation required)
132
+ sinatra workspace leave Leave the workspace (confirmation required)
133
+ --role <member|admin> Role to grant; owner is never a grantable role
134
+ --yes, -y Skip confirmation for destructive access actions, model clear,
135
+ keys remove, repo override clear or repo secrets delete;
136
+ never pass keys or secret values in argv
137
+ Access commands take -w and --json; owner-only except leave
138
+ sinatra workspace create "<name>" [--json]
139
+ Create a workspace you own (one per person without
140
+ GitHub); the first becomes your default
141
+ sinatra workspace show [-w <id>] [--json]
142
+ Read repositories, integrations, plan and default model
143
+ sinatra workspace review-external-prs [on|off] [-w <id>] [--json]
144
+ Read or set external PR reviews (writes: owner/admin)
145
+ sinatra logout Revoke the saved sign-in or token and forget it
146
+ sinatra -v, --version Print the CLI's version
147
+
148
+ -w, --workspace <id> Workspace for task, access, subscription, workspace settings,
149
+ model, keys, repos, repo or billing commands, or default to save at login
150
+ (default: yours from login or \`sinatra workspace\`)
151
+ Account and email preferences need no workspace membership or default workspace.
152
+
153
+ Exit codes: 0 done, 1 error, 2 the task failed, was cancelled or is paused,
154
+ 3 still working (or your reply not picked up yet) when the CLI stopped waiting.`;
26
155
  /**
27
156
  * What the arguments ask for. A command word counts only in the shape that command takes, so
28
157
  * `sinatra stop retrying on 429` or `sinatra logout the user on expiry` start tasks instead of
@@ -35,11 +164,115 @@ export function parseCommand(positionals) {
35
164
  if (!first)
36
165
  return { name: "help" };
37
166
  const usage = (message) => ({ name: "usage", message });
167
+ if (first === "workspace" && rest[0] === "review-external-prs") {
168
+ if (rest.length === 1)
169
+ return { name: "workspace-pr-review" };
170
+ if (rest.length === 2 && (rest[1] === "on" || rest[1] === "off")) {
171
+ return { name: "workspace-pr-review", value: rest[1] === "on" };
172
+ }
173
+ return usage("Usage: sinatra workspace review-external-prs [on|off] [-w <id>] [--json]");
174
+ }
175
+ // Only the group's own shapes count (`sinatra connectors keep timing out` is still a task), but a
176
+ // malformed connect or disconnect is its usage, never a task: a mistyped connect could carry a token.
177
+ if (first === "connectors" && connectorsShape(rest)) {
178
+ if (rest.length === 0 || (rest.length === 1 && rest[0] === "list"))
179
+ return { name: "connectors", action: "list" };
180
+ if (rest.length === 2 && rest[0] === "connect" && rest[1].trim())
181
+ return { name: "connectors", action: "connect", connector: rest[1] };
182
+ if (rest.length === 2 && rest[0] === "disconnect" && rest[1].trim())
183
+ return { name: "connectors", action: "disconnect", connectionId: rest[1] };
184
+ return usage(CONNECTORS_USAGE);
185
+ }
186
+ if (first === "repos")
187
+ return rest.length === 0 ? { name: "repos" } : usage("Usage: sinatra repos [-w <id>] [--json]");
188
+ if (first === "repo") {
189
+ const [repoName, section, action, secretName] = rest;
190
+ if (!repoName || !/^[\w.-]+\/[\w.-]+$/.test(repoName))
191
+ return usage(REPO_USAGE);
192
+ if (section === "review-external-prs") {
193
+ if (rest.length === 2)
194
+ return { name: "repo", repoName, action: "review-external-prs" };
195
+ if (rest.length === 3 && (action === "inherit" || action === "on" || action === "off")) {
196
+ return { name: "repo", repoName, action: "review-external-prs", value: action };
197
+ }
198
+ return usage(REPO_USAGE);
199
+ }
200
+ if (rest.length === 2 && ["config", "env", "capability-requests"].includes(section)) {
201
+ return { name: "repo", repoName, action: section };
202
+ }
203
+ if (rest.length === 3 && section === "config" && action === "preflight")
204
+ return { name: "repo", repoName, action: "preflight" };
205
+ if (rest.length === 3 && section === "override" && (action === "set" || action === "clear"))
206
+ return { name: "repo", repoName, action: action === "set" ? "override-set" : "override-clear" };
207
+ if (section === "secrets") {
208
+ if (rest.length === 2 || (rest.length === 3 && action === "list"))
209
+ return { name: "repo", repoName, action: "secrets-list" };
210
+ if (rest.length === 4 && ["set", "rotate", "update", "delete"].includes(action) && secretName) {
211
+ return { name: "repo", repoName, action: `secrets-${action}`, secretName };
212
+ }
213
+ }
214
+ return usage(REPO_USAGE);
215
+ }
216
+ if (first === "connect") {
217
+ if (rest.length === 1 && ["github", "linear", "slack", "telegram", "buzz"].includes(rest[0])) {
218
+ return { name: "connect", integration: rest[0] };
219
+ }
220
+ return usage(CONNECT_USAGE);
221
+ }
222
+ if (first === "billing") {
223
+ if (rest.length === 0)
224
+ return { name: "billing", action: "status" };
225
+ if (rest.length === 1 && (rest[0] === "upgrade" || rest[0] === "portal"))
226
+ return { name: "billing", action: rest[0] };
227
+ return usage("Usage: sinatra billing [upgrade --plan <pro|team|scale> | portal]");
228
+ }
229
+ if (first === "members" || first === "invite" || first === "requests" || (first === "workspace" && rest[0] === "leave")) {
230
+ if (first === "workspace" && rest.length === 1)
231
+ return { name: "access", action: "leave" };
232
+ if (first === "members" && rest.length === 1 && rest[0] === "list")
233
+ return { name: "access", action: "list" };
234
+ if (first === "invite" && rest.length === 1 && rest[0] !== "resend" && rest[0] !== "revoke")
235
+ return { name: "access", action: "invite", target: rest[0] };
236
+ const action = rest[0];
237
+ if (rest.length === 2 && ((first === "invite" && (action === "resend" || action === "revoke")) ||
238
+ (first === "requests" && (action === "approve" || action === "deny")) ||
239
+ (first === "members" && (action === "role" || action === "remove" || action === "transfer"))))
240
+ return { name: "access", action: action, target: rest[1] };
241
+ return usage("Invalid workspace access command. Run `sinatra --help` for usage.");
242
+ }
243
+ if (first === "model") {
244
+ if (rest.length === 0 || (rest.length === 1 && rest[0] === "get"))
245
+ return { name: "model", action: "get" };
246
+ if (rest.length === 1 && rest[0] === "clear")
247
+ return { name: "model", action: "clear" };
248
+ if (rest.length === 2 && rest[0] === "set")
249
+ return { name: "model", action: "set", model: rest[1] };
250
+ return usage("Usage: sinatra model [get | set <model> --engine <engine> [--effort <effort>] | clear]");
251
+ }
252
+ if (first === "keys") {
253
+ if (rest.length === 0 || (rest.length === 1 && rest[0] === "list"))
254
+ return { name: "keys", action: "list" };
255
+ if (rest.length === 2 && (rest[0] === "add" || rest[0] === "remove") && (rest[1] === "anthropic" || rest[1] === "openrouter")) {
256
+ return { name: "keys", action: rest[0], provider: rest[1] };
257
+ }
258
+ 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.");
259
+ }
38
260
  // More than a word after the command word (`stop retrying on 429`, `show "me why it fails"`).
39
261
  const prose = rest.length >= 2 || (rest.length === 1 && /\s/.test(rest[0]));
40
262
  switch (first) {
41
263
  case "start":
42
264
  return rest.length > 0 ? { name: "start", prompt: rest.join(" ").trim() } : usage('Usage: sinatra start "<what to do>"');
265
+ case "subscriptions":
266
+ if (rest.length === 0 || (rest.length === 1 && rest[0] === "list"))
267
+ return { name: "subscriptions", action: "list" };
268
+ if (rest.length === 2 && rest[0] === "connect" && ["codex", "claude", "xai", "cursor"].includes(rest[1])) {
269
+ return { name: "subscriptions", action: "connect", provider: rest[1] };
270
+ }
271
+ if (rest.length === 2 && rest[0] === "remove" && rest[1].trim()) {
272
+ return { name: "subscriptions", action: "remove", connectionId: rest[1] };
273
+ }
274
+ // Unlike natural-language task shortcuts, subscription mistakes must never spend a task.
275
+ return usage(SUBSCRIPTIONS_USAGE);
43
276
  case "help":
44
277
  case "version":
45
278
  if (rest.length === 0)
@@ -48,6 +281,8 @@ export function parseCommand(positionals) {
48
281
  case "login":
49
282
  case "logout":
50
283
  case "whoami":
284
+ case "account":
285
+ case "email-preferences":
51
286
  case "tasks":
52
287
  case "tickets":
53
288
  if (rest.length === 0)
@@ -59,6 +294,12 @@ export function parseCommand(positionals) {
59
294
  return usage(`Usage: sinatra ${first}`);
60
295
  break;
61
296
  case "workspace":
297
+ if (rest.length === 1 && rest[0] === "show")
298
+ return { name: "workspace-show" };
299
+ // One quoted name. Anything else is a mistake to explain, never a workspace or a task.
300
+ if (rest[0] === "create") {
301
+ return rest.length === 2 && rest[1].trim() ? { name: "workspace-create", workspaceName: rest[1] } : usage(WORKSPACE_CREATE_USAGE);
302
+ }
62
303
  if (rest.length === 0)
63
304
  return { name: "workspace" };
64
305
  if (!prose)
@@ -94,10 +335,22 @@ const OPTIONS = {
94
335
  query: { type: "string", short: "q" },
95
336
  file: { type: "string", short: "f", multiple: true },
96
337
  title: { type: "string", short: "t" },
338
+ model: { type: "string", short: "m" },
339
+ engine: { type: "string" },
340
+ effort: { type: "string" },
97
341
  workspace: { type: "string", short: "w" },
342
+ role: { type: "string" },
343
+ plan: { type: "string" },
344
+ host: { type: "string", multiple: true },
345
+ header: { type: "string" },
346
+ prefix: { type: "string" },
347
+ "capability-request": { type: "string" },
348
+ yes: { type: "boolean", short: "y" },
98
349
  "no-wait": { type: "boolean" },
99
350
  timeout: { type: "string" },
100
351
  json: { type: "boolean" },
352
+ "setup-reminders": { type: "string" },
353
+ "task-alerts": { type: "string" },
101
354
  status: { type: "string" },
102
355
  limit: { type: "string", short: "n" },
103
356
  "api-url": { type: "string" },
@@ -106,22 +359,195 @@ const OPTIONS = {
106
359
  version: { type: "boolean", short: "v" },
107
360
  help: { type: "boolean", short: "h" },
108
361
  };
362
+ /**
363
+ * Options only `sinatra connectors` reads. They are parsed only for that unlisted group, so every
364
+ * other command answers them exactly as it did before (`Unknown option --project.`).
365
+ */
366
+ const CONNECTOR_OPTIONS = {
367
+ project: { type: "string" },
368
+ name: { type: "string" },
369
+ accept: { type: "boolean" },
370
+ };
109
371
  /** The commands each option means something to; given to any other, it's a mistake. */
110
372
  const APPLIES_TO = {
111
373
  repo: ["start", "tickets"],
112
374
  query: ["tickets"],
113
- file: ["start", "reply"],
375
+ file: ["start", "reply", "repo"],
114
376
  title: ["start"],
115
- workspace: ["start", "reply", "show", "tasks", "stop", "tickets", "delegate", "login"],
377
+ model: ["start"],
378
+ workspace: ["start", "reply", "show", "workspace-show", "workspace-pr-review", "tasks", "stop", "tickets", "delegate", "login", "access", "subscriptions", "model", "keys", "billing", "connect", "connectors", "repos", "repo"],
116
379
  "no-wait": ["start", "reply"],
117
- timeout: ["start", "reply"],
118
- json: ["whoami", "tasks", "show", "start", "reply", "tickets"],
380
+ timeout: ["start", "reply", "connect"],
381
+ json: ["whoami", "account", "email-preferences", "tasks", "show", "workspace-show", "workspace-create", "workspace-pr-review", "start", "reply", "tickets", "access", "subscriptions", "model", "keys", "billing", "connect", "connectors", "repos", "repo"],
382
+ "setup-reminders": ["email-preferences"],
383
+ "task-alerts": ["email-preferences"],
119
384
  status: ["tasks"],
120
385
  limit: ["tasks"],
121
386
  "api-url": ["login"],
122
- token: ["login"],
123
- "no-browser": ["login"],
387
+ token: ["login", "connectors"],
388
+ "no-browser": ["login", "subscriptions"],
389
+ role: ["access"],
390
+ yes: ["access", "model", "keys", "repo", "connectors"],
391
+ engine: ["model"],
392
+ effort: ["model"],
393
+ plan: ["billing"],
394
+ host: ["repo"],
395
+ header: ["repo"],
396
+ prefix: ["repo"],
397
+ "capability-request": ["repo"],
398
+ project: ["connectors"],
399
+ name: ["connectors"],
400
+ accept: ["connectors"],
124
401
  };
402
+ function requiresConfirmation(command) {
403
+ return (command.name === "access" && ["revoke", "remove", "transfer", "leave"].includes(command.action))
404
+ || (command.name === "model" && command.action === "clear")
405
+ || (command.name === "keys" && command.action === "remove")
406
+ || (command.name === "repo" && (command.action === "override-clear" || command.action === "secrets-delete"))
407
+ || (command.name === "connectors" && command.action === "disconnect");
408
+ }
409
+ /** Refusals fail closed before the caller sends a workspace mutation. */
410
+ export async function confirmWorkspaceMutation(command, options) {
411
+ if (!requiresConfirmation(command) || options.yes)
412
+ return;
413
+ if (!options.interactive)
414
+ throw new UsageError("This action requires confirmation. Run at a terminal or pass --yes.");
415
+ const action = command.name === "access"
416
+ ? `${command.action}${command.target ? ` ${command.target}` : ""}`
417
+ : command.name === "keys" && command.action === "remove"
418
+ ? `remove ${command.provider} key`
419
+ : command.name === "repo"
420
+ ? `${command.action} in ${command.repoName}${"secretName" in command ? ` (${command.secretName})` : ""}`
421
+ : command.name === "connectors"
422
+ ? `disconnect connection${"connectionId" in command ? ` ${command.connectionId}` : ""}`
423
+ : "clear model default";
424
+ const answer = await options.ask(printable(`Confirm ${action} in workspace ${options.workspaceId}? [y/N] `));
425
+ if (!/^(y|yes)$/i.test(answer.trim()))
426
+ throw new UsageError("Cancelled. Nothing changed.");
427
+ }
428
+ /** Keys enter through an injected hidden prompt/stdin reader, never through command arguments. */
429
+ export async function addWorkspaceModelKey(client, workspaceId, provider, readSecret) {
430
+ let apiKey;
431
+ try {
432
+ apiKey = (await readSecret("API key (hidden): ")).trim();
433
+ }
434
+ catch {
435
+ throw new UsageError("Couldn't read the API key. Paste it at the hidden prompt or pipe it on stdin.");
436
+ }
437
+ if (!apiKey)
438
+ throw new UsageError("No API key supplied. Nothing changed.");
439
+ return client.addModelKey(workspaceId, provider, apiKey);
440
+ }
441
+ /** Only an absent provider key is a successful no-op; an inaccessible workspace is still an error. */
442
+ export async function removeWorkspaceModelKey(client, workspaceId, provider) {
443
+ try {
444
+ const result = await client.removeModelKey(workspaceId, provider);
445
+ return { result, message: `${provider} key removed.` };
446
+ }
447
+ catch (error) {
448
+ if (!(error instanceof ApiError) || error.status !== 404 || error.code !== "model_key_not_found")
449
+ throw error;
450
+ return { result: {}, message: `No ${provider} key is configured in this workspace.` };
451
+ }
452
+ }
453
+ /** Execute repo commands through the same workspace overview used by workspace show. */
454
+ export async function runRepo(client, workspaceId, inv, io) {
455
+ const { command } = inv;
456
+ const overview = await client.getWorkspace(workspaceId);
457
+ if (command.name === "repos") {
458
+ if (inv.json)
459
+ io.out(`${JSON.stringify(overview.repos, null, 2)}\n`);
460
+ else if (overview.repos.length === 0)
461
+ io.out(`No repositories available (${overview.repoCatalog}).\n`);
462
+ else
463
+ for (const repo of overview.repos)
464
+ io.out(printable(`${repo.name} (${repo.id})${repo.shortDescription ? ` ${repo.shortDescription}` : ""}\n`));
465
+ return;
466
+ }
467
+ const repo = overview.repos.find((row) => row.name.toLowerCase() === command.repoName.toLowerCase());
468
+ if (!repo)
469
+ throw new UsageError("Repository is not available in this workspace. Run `sinatra repos` to see accessible repositories.");
470
+ await confirmWorkspaceMutation(command, { yes: inv.yes ?? false, interactive: io.interactive, workspaceId, ask: io.ask });
471
+ let result;
472
+ switch (command.action) {
473
+ case "review-external-prs":
474
+ result = await client.repoRequest(workspaceId, repo.id, "review-external-prs", command.value === undefined ? "GET" : "PUT", command.value === undefined ? undefined : { reviewExternalPrs: command.value });
475
+ break;
476
+ case "config":
477
+ result = await client.repoRequest(workspaceId, repo.id, "sinatrarc");
478
+ break;
479
+ case "preflight":
480
+ case "override-set": {
481
+ let fragment;
482
+ try {
483
+ fragment = JSON.parse(await readFile(inv.files[0], "utf8"));
484
+ }
485
+ catch {
486
+ throw new UsageError("Couldn't read the fragment. --file must name a readable JSON file.");
487
+ }
488
+ result = await client.repoRequest(workspaceId, repo.id, command.action === "preflight" ? "config-preflight" : "user-override", command.action === "preflight" ? "POST" : "PUT", { fragment });
489
+ break;
490
+ }
491
+ case "override-clear":
492
+ result = await client.repoRequest(workspaceId, repo.id, "user-override", "DELETE");
493
+ break;
494
+ case "secrets-list":
495
+ result = await client.repoRequest(workspaceId, repo.id, "secrets");
496
+ break;
497
+ case "secrets-set":
498
+ case "secrets-rotate": {
499
+ let value;
500
+ try {
501
+ value = (await io.askSecret("Secret value (hidden): ")).replace(/\r?\n$/, "");
502
+ }
503
+ catch {
504
+ throw new UsageError("Couldn't read the secret. Paste it at the hidden prompt or pipe it on stdin.");
505
+ }
506
+ if (!value)
507
+ throw new UsageError("No secret supplied. Nothing changed.");
508
+ result = await client.repoRequest(workspaceId, repo.id, `secrets/${encodeURIComponent(command.secretName)}`, "PUT", { ...inv.secretMetadata, value });
509
+ break;
510
+ }
511
+ case "secrets-update":
512
+ case "secrets-delete":
513
+ try {
514
+ result = command.action === "secrets-update"
515
+ ? await client.repoRequest(workspaceId, repo.id, `secrets/${encodeURIComponent(command.secretName)}`, "PATCH", inv.secretMetadata)
516
+ : await client.repoRequest(workspaceId, repo.id, `secrets/${encodeURIComponent(command.secretName)}`, "DELETE");
517
+ }
518
+ catch (error) {
519
+ // The repo was already resolved above, so a 404 here is the secret.
520
+ if (error instanceof ApiError && error.status === 404 && error.code === "not_found")
521
+ throw new ApiError(404, "secret_not_found");
522
+ throw error;
523
+ }
524
+ break;
525
+ case "env":
526
+ result = await client.repoRequest(workspaceId, repo.id, "environment");
527
+ break;
528
+ case "capability-requests":
529
+ result = await client.repoRequest(workspaceId, repo.id, "capability-requests");
530
+ break;
531
+ }
532
+ if (inv.json)
533
+ io.out(`${JSON.stringify(result, null, 2)}\n`);
534
+ else if (command.action === "override-clear" || command.action === "secrets-delete") {
535
+ io.out(command.action === "override-clear" ? "Repository override cleared.\n" : "Repository secret deleted.\n");
536
+ }
537
+ else
538
+ io.out(printable(`${describeRepoResponse(result)}\n`));
539
+ }
540
+ /** Keep nested config/environment responses readable without dropping server-owned fields. */
541
+ function describeRepoResponse(value, indent = "") {
542
+ if (value === null)
543
+ return "none";
544
+ if (Array.isArray(value))
545
+ return value.length ? value.map((item) => `${indent}- ${describeRepoResponse(item, `${indent} `)}`).join("\n") : "none";
546
+ if (typeof value === "object")
547
+ return Object.entries(value)
548
+ .map(([key, item]) => `${indent}${key}: ${describeRepoResponse(item, `${indent} `)}`).join("\n") || "Done.";
549
+ return String(value);
550
+ }
125
551
  /**
126
552
  * How `sinatra login` gets its credential. Asked for explicitly, that way; otherwise the browser
127
553
  * at a terminal, and a pasted token when stdin is piped (`sinatra login < token-file`), which
@@ -141,6 +567,25 @@ export function parseInvocation(argv) {
141
567
  return parseArgs({ args: argv, allowPositionals: true, options: OPTIONS });
142
568
  }
143
569
  catch (error) {
570
+ // The unlisted connectors group reads its own options; any other command never sees them.
571
+ if (connectorsInvocation(argv)) {
572
+ try {
573
+ return parseArgs({ args: argv, allowPositionals: true, options: { ...OPTIONS, ...CONNECTOR_OPTIONS } });
574
+ }
575
+ catch {
576
+ // Never quote the option: it could be a pasted token.
577
+ throw new UsageError(CONNECTORS_USAGE);
578
+ }
579
+ }
580
+ // parseArgs can quote an entire unknown option, including a pasted secret after `=`.
581
+ if (argv.includes("repo"))
582
+ throw new UsageError(REPO_USAGE);
583
+ if (argv.includes("connect"))
584
+ throw new UsageError(CONNECT_USAGE);
585
+ if (argv.includes("subscriptions"))
586
+ throw new UsageError(SUBSCRIPTIONS_USAGE);
587
+ if (argv.includes("keys"))
588
+ 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
589
  throw new UsageError(`${argumentProblem(error, argv)}\nRun \`sinatra --help\` for usage.`);
145
590
  }
146
591
  })();
@@ -165,6 +610,9 @@ export function parseInvocation(argv) {
165
610
  }
166
611
  }
167
612
  }
613
+ if (values["no-browser"] && command.name === "subscriptions" && command.action !== "connect") {
614
+ throw new UsageError("--no-browser only applies to `sinatra subscriptions connect <provider>`.");
615
+ }
168
616
  if (values.token && values["no-browser"]) {
169
617
  throw new UsageError("--token pastes a token and --no-browser signs in through a browser: pick one.");
170
618
  }
@@ -185,23 +633,104 @@ export function parseInvocation(argv) {
185
633
  throw new UsageError("--timeout takes a number of minutes, more than 0.");
186
634
  timeoutMs = minutes * 60_000;
187
635
  }
636
+ if (command.name === "repo") {
637
+ const needsFile = command.action === "preflight" || command.action === "override-set";
638
+ if (needsFile ? values.file?.length !== 1 : values.file !== undefined)
639
+ throw new UsageError(needsFile ? "This action requires exactly one --file <json> containing the fragment." : "--file only applies to config preflight or override set.");
640
+ const metadata = values.host !== undefined || values.header !== undefined || values.prefix !== undefined;
641
+ if (metadata && !["secrets-set", "secrets-rotate", "secrets-update"].includes(command.action))
642
+ throw new UsageError("Secret metadata flags only apply to secrets set, rotate or update.");
643
+ if (values["capability-request"] !== undefined && !["secrets-set", "secrets-rotate"].includes(command.action))
644
+ throw new UsageError("--capability-request only applies to secrets set or rotate.");
645
+ if (command.action === "secrets-set" && !values.host?.some((host) => host.trim()))
646
+ throw new UsageError("New secrets require --host <host> (repeatable). Use secrets rotate to retain existing hosts.");
647
+ if (command.action === "secrets-update" && !metadata)
648
+ throw new UsageError("secrets update requires --host, --header or --prefix.");
649
+ }
650
+ if (command.name === "model") {
651
+ if (command.action === "set" && !values.engine?.trim())
652
+ throw new UsageError("model set requires --engine <engine>; use the engine/model pairing from the dashboard's model catalog.");
653
+ if (command.action !== "set" && (values.engine !== undefined || values.effort !== undefined))
654
+ throw new UsageError("--engine and --effort apply only to model set.");
655
+ }
656
+ if (command.name === "access") {
657
+ const needsRole = ["invite", "approve", "role"].includes(command.action);
658
+ if (needsRole && values.role !== "member" && values.role !== "admin")
659
+ throw new UsageError("--role must be member or admin.");
660
+ if (!needsRole && values.role !== undefined)
661
+ throw new UsageError("--role doesn't apply to this access action.");
662
+ }
663
+ if (command.name === "connectors") {
664
+ const connecting = command.action === "connect";
665
+ if (!connecting && (values.project !== undefined || values.name !== undefined || values.accept !== undefined || values.token !== undefined)) {
666
+ throw new UsageError("--project, --name, --token and --accept only apply to `sinatra connectors connect`.");
667
+ }
668
+ }
669
+ if (values.yes !== undefined && command.name !== "help" && command.name !== "version" && !requiresConfirmation(command)) {
670
+ throw new UsageError("--yes doesn't apply to this action.");
671
+ }
672
+ const emailPreferences = {};
673
+ for (const [flag, field] of [["setup-reminders", "setupReminders"], ["task-alerts", "taskAlerts"]]) {
674
+ const value = values[flag];
675
+ if (value === undefined)
676
+ continue;
677
+ if (value !== "on" && value !== "off")
678
+ throw new UsageError(`--${flag} takes on or off.`);
679
+ emailPreferences[field] = value === "on";
680
+ }
681
+ if (command.name === "billing") {
682
+ if (command.action === "upgrade") {
683
+ if (values.plan !== "pro" && values.plan !== "team" && values.plan !== "scale")
684
+ throw new UsageError("Billing upgrade requires --plan pro, team or scale.");
685
+ }
686
+ else if (values.plan !== undefined)
687
+ throw new UsageError("--plan only applies to billing upgrade.");
688
+ }
188
689
  return {
189
690
  command,
190
691
  files: values.file ?? [],
191
692
  wait,
192
693
  timeoutMs,
193
694
  json: values.json ?? false,
695
+ emailPreferences,
194
696
  pasteToken: values.token ?? false,
195
697
  noBrowser: values["no-browser"] ?? false,
698
+ ...(command.name === "repo" ? { secretMetadata: {
699
+ ...(values.host !== undefined ? { hosts: values.host } : {}),
700
+ ...(values.header !== undefined ? { header: values.header } : {}),
701
+ ...(values.prefix !== undefined ? { prefix: values.prefix } : {}),
702
+ ...(values["capability-request"] !== undefined ? { capabilityRequestId: values["capability-request"] } : {}),
703
+ } } : {}),
704
+ ...(command.name === "connectors" && command.action === "connect" ? { connection: {
705
+ ...(values.project?.trim() ? { projectRef: values.project.trim() } : {}),
706
+ ...(values.name !== undefined ? { label: values.name } : {}),
707
+ accept: values.accept ?? false,
708
+ token: values.token ?? false,
709
+ } } : {}),
710
+ ...(values.role === "member" || values.role === "admin" ? { role: values.role } : {}),
711
+ ...(values.yes !== undefined ? { yes: values.yes } : {}),
196
712
  ...(values.repo !== undefined ? { repo: values.repo } : {}),
197
713
  ...(values.query !== undefined ? { query: values.query } : {}),
198
714
  ...(values.title !== undefined ? { title: values.title } : {}),
715
+ ...(values.model !== undefined ? { model: values.model } : {}),
716
+ ...(values.engine !== undefined ? { engine: values.engine } : {}),
717
+ ...(values.effort !== undefined ? { effort: values.effort } : {}),
199
718
  ...(values.workspace !== undefined ? { workspace: values.workspace } : {}),
719
+ ...(values.plan === "pro" || values.plan === "team" || values.plan === "scale" ? { plan: values.plan } : {}),
200
720
  ...(values.status !== undefined ? { status: values.status } : {}),
201
721
  ...(limit !== undefined ? { limit } : {}),
202
722
  ...(values["api-url"] !== undefined ? { apiUrl: values["api-url"] } : {}),
203
723
  };
204
724
  }
725
+ /** The words after `connectors` that make it the group: none, `list`, or a connect or disconnect. */
726
+ function connectorsShape(rest) {
727
+ return rest.length === 0 || (rest.length === 1 && rest[0] === "list") || rest[0] === "connect" || rest[0] === "disconnect";
728
+ }
729
+ /** Whether the command line is the `sinatra connectors` group, read leniently so a bad option can't hide it. */
730
+ function connectorsInvocation(argv) {
731
+ const [first, ...rest] = parseArgs({ args: argv, allowPositionals: true, strict: false, options: { ...OPTIONS, ...CONNECTOR_OPTIONS } }).positionals;
732
+ return first === "connectors" && connectorsShape(rest);
733
+ }
205
734
  /**
206
735
  * An argument that starts with `-` but holds whitespace, before any `--`: a prompt, not options
207
736
  * (`sinatra "-v is broken"`).
@@ -275,6 +804,133 @@ export async function startTask(client, workspaceId, body, repos, notice) {
275
804
  }
276
805
  return { started: await client.startTask(workspaceId, body), repo: null };
277
806
  }
807
+ function subscriptionFailure(status) {
808
+ if (status === "denied")
809
+ return new UsageError("Subscription authorization was denied. Run connect again to try again.");
810
+ if (status === "expired")
811
+ return new UsageError("Subscription authorization expired. Run connect again.");
812
+ return new UsageError("Subscription connection failed. Run connect again, or reconnect on your Sinatra Account page.");
813
+ }
814
+ /** Never print provider errors or response bodies: they can contain authorization credentials. */
815
+ function subscriptionApiFailure(error) {
816
+ if (error instanceof ApiError) {
817
+ if (error.status === 409 && error.code === "device_auth_not_enabled") {
818
+ let settingsUrl;
819
+ if (typeof error.detail.settingsUrl === "string" && !/[\s\u0000-\u001f\u007f-\u009f]/u.test(error.detail.settingsUrl)) {
820
+ try {
821
+ const url = new URL(error.detail.settingsUrl);
822
+ if (["https:", "http:"].includes(url.protocol) && !url.username && !url.password)
823
+ settingsUrl = url.href;
824
+ }
825
+ catch { /* An unsafe or malformed URL must not reach the terminal. */ }
826
+ }
827
+ return new UsageError(`Enable device-code login in your ChatGPT security settings${settingsUrl ? `: ${settingsUrl}` : ""}, then run \`sinatra subscriptions connect codex\` again.`);
828
+ }
829
+ if (["denied", "expired", "failed"].includes(String(error.detail.status)))
830
+ return subscriptionFailure(error.detail.status);
831
+ if (error.status === 401)
832
+ return new UsageError("Your Sinatra sign-in was refused. Run `sinatra login` again.");
833
+ if (error.status === 403)
834
+ return new UsageError("You don't have access to manage these subscriptions.");
835
+ if (error.status === 404)
836
+ return new UsageError("The workspace, subscription, or provider isn't available to your account.");
837
+ if (error.status === 429)
838
+ return new UsageError("Too many subscription requests. Try again later.");
839
+ }
840
+ return new UsageError("The subscription request couldn't be completed. Try again, or use your Sinatra Account page.");
841
+ }
842
+ /** Subscription commands have their own failure boundary, so no raw API or transport error escapes. */
843
+ export async function subscriptions(command, deps) {
844
+ const { client, workspaceId, out } = deps;
845
+ const emit = (value) => out(`${JSON.stringify(value, null, 2)}\n`);
846
+ try {
847
+ if (command.action === "list") {
848
+ const result = await client.listSubscriptions(workspaceId);
849
+ if (deps.json)
850
+ return emit(result);
851
+ if (result.connections.length === 0)
852
+ out("No subscriptions connected.\n");
853
+ for (const connection of result.connections) {
854
+ const status = connection.needsReconnect ? "needs reconnect" : connection.connected ? "connected" : "disconnected";
855
+ out(printable(`${connection.id} ${connection.provider} ${connection.label ?? connection.email ?? ""} ${status}${connection.primary ? " (primary)" : ""}\n`));
856
+ }
857
+ return;
858
+ }
859
+ if (command.action === "remove") {
860
+ await client.removeSubscription(workspaceId, command.connectionId);
861
+ if (deps.json)
862
+ emit({ removed: true, id: command.connectionId });
863
+ else
864
+ out("Subscription removed.\n");
865
+ return;
866
+ }
867
+ const result = await connectSubscription(command.provider, deps);
868
+ // Only the public outcome is printed, never pending bindings or the pasted completion code.
869
+ if (deps.json)
870
+ emit({ provider: command.provider, status: "connected", email: result.email ?? null });
871
+ else
872
+ out(printable(`Connected ${command.provider}${result.email ? ` (${result.email})` : ""}.\n`));
873
+ }
874
+ catch (error) {
875
+ if (error instanceof UsageError)
876
+ throw error;
877
+ throw subscriptionApiFailure(error);
878
+ }
879
+ }
880
+ async function connectSubscription(provider, deps) {
881
+ const { client, workspaceId, notice } = deps;
882
+ const handoff = async (url, userCode) => {
883
+ notice(printable(`Open this URL to connect ${provider}:\n${url}\n${userCode ? `Verification code: ${userCode}\n` : ""}`));
884
+ if (deps.openBrowser && !await deps.openBrowser(url).catch(() => false))
885
+ notice("Couldn't open a browser. Open the URL above yourself.\n");
886
+ };
887
+ if (provider === "claude") {
888
+ const started = await client.startSubscription(workspaceId, provider);
889
+ await handoff(started.authorizeUrl);
890
+ const code = (await deps.askSecret("Claude authorization code (hidden): ")).trim();
891
+ if (!code)
892
+ throw new UsageError("No authorization code given. Run `sinatra subscriptions connect claude` again.");
893
+ const result = await client.completeSubscription(workspaceId, { code, state: started.state, pendingToken: started.pendingToken });
894
+ if (result.status !== "connected")
895
+ throw subscriptionFailure(result.status);
896
+ return result;
897
+ }
898
+ const now = deps.now ?? Date.now;
899
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
900
+ const deadline = now() + (deps.timeoutMs ?? 15 * 60_000);
901
+ let interval;
902
+ let body;
903
+ if (provider === "codex") {
904
+ const started = await client.startSubscription(workspaceId, provider);
905
+ await handoff(started.verificationUrl, started.userCode);
906
+ interval = started.interval;
907
+ body = { deviceAuthId: started.deviceAuthId, userCode: started.userCode, pollToken: started.pollToken };
908
+ }
909
+ else if (provider === "xai") {
910
+ const started = await client.startSubscription(workspaceId, provider);
911
+ await handoff(started.verificationUrl, started.userCode);
912
+ interval = started.interval;
913
+ body = { deviceCode: started.deviceCode, pollToken: started.pollToken };
914
+ }
915
+ else {
916
+ const started = await client.startSubscription(workspaceId, provider);
917
+ await handoff(started.loginUrl);
918
+ interval = started.interval;
919
+ body = { pollToken: started.pollToken };
920
+ }
921
+ const intervalMs = Number.isFinite(interval) && interval > 0 ? Math.max(1_000, interval * 1_000) : 5_000;
922
+ while (now() < deadline) {
923
+ await sleep(Math.min(intervalMs, deadline - now()));
924
+ if (now() >= deadline)
925
+ break;
926
+ const result = await client.pollSubscription(workspaceId, provider, body);
927
+ if (result.status === "connected")
928
+ return result;
929
+ if (result.status !== "pending")
930
+ throw subscriptionFailure(result.status);
931
+ }
932
+ throw new UsageError("Timed out waiting for subscription authorization. Run connect again.");
933
+ }
278
934
  async function pastedToken(deps) {
279
935
  // The sign-in page sends a signed-in visitor straight on, and a signed-out one there after signing in.
280
936
  deps.out(deps.apiUrl === DEFAULT_API_URL
@@ -328,8 +984,10 @@ async function loginWorkspace(workspaces, deps) {
328
984
  }
329
985
  if (workspaces.length === 1)
330
986
  return workspaces[0].id;
331
- if (workspaces.length === 0)
987
+ if (workspaces.length === 0) {
988
+ out('You don\'t have a workspace yet. Create one with: sinatra workspace create "<name>"\n');
332
989
  return undefined;
990
+ }
333
991
  if (!deps.interactive) {
334
992
  // Piped stdin has nothing left after the token: asking would only read end-of-input.
335
993
  out("No default workspace saved: you belong to more than one. Set one with `sinatra workspace <id>`, or log in with --workspace <id>.\n");
@@ -419,6 +1077,8 @@ export function classifyRefusal(error, context = {}) {
419
1077
  case "invalid_token":
420
1078
  return { kind: context.during === "login" ? "token_rejected_at_login" : "token_invalid" };
421
1079
  case "not_found":
1080
+ if (context.group === "connectors")
1081
+ return { kind: "connectors_unavailable" };
422
1082
  return { kind: context.during ? "task_api_off" : "not_found" };
423
1083
  case "unavailable":
424
1084
  if (typeof error.detail.taskId === "string")
@@ -440,23 +1100,436 @@ export function explain(error, context = {}) {
440
1100
  case "task_api_off":
441
1101
  return "The task API isn't available for this account. Write to contact@sinatra.dev if you think it should be.";
442
1102
  case "not_found": return "No such task or workspace, or you're not a member of it.";
1103
+ case "connectors_unavailable": return "Connectors aren't available for this workspace.";
443
1104
  case "created_not_started":
444
1105
  return `Task ${refusal.taskId} was created but Sinatra couldn't start it yet. Run \`sinatra reply ${refusal.taskId} "go"\` to start it (your prompt goes first).`;
445
1106
  case "message_saved_not_sent":
446
1107
  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
1108
  case "unreachable": return "Sinatra couldn't be reached; try again shortly.";
448
1109
  }
1110
+ // The server's reason names API routes; say it in commands. Connecting GitHub doesn't lift the limit.
1111
+ if (refusal.code === "workspace_limit") {
1112
+ return "You already created a workspace without GitHub, and each person can create one that way. Use that workspace " +
1113
+ "(`sinatra whoami` lists it; `sinatra workspace <id>` makes it the default), and connect GitHub to it with " +
1114
+ "`sinatra connect github` if it isn't yet. To make another workspace, install the Sinatra GitHub App on another " +
1115
+ "account or organization from the dashboard's Add a workspace.";
1116
+ }
1117
+ // The connect request keeps no server detail, so say the role rule here rather than the model-key one.
1118
+ if (context.group === "connectors" && refusal.code === "actor_not_authorized") {
1119
+ return "Only workspace owners and admins can connect or disconnect services.";
1120
+ }
449
1121
  // A refusal the server explained itself (delegation's are the dashboard's own words).
450
1122
  if (typeof error.detail.reason === "string")
451
1123
  return printable(error.detail.reason);
452
1124
  switch (refusal.code) {
1125
+ case "invalid_model_selection": return "That engine/model/effort selection isn't in Sinatra's catalog. Check the dashboard's model settings.";
1126
+ case "actor_not_authorized":
1127
+ 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.";
1128
+ case "unsupported_provider": return "Supported key providers are anthropic and openrouter.";
1129
+ case "key_validation_failed":
1130
+ return "Sinatra couldn't validate that API key. Check the key and its provider, then try again.";
1131
+ case "provider_unreachable": return "The model provider couldn't be reached to validate the key. Try again shortly.";
1132
+ case "invalid_body": return "The request is invalid. Check the supplied configuration or metadata; enter secret values only through the hidden prompt or stdin.";
1133
+ case "internal_error": return "Sinatra couldn't save the change. Check the workspace's current settings before trying again.";
1134
+ case "no_customer": return "This workspace has no billing account yet. Run `sinatra billing upgrade --plan <pro|team|scale>` first.";
1135
+ case "customer_missing": return "Your billing account needs to be reconnected. Start a new subscription with `sinatra billing upgrade --plan <pro|team|scale>`.";
1136
+ case "billing_disabled": return "Billing is disabled on this Sinatra installation. Contact your administrator.";
1137
+ case "plans_not_configured": return "Paid billing plans are not configured on this installation. Contact your administrator.";
453
1138
  case "invalid_prompt": return "The message is empty or too long.";
454
1139
  case "invalid_repo": return "That repository isn't connected to this workspace (see the dashboard's Repositories page).";
1140
+ case "repo_not_found": return "That repository isn't available in this workspace. Run `sinatra repos` to list accessible repositories.";
1141
+ case "secret_not_found": return "That repository secret doesn't exist. Use secrets set with --host to create it.";
1142
+ case "invalid_secret_hosts": return "Supply at least one valid allowed host with --host; hosts must authorize the intended target.";
1143
+ case "invalid_secret_header": return "That proxy header isn't valid. Check --header.";
1144
+ case "invalid_secret_prefix": return "That proxy prefix isn't valid. Check --prefix.";
1145
+ case "invalid_secret_name": return "That secret name isn't valid. Use the naming rules shown in the dashboard.";
1146
+ case "invalid_secret_value": return "That secret value isn't valid. Enter a nonempty value through the hidden prompt or stdin.";
1147
+ case "secret_cap_exceeded": return "This repository has reached its secret limit.";
1148
+ case "capability_request_not_found": return "That capability request isn't available for this repository.";
1149
+ case "capability_target_not_authorized": return "The allowed hosts don't authorize the capability request's target. Update --host.";
1150
+ case "repo_environments_not_enabled": return "Repository environments aren't enabled for this workspace.";
1151
+ case "invalid_model": return "Sinatra doesn't offer that model (see docs.sinatra.dev/docs/configuration/models).";
455
1152
  case "invalid_status": return "That isn't a task status (some are: pending, implementing, replied, pr_open, completed, failed).";
456
1153
  case "invalid_limit": return "--limit takes a whole number from 1 to 100.";
457
1154
  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.";
458
1155
  case "not_running": return "That task isn't running.";
459
1156
  case "idempotency_conflict": return "That request conflicts with an earlier one; try again.";
1157
+ case "invalid_project_ref": return "That doesn't look like a valid project reference for this service.";
1158
+ case "invalid_label": return "Use a name of up to 64 characters, with no line breaks or invisible characters.";
1159
+ case "invalid_token_value": return "That token can't be used. Paste it exactly as the provider shows it, with no spaces or line breaks.";
1160
+ case "acknowledgement_required": return "The terms for this connection have changed. Run the command again to review them.";
1161
+ case "connector_label_taken": return "This workspace already has a connection with that name. Pass --name to choose another.";
1162
+ case "connector_cap_exceeded": return "This workspace has reached its connection limit, counting sign-ins still in progress. Disconnect one first.";
1163
+ case "connector_not_found": return "No such service. Run `sinatra connectors` to see what can be connected.";
1164
+ case "connection_not_found": return "No such connection. Run `sinatra connectors` to see this workspace's connections.";
460
1165
  default: return `Sinatra refused: ${error.code} (HTTP ${error.status}).`;
461
1166
  }
462
1167
  }
1168
+ /** Execute billing without mixing machine-readable output with browser notices. */
1169
+ export async function runBilling(client, workspaceId, invocation, deps) {
1170
+ const { action } = invocation.command;
1171
+ if (action === "status") {
1172
+ const status = await client.planStatus(workspaceId);
1173
+ if (invocation.json) {
1174
+ deps.out(`${JSON.stringify(status)}\n`);
1175
+ return;
1176
+ }
1177
+ const lines = [`Plan: ${status.capacity?.plan ?? status.plan}`];
1178
+ if (status.capacity)
1179
+ lines.push(`Capacity: ${status.capacity.running} running, ${status.capacity.queued} queued`);
1180
+ if (status.byokConfigured !== undefined)
1181
+ lines.push(`Own provider credentials: ${status.byokConfigured ? "configured" : "not configured"}`);
1182
+ const sub = status.subscription;
1183
+ lines.push(`Subscription: ${sub?.status ?? "none"}`);
1184
+ if (sub?.trialEndsAt)
1185
+ lines.push(`Trial ends: ${sub.trialEndsAt}`);
1186
+ if (sub?.currentPeriodEnd)
1187
+ lines.push(`Current period ends: ${sub.currentPeriodEnd}`);
1188
+ if (sub?.cancelAtPeriodEnd)
1189
+ lines.push(`Cancels at period end${sub.endsAt ? `: ${sub.endsAt}` : ""}`);
1190
+ if (sub?.pastDueSinceAt)
1191
+ lines.push(`Payment past due since: ${sub.pastDueSinceAt}`);
1192
+ if (sub?.actionRequiredHostedInvoiceUrl)
1193
+ lines.push(`Payment action required: ${sub.actionRequiredHostedInvoiceUrl}`);
1194
+ deps.out(printable(`${lines.join("\n")}\n`));
1195
+ return;
1196
+ }
1197
+ if (action === "upgrade" && !invocation.plan)
1198
+ throw new UsageError("Billing upgrade requires --plan pro, team or scale.");
1199
+ const result = action === "upgrade"
1200
+ ? await client.billingCheckout(workspaceId, invocation.plan)
1201
+ : await client.billingPortal(workspaceId);
1202
+ const url = new URL(result.url);
1203
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1204
+ throw new UsageError("Sinatra returned an invalid billing URL.");
1205
+ if (invocation.json) {
1206
+ deps.out(`${JSON.stringify(result)}\n`);
1207
+ return;
1208
+ }
1209
+ deps.out(printable(`Open billing in your browser:\n${result.url}\n`));
1210
+ // The URL is already printed, so failed desktop integration never loses the handoff.
1211
+ await deps.openBrowser(result.url).catch(() => false);
1212
+ }
1213
+ /**
1214
+ * `sinatra workspace create`: the first workspace becomes the default, so the next command needs
1215
+ * no -w; an existing default is kept. The config is read again after the request, which may have
1216
+ * refreshed the sign-in and rotated the tokens the caller's copy holds.
1217
+ */
1218
+ export async function runWorkspaceCreate(client, invocation, deps) {
1219
+ const { workspace } = await client.createWorkspace(invocation.command.workspaceName);
1220
+ const latest = (await deps.read()) ?? deps.fallback;
1221
+ const madeDefault = !latest.workspaceId;
1222
+ if (madeDefault)
1223
+ await deps.write({ ...latest, workspaceId: workspace.id });
1224
+ const { out } = deps;
1225
+ if (invocation.json) {
1226
+ out(`${JSON.stringify({ workspace, defaultWorkspaceId: madeDefault ? workspace.id : latest.workspaceId }, null, 2)}\n`);
1227
+ return;
1228
+ }
1229
+ out(printable(`Created workspace ${workspace.name} (${workspace.id}). You're its owner.\n`));
1230
+ out(madeDefault
1231
+ ? "It's your default workspace.\n"
1232
+ : printable(`Your default workspace is still ${latest.workspaceId}; switch with: sinatra workspace ${workspace.id}\n`));
1233
+ out(printable(`Connect GitHub next: sinatra connect github${madeDefault ? "" : ` -w ${workspace.id}`}\n`));
1234
+ }
1235
+ /** Browser authorization is observed through the existing workspace overview, never a new status API. */
1236
+ export async function runConnect(client, workspaceId, invocation, deps) {
1237
+ const { integration } = invocation.command;
1238
+ const result = await client.integrationConnect(workspaceId, integration);
1239
+ if (invocation.json) {
1240
+ deps.out(`${JSON.stringify(result)}\n`);
1241
+ return;
1242
+ }
1243
+ const url = new URL(result.url);
1244
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1245
+ throw new UsageError("Sinatra returned an invalid integration URL.");
1246
+ deps.out(printable(`Connect ${integration} in your browser:\n${result.url}\n`));
1247
+ await deps.openBrowser(result.url).catch(() => false);
1248
+ const now = deps.now ?? Date.now;
1249
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1250
+ const deadline = now() + invocation.timeoutMs;
1251
+ while (now() < deadline) {
1252
+ const overview = await client.getWorkspace(workspaceId);
1253
+ if (integration === "buzz" && overview.buzz?.status === "pending_owner") {
1254
+ deps.out("Buzz joined. A community owner or admin must link their Buzz account before tasks can start.\n");
1255
+ return;
1256
+ }
1257
+ const connected = integration === "telegram"
1258
+ ? overview.telegram.connected === true
1259
+ : overview[integration]?.status === "connected" && (integration !== "linear" || overview.linear.needsReconnect === false);
1260
+ if (connected) {
1261
+ deps.out(printable(`${integration} connected.\n`));
1262
+ return;
1263
+ }
1264
+ const remaining = deadline - now();
1265
+ if (remaining > 0)
1266
+ await sleep(Math.min(2_000, remaining));
1267
+ }
1268
+ 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\`.`);
1269
+ }
1270
+ /** How long, and how often, a sign-in at a terminal watches the list for its connection. */
1271
+ const SIGN_IN_WAIT_MS = 10 * 60_000;
1272
+ const SIGN_IN_POLL_MS = 3_000;
1273
+ /**
1274
+ * What the dashboard and MCP check a connect link's project and name against, copied from
1275
+ * packages/shared/src/lib/connectors/catalog.ts (`reference.pattern`, and the patterns
1276
+ * `looksLikeConnectorCredential` reads): the CLI is published on its own and can't import it. A
1277
+ * test compares the copies. A connector missing here (a newer API's) gets the credential check only.
1278
+ */
1279
+ export const CONNECT_LINK_REFERENCE_PATTERNS = {
1280
+ neon: /^[a-z0-9-]{3,64}$/,
1281
+ supabase: /^[a-z0-9]{20}$/,
1282
+ posthog: /^[0-9]{1,12}$/,
1283
+ sentry: /^[a-z0-9][a-z0-9_-]{0,63}$/,
1284
+ };
1285
+ export const CONNECT_LINK_CREDENTIAL_PATTERNS = [
1286
+ /^napi_/, /^sbp_/, /^phx_/, /^sntry[su]_/, /^pscale_tkn_/, /^cfk_/, /^ntn_/,
1287
+ ];
1288
+ const CONNECTOR_LABEL_MAX_CHARS = 64;
1289
+ const LABEL_FORBIDDEN = /[\p{Cc}\p{Cf}\u2028\u2029]/u;
1290
+ /**
1291
+ * Refuses a `--project` or `--name` that the dashboard would drop from a connect link, or that is
1292
+ * shaped like a credential (it may be a token typed in the wrong place). The value is never repeated.
1293
+ */
1294
+ function checkConnectLinkValues(entry, connection) {
1295
+ const credential = (value) => CONNECT_LINK_CREDENTIAL_PATTERNS.some((pattern) => pattern.test(value.trim()));
1296
+ for (const [flag, value] of [["--project", connection.projectRef], ["--name", connection.label]]) {
1297
+ if (value !== undefined && credential(value)) {
1298
+ throw new UsageError(`That ${flag} looks like a token, so it was not used. Never put a token in a connect link; the provider's sign-in happens in your browser.`);
1299
+ }
1300
+ }
1301
+ const project = connection.projectRef;
1302
+ const pattern = CONNECT_LINK_REFERENCE_PATTERNS[entry.id];
1303
+ if (project && pattern && !pattern.test(project)) {
1304
+ throw new UsageError(printable(`That --project doesn't look like a ${entry.name} ${connectorReference(entry)?.label ?? "project reference"}.`));
1305
+ }
1306
+ const label = connection.label?.trim();
1307
+ if (label !== undefined && (label === "" || [...label].length > CONNECTOR_LABEL_MAX_CHARS || LABEL_FORBIDDEN.test(label))) {
1308
+ throw new UsageError("Use a --name of up to 64 characters, with no line breaks or invisible characters.");
1309
+ }
1310
+ }
1311
+ /** A failed poll worth retrying: a server error, a rate limit, or no answer at all (not a sign-in or config failure). */
1312
+ function pollFailureIsTransient(error) {
1313
+ if (error instanceof ApiError)
1314
+ return error.status >= 500 || error.status === 429;
1315
+ return !(error instanceof SignInError || error instanceof ConfigError || error instanceof UsageError);
1316
+ }
1317
+ /** One shell word: as is when nothing in it needs quoting, otherwise single-quoted. */
1318
+ function shellWord(value) {
1319
+ return /^[A-Za-z0-9._@%+=:,/-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
1320
+ }
1321
+ /** The command that signs a connection in again: the same service, reference and name. */
1322
+ function signInAgainCommand(connection) {
1323
+ return `sinatra connectors connect ${shellWord(connection.connector)}${connection.projectRef ? ` --project ${shellWord(connection.projectRef)}` : ""} --name ${shellWord(connection.label)}`;
1324
+ }
1325
+ /** The reference `entry` takes, read from either API shape; null when it takes none. */
1326
+ function connectorReference(entry) {
1327
+ if (entry.reference !== undefined)
1328
+ return entry.reference;
1329
+ return entry.projectRefLabel ? { label: entry.projectRefLabel, required: true } : null;
1330
+ }
1331
+ function connectionLine(connection, projectRefLabel) {
1332
+ const readOnly = connection.grantLabel === "enforced"
1333
+ ? `read-only, enforced by ${connection.name}`
1334
+ : connection.grantLabel === "token_decides" ? "may be able to make changes" : "read-only not guaranteed";
1335
+ return [
1336
+ `${connection.name} · ${connection.label}`,
1337
+ ...(connection.projectRef ? [`${projectRefLabel} ${connection.projectRef}`] : []),
1338
+ readOnly,
1339
+ ...(connection.status === "needs_reconnect"
1340
+ ? [`needs sign-in again (run: ${signInAgainCommand(connection)})`]
1341
+ : connection.status !== "active" ? [connection.status] : []),
1342
+ ...(connection.connectedByName ? [`connected by ${connection.connectedByName}`] : []),
1343
+ // Disconnect takes the id, so the list has to show it.
1344
+ `(connection ${connection.id})`,
1345
+ ].join(" ");
1346
+ }
1347
+ /**
1348
+ * `sinatra connectors` (unlisted). A token is read only through the hidden reader and sent only
1349
+ * in the connect request's body, through the client path that keeps no server detail.
1350
+ */
1351
+ export async function runConnectors(client, workspaceId, inv, deps) {
1352
+ const { command } = inv;
1353
+ const emit = (value) => deps.out(`${JSON.stringify(value, null, 2)}\n`);
1354
+ // Writes are for owners and admins: refuse anyone else before showing terms or asking for a token.
1355
+ const requireAdmin = async () => {
1356
+ const { role } = await client.getWorkspace(workspaceId);
1357
+ if (role !== "owner" && role !== "admin")
1358
+ throw new ApiError(403, "actor_not_authorized");
1359
+ };
1360
+ /** The service being connected, once the catalog has named it. */
1361
+ let listedName;
1362
+ /**
1363
+ * Signing in, and accepting the warning, happen in a person's browser: the CLI only hands over
1364
+ * the dashboard link that opens the dialog filled in. At a terminal it opens the link and watches
1365
+ * the list for the new connection; otherwise it prints the link and returns.
1366
+ */
1367
+ const signInByLink = async (entry, connection, before) => {
1368
+ if (!entry.connectUrl)
1369
+ throw new UsageError(printable(`Sign in to ${entry.name} from the Connectors page of your Sinatra dashboard.`));
1370
+ const url = new URL(entry.connectUrl);
1371
+ if (url.protocol !== "https:" && url.protocol !== "http:")
1372
+ throw new UsageError("Sinatra returned an invalid connect link.");
1373
+ if (connection.projectRef !== undefined)
1374
+ url.searchParams.set("project", connection.projectRef);
1375
+ if (connection.label !== undefined)
1376
+ url.searchParams.set("name", connection.label);
1377
+ url.searchParams.set("method", "oauth");
1378
+ const link = url.toString();
1379
+ if (inv.json || !deps.interactive) {
1380
+ return emit({
1381
+ connector: entry.id,
1382
+ url: link,
1383
+ next: `Have a workspace admin or owner open this link in a browser, sign in to ${entry.name} and accept the warning there. Then run \`sinatra connectors -w ${workspaceId} --json\` to check that the connection appears.`,
1384
+ });
1385
+ }
1386
+ deps.out(printable(`${entry.name}'s warning and sign-in happen in your browser:\n${link}\n`));
1387
+ await deps.openBrowser?.(link).catch(() => false);
1388
+ // Only the caller's own new connection counts: another admin may connect the same service meanwhile.
1389
+ const { user } = await client.me();
1390
+ const known = new Set(before);
1391
+ const now = deps.now ?? Date.now;
1392
+ const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1393
+ const deadline = now() + SIGN_IN_WAIT_MS;
1394
+ while (now() < deadline) {
1395
+ await sleep(Math.min(SIGN_IN_POLL_MS, deadline - now()));
1396
+ let connections;
1397
+ try {
1398
+ ({ connections } = await client.listConnectors(workspaceId));
1399
+ }
1400
+ catch (error) {
1401
+ // A dropped connection, a server error or a rate limit is not an answer: keep watching until the deadline.
1402
+ // Anything else (signed out, no access, connectors off) ends the wait with its own message.
1403
+ if (pollFailureIsTransient(error))
1404
+ continue;
1405
+ throw error;
1406
+ }
1407
+ const added = connections.find((row) => row.connector === entry.id && row.status === "active" && row.connectedByUserId === user.id && !known.has(row.id));
1408
+ if (added) {
1409
+ deps.out(printable(`Connected ${added.name} (${added.label}). Agents can use it on their next run.\n`));
1410
+ return;
1411
+ }
1412
+ }
1413
+ throw new UsageError("Nothing was connected yet. `sinatra connectors` shows the connection once it is.");
1414
+ };
1415
+ try {
1416
+ if (command.action === "list") {
1417
+ const result = await client.listConnectors(workspaceId);
1418
+ if (inv.json)
1419
+ return emit(result);
1420
+ if (result.connections.length === 0)
1421
+ deps.out("Nothing connected.\n");
1422
+ for (const connection of result.connections) {
1423
+ const entry = result.catalog.find((row) => row.id === connection.connector);
1424
+ const label = (entry && connectorReference(entry)?.label) ?? "Project";
1425
+ deps.out(printable(`${connectionLine(connection, label)}\n`));
1426
+ }
1427
+ if (result.catalog.length > 0)
1428
+ deps.out(printable(`Available: ${result.catalog.map((entry) => entry.id).join(", ")}\n`));
1429
+ return;
1430
+ }
1431
+ if (command.action === "disconnect") {
1432
+ await requireAdmin();
1433
+ await confirmWorkspaceMutation(command, { yes: inv.yes ?? false, interactive: deps.interactive, workspaceId, ask: deps.ask });
1434
+ const result = await client.disconnectConnector(workspaceId, command.connectionId);
1435
+ if (inv.json)
1436
+ return emit(result);
1437
+ deps.out("Disconnected.\n");
1438
+ if (result.providerRevocation === "revoked")
1439
+ deps.out("Sinatra's access was revoked at the provider.\n");
1440
+ else if (result.providerRevocation === "failed") {
1441
+ deps.out("Sinatra could not revoke its access at the provider. Remove Sinatra in your account settings there.\n");
1442
+ }
1443
+ else if (result.revokeAtProvider)
1444
+ deps.out("The token still works at the provider until you revoke it there.\n");
1445
+ return;
1446
+ }
1447
+ const connection = inv.connection;
1448
+ if (!connection)
1449
+ throw new UsageError(CONNECTORS_USAGE);
1450
+ const listed = await client.listConnectors(workspaceId);
1451
+ // Off for this workspace or caller, the list still answers while connections remain: nothing can be connected.
1452
+ if (!listed.enabled)
1453
+ throw new ApiError(404, "not_found");
1454
+ const entry = listed.catalog.find((row) => row.id === command.connector);
1455
+ if (!entry)
1456
+ throw new ApiError(404, "connector_not_found");
1457
+ listedName = entry.name;
1458
+ const reference = connectorReference(entry);
1459
+ if (!reference && connection.projectRef !== undefined) {
1460
+ throw new UsageError(printable(`${entry.name} takes no project reference, so leave out --project. ${CONNECTORS_USAGE}`));
1461
+ }
1462
+ const offersSignIn = entry.methods.includes("oauth");
1463
+ const takesToken = entry.methods.includes("token");
1464
+ if ((connection.token || connection.accept) && !takesToken) {
1465
+ const flags = [connection.token ? "--token" : "", connection.accept ? "--accept" : ""].filter(Boolean).join(" and ");
1466
+ throw new UsageError(printable(`${entry.name} connects only by signing in, in the browser: leave out ${flags}.`));
1467
+ }
1468
+ // Signing in is the default only when nothing asks for a token: `--accept` keeps pasting one, as
1469
+ // it did before sign-in existed (`echo "$KEY" | sinatra connectors connect neon --project p --accept`).
1470
+ if (offersSignIn && !connection.token && !connection.accept) {
1471
+ checkConnectLinkValues(entry, connection);
1472
+ // As with a token: refuse anyone but an owner or admin before handing over a link or waiting.
1473
+ await requireAdmin();
1474
+ return await signInByLink(entry, connection, listed.connections.map((row) => row.id));
1475
+ }
1476
+ if (reference?.required && connection.projectRef === undefined) {
1477
+ throw new UsageError(printable(`Connecting ${entry.name} requires --project <ref>: its ${reference.label}.`));
1478
+ }
1479
+ await requireAdmin();
1480
+ // An API from before sign-in sends only `acknowledgement`, which is the token's.
1481
+ const acknowledgement = entry.acknowledgements?.token ?? entry.acknowledgement;
1482
+ const { warning, confirmations } = acknowledgement;
1483
+ if (warning) {
1484
+ deps.notice(printable(`${warning.title}\n${warning.body}\n${warning.items.map((item) => ` - ${item}\n`).join("")}\n`));
1485
+ }
1486
+ deps.notice(printable(`${acknowledgement.text}\n\n`));
1487
+ // The acknowledgement already ends with the provider's guidance; say it only if it ever doesn't.
1488
+ if (!acknowledgement.text.includes(entry.providerGuidance))
1489
+ deps.notice(printable(`${entry.providerGuidance}\n\n`));
1490
+ if (confirmations?.length) {
1491
+ deps.notice(printable(`By accepting, you confirm:\n${confirmations.map((line) => ` - ${line}\n`).join("")}\n`));
1492
+ }
1493
+ if (!connection.accept) {
1494
+ if (!deps.interactive)
1495
+ throw new UsageError("Connecting needs your acceptance of the text above. Run at a terminal or pass --accept.");
1496
+ const answer = await deps.ask(printable(`Accept and connect ${entry.name}? [y/N] `));
1497
+ if (!/^(y|yes)$/i.test(answer.trim()))
1498
+ throw new UsageError("Cancelled. Nothing changed.");
1499
+ }
1500
+ deps.notice(printable(`${entry.tokenHelp}\n${entry.tokenHelpUrl}\n`));
1501
+ let token;
1502
+ try {
1503
+ token = (await deps.askSecret(printable(`${entry.name} token (hidden): `))).trim();
1504
+ }
1505
+ catch {
1506
+ throw new UsageError("Couldn't read the token. Paste it at the hidden prompt or pipe it on stdin.");
1507
+ }
1508
+ if (!token)
1509
+ throw new UsageError("No token supplied. Nothing changed.");
1510
+ const connected = await client.connectConnector(workspaceId, {
1511
+ connector: entry.id,
1512
+ ...(connection.projectRef !== undefined ? { projectRef: connection.projectRef } : {}),
1513
+ ...(connection.label !== undefined ? { label: connection.label } : {}),
1514
+ token,
1515
+ // The version of the text just shown, so the server refuses if it has changed since.
1516
+ acknowledgementVersion: acknowledgement.version,
1517
+ // The confirmations just printed and accepted. An API that sends none refuses the field.
1518
+ ...(confirmations?.length ? { confirmations } : {}),
1519
+ });
1520
+ if (inv.json)
1521
+ return emit(connected);
1522
+ deps.out(printable(`Connected ${connected.name} (${connected.label}). Agents can use it on their next run.\n`));
1523
+ }
1524
+ catch (error) {
1525
+ // With no --name, the default name is the one that collided.
1526
+ if (error instanceof ApiError && error.code === "connector_label_taken" && command.action === "connect" && inv.connection?.label === undefined) {
1527
+ const name = listedName ?? "service";
1528
+ throw new UsageError(printable(`This workspace already has an unnamed ${name} connection. Give this one a name.`));
1529
+ }
1530
+ // The group's own wording, so a gated workspace isn't reported as a missing task.
1531
+ if (error instanceof ApiError)
1532
+ throw new UsageError(explain(error, { group: "connectors" }));
1533
+ throw error;
1534
+ }
1535
+ }