sinatra.dev 0.0.1 → 0.1.1
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 +99 -3
- package/dist/client.js +81 -0
- package/dist/commands.js +379 -0
- package/dist/config.js +69 -0
- package/dist/context.js +178 -0
- package/dist/follow.js +92 -0
- package/dist/index.js +320 -0
- package/dist/prompt.js +75 -0
- package/package.json +37 -8
- package/bin/sinatra.js +0 -3
package/README.md
CHANGED
|
@@ -1,5 +1,101 @@
|
|
|
1
|
-
# sinatra.dev
|
|
1
|
+
# sinatra.dev CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Hand coding tasks to [Sinatra](https://sinatra.dev) from your terminal, follow the conversation,
|
|
4
|
+
and get a GitHub pull request back when the work calls for one.
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
Requires Node 22 or newer.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm i -g sinatra.dev
|
|
12
|
+
sinatra --version
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Log in
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
sinatra login
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Create a personal access token on the **Access tokens** page of the Sinatra dashboard
|
|
22
|
+
(<https://app.sinatra.dev/tokens>) and paste it in; it isn't echoed. If you belong to more than one
|
|
23
|
+
workspace, pick the default one. The token is saved in `~/.config/sinatra/config.json`
|
|
24
|
+
(`$XDG_CONFIG_HOME/sinatra` if set, `%APPDATA%\sinatra` on Windows), readable only by you.
|
|
25
|
+
|
|
26
|
+
In a script, pipe the token in and name the default workspace with `-w`:
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
sinatra login -w <workspace-id> < token-file
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Without `-w`, piped input isn't asked for a workspace: set one later with `sinatra workspace <id>`.
|
|
33
|
+
A `-w` that isn't one of the token's workspaces is an error, and nothing is saved.
|
|
34
|
+
|
|
35
|
+
## Commands
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
sinatra "fix the flaky retry test" # start a task and follow it
|
|
39
|
+
sinatra "explain this" -f notes.md -f err.log # attach text files (80KB total)
|
|
40
|
+
sinatra reply <task-id> "also update the docs" # follow up, then follow it
|
|
41
|
+
sinatra show <task-id> # a task and its conversation
|
|
42
|
+
sinatra tasks # recent tasks in your workspace
|
|
43
|
+
sinatra stop <task-id> # stop a running turn
|
|
44
|
+
sinatra whoami # who the token acts as, and its workspaces
|
|
45
|
+
sinatra workspace [<id>] # list workspaces, or set the default
|
|
46
|
+
sinatra logout # revoke the token and forget it
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
| Command | Options |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `sinatra login` | `--api-url <url>`: another Sinatra API (https; plain http only for localhost); `-w, --workspace <id>`: the default workspace |
|
|
52
|
+
| `sinatra [start] "<what to do>"` | `-r, --repo <owner/name>`, `-f, --file <path>` (repeatable), `-t, --title <title>`, `-w, --workspace <id>`, `--timeout <minutes>`, `--no-wait`, `--json` (with `--no-wait`) |
|
|
53
|
+
| `sinatra reply <task-id> "<message>"` | `-f, --file <path>` (repeatable), `-w`, `--timeout <minutes>`, `--no-wait`, `--json` (with `--no-wait`) |
|
|
54
|
+
| `sinatra show <task-id>` | `-w`, `--json` |
|
|
55
|
+
| `sinatra tasks` | `--status <status>`, `-n, --limit <n>` (1 to 100, default 20), `-w`, `--json` |
|
|
56
|
+
| `sinatra stop <task-id>` | `-w` |
|
|
57
|
+
| `sinatra whoami` | `--json` |
|
|
58
|
+
| `sinatra workspace [<id>]` | none |
|
|
59
|
+
| `sinatra logout` | none |
|
|
60
|
+
| `sinatra --version`, `-v` / `sinatra --help`, `-h` | none |
|
|
61
|
+
|
|
62
|
+
An option a command doesn't use is an error, not silently ignored.
|
|
63
|
+
|
|
64
|
+
- **Repository:** inside a git checkout, the task runs on its GitHub repository: the `origin`
|
|
65
|
+
remote, then `upstream`; another GitHub remote counts only when neither is on GitHub. SSH host
|
|
66
|
+
aliases from `~/.ssh/config` (like `git@github-work:owner/repo.git`) count when they point at
|
|
67
|
+
github.com. If `origin`'s repository isn't connected to your workspace, the CLI says so and tries
|
|
68
|
+
`upstream`'s (so a fork falls through to the repository it forks); when none is connected,
|
|
69
|
+
Sinatra's agent picks one. The CLI
|
|
70
|
+
prints which remote it used. `-r owner/name` picks a repository explicitly, and is never
|
|
71
|
+
second-guessed.
|
|
72
|
+
- **Attachments:** `-f` attaches text files to a new task or a reply, up to 80KB together. Binary
|
|
73
|
+
files are refused.
|
|
74
|
+
- **Following:** after `start` or `reply`, the CLI prints what Sinatra posts until the turn is
|
|
75
|
+
done: Sinatra replied, or the task finished, failed, was cancelled, or paused. While the task waits
|
|
76
|
+
for a free slot in your workspace's plan, it says so. It stops waiting after `--timeout` minutes
|
|
77
|
+
(30 by default); the task keeps going. Ctrl-C stops waiting too. After a `reply` to a task that
|
|
78
|
+
had already stopped, if Sinatra hasn't picked the message up within two minutes, the CLI says so
|
|
79
|
+
(exit 3) instead of reporting the previous turn's result.
|
|
80
|
+
- **Prompts that start with `-`:** put them after `--`: `sinatra -- "-v is broken"`. A title that
|
|
81
|
+
starts with `-` takes the `=` form: `--title="-x title"`.
|
|
82
|
+
- **Workspace:** commands use the default workspace from login. `sinatra workspace <id>` changes it
|
|
83
|
+
without logging in again; `-w <id>` overrides it for one command.
|
|
84
|
+
- **JSON:** `--json` prints the API's objects and nothing else, for scripts: `whoami`, `tasks`,
|
|
85
|
+
`show`, and `start` or `reply` with `--no-wait`.
|
|
86
|
+
- **Prompts vs commands:** a prompt that starts with a command word still starts a task, unless it
|
|
87
|
+
has exactly that command's shape. `sinatra start "..."` always starts one.
|
|
88
|
+
- **Logout:** `sinatra logout` revokes the token on Sinatra, then deletes the local file. If Sinatra
|
|
89
|
+
can't be reached, the file is still deleted and the CLI warns that the token may still be active:
|
|
90
|
+
revoke it on the Access tokens page.
|
|
91
|
+
- **Retries:** every request that changes something carries an idempotency key, so a retry after a
|
|
92
|
+
dropped connection never starts a second task or sends a message twice.
|
|
93
|
+
|
|
94
|
+
## Exit codes
|
|
95
|
+
|
|
96
|
+
| Code | Meaning |
|
|
97
|
+
| --- | --- |
|
|
98
|
+
| 0 | Done: the turn finished, or the command succeeded |
|
|
99
|
+
| 1 | Error: bad usage, not logged in, or Sinatra refused the request |
|
|
100
|
+
| 2 | The task failed, was cancelled, or is paused (billing or access) |
|
|
101
|
+
| 3 | Still working when the CLI stopped waiting (`--timeout`), or your reply wasn't picked up yet |
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The task API (`/v1`) as the CLI uses it. A request that changes something carries an
|
|
3
|
+
* Idempotency-Key, so a retry after a dropped connection or a 503 never starts a second task or
|
|
4
|
+
* sends a message twice.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
export class ApiError extends Error {
|
|
8
|
+
status;
|
|
9
|
+
code;
|
|
10
|
+
detail;
|
|
11
|
+
constructor(status, code, detail = {}) {
|
|
12
|
+
super(`${code} (HTTP ${status})`);
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.code = code;
|
|
15
|
+
this.detail = detail;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const RETRIES = 3;
|
|
19
|
+
const RETRY_DELAY_MS = 1_000;
|
|
20
|
+
export function createClient(options) {
|
|
21
|
+
const fetchFn = options.fetch ?? globalThis.fetch;
|
|
22
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
23
|
+
const base = options.apiUrl.replace(/\/+$/, "");
|
|
24
|
+
const attempts = options.attempts ?? RETRIES;
|
|
25
|
+
async function request(method, path, body) {
|
|
26
|
+
// One key for every attempt of this call: the server answers a retry with the first result.
|
|
27
|
+
// Each call gets its own, so a second call (another repository, say) is a new request.
|
|
28
|
+
const key = method === "GET" ? undefined : randomUUID();
|
|
29
|
+
for (let attempt = 1;; attempt++) {
|
|
30
|
+
let response;
|
|
31
|
+
try {
|
|
32
|
+
response = await fetchFn(`${base}${path}`, {
|
|
33
|
+
method,
|
|
34
|
+
headers: {
|
|
35
|
+
authorization: `Bearer ${options.token}`,
|
|
36
|
+
accept: "application/json",
|
|
37
|
+
...(body !== undefined ? { "content-type": "application/json" } : {}),
|
|
38
|
+
...(key ? { "idempotency-key": key } : {}),
|
|
39
|
+
},
|
|
40
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
41
|
+
...(options.timeoutMs ? { signal: AbortSignal.timeout(options.timeoutMs) } : {}),
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (attempt < attempts) {
|
|
46
|
+
await sleep(RETRY_DELAY_MS * attempt);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
const payload = response.status === 204 ? {} : await response.json().catch(() => ({}));
|
|
52
|
+
if (response.ok)
|
|
53
|
+
return payload;
|
|
54
|
+
if (response.status >= 500 && attempt < attempts) {
|
|
55
|
+
await sleep(RETRY_DELAY_MS * attempt);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const { error, ...detail } = payload;
|
|
59
|
+
throw new ApiError(response.status, error ?? "request_failed", detail);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
me: () => request("GET", "/v1/me"),
|
|
64
|
+
/** Revokes the token this client authenticates with. */
|
|
65
|
+
revokeToken: () => request("DELETE", "/v1/me/token"),
|
|
66
|
+
listTasks: (workspaceId, query = {}) => {
|
|
67
|
+
const params = new URLSearchParams();
|
|
68
|
+
if (query.status)
|
|
69
|
+
params.set("status", query.status);
|
|
70
|
+
if (query.limit)
|
|
71
|
+
params.set("limit", String(query.limit));
|
|
72
|
+
const qs = params.toString();
|
|
73
|
+
return request("GET", `/v1/workspaces/${workspaceId}/tasks${qs ? `?${qs}` : ""}`);
|
|
74
|
+
},
|
|
75
|
+
getTask: (workspaceId, taskId) => request("GET", `/v1/workspaces/${workspaceId}/tasks/${taskId}`),
|
|
76
|
+
startTask: (workspaceId, body) => request("POST", `/v1/workspaces/${workspaceId}/tasks`, body),
|
|
77
|
+
followUp: (workspaceId, taskId, text) => request("POST", `/v1/workspaces/${workspaceId}/tasks/${taskId}/messages`, { text }),
|
|
78
|
+
messages: (workspaceId, taskId, after) => request("GET", `/v1/workspaces/${workspaceId}/tasks/${taskId}/messages${after ? `?after=${encodeURIComponent(after)}` : ""}`),
|
|
79
|
+
stopTask: (workspaceId, taskId) => request("POST", `/v1/workspaces/${workspaceId}/tasks/${taskId}/stop`),
|
|
80
|
+
};
|
|
81
|
+
}
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/** The CLI's decisions that don't touch the terminal: what was asked for, and what to send. */
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { ApiError, createClient } from "./client.js";
|
|
4
|
+
import { ConfigError, DEFAULT_API_URL, DEFAULT_APP_URL } from "./config.js";
|
|
5
|
+
import { DEFAULT_FOLLOW_TIMEOUT_MS } from "./follow.js";
|
|
6
|
+
/** A mistake in how the CLI was called, or anything else to say before exiting with 1. */
|
|
7
|
+
export class UsageError extends Error {
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A task id as the API hands them out (cuids, `api…` ids, and hand-made ids with dashes):
|
|
11
|
+
* never a word of a prompt, which is shorter.
|
|
12
|
+
*/
|
|
13
|
+
const TASK_ID = /^[a-z0-9][a-z0-9_-]{19,63}$/;
|
|
14
|
+
/**
|
|
15
|
+
* What the arguments ask for. A command word counts only in the shape that command takes, so
|
|
16
|
+
* `sinatra stop retrying on 429` or `sinatra logout the user on expiry` start tasks instead of
|
|
17
|
+
* stopping one or logging you out; `sinatra start ...` always starts one. A command word with
|
|
18
|
+
* at most one word after it is a mistyped command, never a task: starting one would spend the
|
|
19
|
+
* person's allowance on `sinatra stop <a bad id>`.
|
|
20
|
+
*/
|
|
21
|
+
export function parseCommand(positionals) {
|
|
22
|
+
const [first, ...rest] = positionals;
|
|
23
|
+
if (!first)
|
|
24
|
+
return { name: "help" };
|
|
25
|
+
const usage = (message) => ({ name: "usage", message });
|
|
26
|
+
// More than a word after the command word (`stop retrying on 429`, `show "me why it fails"`).
|
|
27
|
+
const prose = rest.length >= 2 || (rest.length === 1 && /\s/.test(rest[0]));
|
|
28
|
+
switch (first) {
|
|
29
|
+
case "start":
|
|
30
|
+
return rest.length > 0 ? { name: "start", prompt: rest.join(" ").trim() } : usage('Usage: sinatra start "<what to do>"');
|
|
31
|
+
case "help":
|
|
32
|
+
case "version":
|
|
33
|
+
if (rest.length === 0)
|
|
34
|
+
return { name: first };
|
|
35
|
+
break;
|
|
36
|
+
case "login":
|
|
37
|
+
case "logout":
|
|
38
|
+
case "whoami":
|
|
39
|
+
case "tasks":
|
|
40
|
+
if (rest.length === 0)
|
|
41
|
+
return { name: first };
|
|
42
|
+
if (!prose)
|
|
43
|
+
return usage(`Usage: sinatra ${first}`);
|
|
44
|
+
break;
|
|
45
|
+
case "workspace":
|
|
46
|
+
if (rest.length === 0)
|
|
47
|
+
return { name: "workspace" };
|
|
48
|
+
if (!prose)
|
|
49
|
+
return { name: "workspace", workspaceId: rest[0] };
|
|
50
|
+
break;
|
|
51
|
+
case "show":
|
|
52
|
+
case "stop":
|
|
53
|
+
if (rest.length === 1 && TASK_ID.test(rest[0]))
|
|
54
|
+
return { name: first, taskId: rest[0] };
|
|
55
|
+
// A task id and more (`stop <id> <id>`, `show <id> please`) is a mistyped command too.
|
|
56
|
+
if (!prose || TASK_ID.test(rest[0]))
|
|
57
|
+
return usage(`Usage: sinatra ${first} <task-id> (task ids look like those in \`sinatra tasks\`)`);
|
|
58
|
+
break;
|
|
59
|
+
case "reply":
|
|
60
|
+
if (rest.length >= 2 && TASK_ID.test(rest[0]))
|
|
61
|
+
return { name: "reply", taskId: rest[0], text: rest.slice(1).join(" ").trim() };
|
|
62
|
+
if (!prose || TASK_ID.test(rest[0]))
|
|
63
|
+
return usage('Usage: sinatra reply <task-id> "<message>"');
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
return { name: "start", prompt: positionals.join(" ").trim() };
|
|
67
|
+
}
|
|
68
|
+
const OPTIONS = {
|
|
69
|
+
repo: { type: "string", short: "r" },
|
|
70
|
+
file: { type: "string", short: "f", multiple: true },
|
|
71
|
+
title: { type: "string", short: "t" },
|
|
72
|
+
workspace: { type: "string", short: "w" },
|
|
73
|
+
"no-wait": { type: "boolean" },
|
|
74
|
+
timeout: { type: "string" },
|
|
75
|
+
json: { type: "boolean" },
|
|
76
|
+
status: { type: "string" },
|
|
77
|
+
limit: { type: "string", short: "n" },
|
|
78
|
+
"api-url": { type: "string" },
|
|
79
|
+
version: { type: "boolean", short: "v" },
|
|
80
|
+
help: { type: "boolean", short: "h" },
|
|
81
|
+
};
|
|
82
|
+
/** The commands each option means something to; given to any other, it's a mistake. */
|
|
83
|
+
const APPLIES_TO = {
|
|
84
|
+
repo: ["start"],
|
|
85
|
+
file: ["start", "reply"],
|
|
86
|
+
title: ["start"],
|
|
87
|
+
workspace: ["start", "reply", "show", "tasks", "stop", "login"],
|
|
88
|
+
"no-wait": ["start", "reply"],
|
|
89
|
+
timeout: ["start", "reply"],
|
|
90
|
+
json: ["whoami", "tasks", "show", "start", "reply"],
|
|
91
|
+
status: ["tasks"],
|
|
92
|
+
limit: ["tasks"],
|
|
93
|
+
"api-url": ["login"],
|
|
94
|
+
};
|
|
95
|
+
/** The command line, read and checked; anything it can't run is a UsageError. */
|
|
96
|
+
export function parseInvocation(argv) {
|
|
97
|
+
const { values, positionals } = (() => {
|
|
98
|
+
try {
|
|
99
|
+
return parseArgs({ args: argv, allowPositionals: true, options: OPTIONS });
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
throw new UsageError(`${argumentProblem(error, argv)}\nRun \`sinatra --help\` for usage.`);
|
|
103
|
+
}
|
|
104
|
+
})();
|
|
105
|
+
const given = Object.keys(values).filter((key) => key !== "help" && key !== "version");
|
|
106
|
+
const command = values.help ? { name: "help" } : values.version ? { name: "version" } : parseCommand(positionals);
|
|
107
|
+
if (command.name === "usage")
|
|
108
|
+
throw new UsageError(command.message);
|
|
109
|
+
if (command.name === "help" && positionals.length === 0 && given.length > 0 && !values.help) {
|
|
110
|
+
// `sinatra -f notes.md` without saying what to do: never a task, and not a silent help screen.
|
|
111
|
+
// (`sinatra "-the thing"` lands here too: `-t` took the rest as its value.)
|
|
112
|
+
const prose = promptLike(argv);
|
|
113
|
+
if (prose)
|
|
114
|
+
throw new UsageError(dashPromptHint(prose));
|
|
115
|
+
throw new UsageError('What should Sinatra do? Usage: sinatra "<what to do>" [options] (see `sinatra --help`).');
|
|
116
|
+
}
|
|
117
|
+
if (command.name !== "help" && command.name !== "version") {
|
|
118
|
+
for (const key of given) {
|
|
119
|
+
const applies = APPLIES_TO[key];
|
|
120
|
+
if (applies && !applies.includes(command.name)) {
|
|
121
|
+
const shown = command.name === "start" ? 'sinatra "<what to do>"' : `sinatra ${command.name}`;
|
|
122
|
+
throw new UsageError(`--${key} doesn't apply to \`${shown}\`. Run \`sinatra --help\` for usage.`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const wait = !values["no-wait"];
|
|
127
|
+
if (values.json && (command.name === "start" || command.name === "reply") && wait) {
|
|
128
|
+
throw new UsageError("--json with start or reply needs --no-wait: following prints the conversation as it comes.");
|
|
129
|
+
}
|
|
130
|
+
let limit;
|
|
131
|
+
if (values.limit !== undefined) {
|
|
132
|
+
limit = Number(values.limit);
|
|
133
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
134
|
+
throw new UsageError("--limit takes a whole number from 1 to 100.");
|
|
135
|
+
}
|
|
136
|
+
let timeoutMs = DEFAULT_FOLLOW_TIMEOUT_MS;
|
|
137
|
+
if (values.timeout !== undefined) {
|
|
138
|
+
const minutes = Number(values.timeout);
|
|
139
|
+
if (!values.timeout.trim() || !Number.isFinite(minutes) || minutes <= 0)
|
|
140
|
+
throw new UsageError("--timeout takes a number of minutes, more than 0.");
|
|
141
|
+
timeoutMs = minutes * 60_000;
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
command,
|
|
145
|
+
files: values.file ?? [],
|
|
146
|
+
wait,
|
|
147
|
+
timeoutMs,
|
|
148
|
+
json: values.json ?? false,
|
|
149
|
+
...(values.repo !== undefined ? { repo: values.repo } : {}),
|
|
150
|
+
...(values.title !== undefined ? { title: values.title } : {}),
|
|
151
|
+
...(values.workspace !== undefined ? { workspace: values.workspace } : {}),
|
|
152
|
+
...(values.status !== undefined ? { status: values.status } : {}),
|
|
153
|
+
...(limit !== undefined ? { limit } : {}),
|
|
154
|
+
...(values["api-url"] !== undefined ? { apiUrl: values["api-url"] } : {}),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* An argument that starts with `-` but holds whitespace, before any `--`: a prompt, not options
|
|
159
|
+
* (`sinatra "-v is broken"`).
|
|
160
|
+
*/
|
|
161
|
+
function promptLike(argv) {
|
|
162
|
+
const end = argv.indexOf("--");
|
|
163
|
+
return (end === -1 ? argv : argv.slice(0, end)).find((arg) => /^-[^-]/.test(arg) && /\s/.test(arg));
|
|
164
|
+
}
|
|
165
|
+
function dashPromptHint(prompt) {
|
|
166
|
+
return `"${prompt}" reads as options. Put a prompt that starts with - after --: sinatra -- "${prompt}"`;
|
|
167
|
+
}
|
|
168
|
+
/** Node's parseArgs errors, said plainly. */
|
|
169
|
+
function argumentProblem(error, argv) {
|
|
170
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
171
|
+
const code = error.code;
|
|
172
|
+
const flag = /'([^']+)'/.exec(message)?.[1];
|
|
173
|
+
if (code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" && flag) {
|
|
174
|
+
const prose = promptLike(argv);
|
|
175
|
+
return prose ? dashPromptHint(prose) : `Unknown option ${flag}.`;
|
|
176
|
+
}
|
|
177
|
+
if (code === "ERR_PARSE_ARGS_INVALID_OPTION_VALUE" && flag) {
|
|
178
|
+
if (/argument missing/.test(message))
|
|
179
|
+
return `${flag.replace(/ <value>$/, "")} needs a value.`;
|
|
180
|
+
if (/ambiguous/.test(message)) {
|
|
181
|
+
// The value starts with `-`: say it the one way that can't be read as another option.
|
|
182
|
+
const long = flag.startsWith("--")
|
|
183
|
+
? flag.slice(2)
|
|
184
|
+
: Object.entries(OPTIONS).find(([, option]) => "short" in option && `-${option.short}` === flag)?.[0];
|
|
185
|
+
const value = argv[argv.indexOf(flag) + 1] ?? "-...";
|
|
186
|
+
return long
|
|
187
|
+
? `The value after ${flag} starts with -, so it reads as an option. Write it as --${long}="${value}".`
|
|
188
|
+
: `The value after ${flag} starts with -, so it reads as an option.`;
|
|
189
|
+
}
|
|
190
|
+
return `${flag} doesn't take a value.`;
|
|
191
|
+
}
|
|
192
|
+
return message;
|
|
193
|
+
}
|
|
194
|
+
export function repoChoices(named, detected) {
|
|
195
|
+
return named ? [{ name: named, explicit: true }] : detected.map(({ repo, remote }) => ({ name: repo, explicit: false, remote }));
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Starts the task on the first repository the workspace accepts, and says which that was. One
|
|
199
|
+
* the person named is never second-guessed: its refusal is the answer. Detected ones are tried in
|
|
200
|
+
* order (a fork's `origin`, then the `upstream` it came from), and when none is connected the
|
|
201
|
+
* agent picks, which is said first. Every attempt is its own request with its own idempotency
|
|
202
|
+
* key: the server refuses an unconnected repository before creating anything.
|
|
203
|
+
*/
|
|
204
|
+
export async function startTask(client, workspaceId, body, repos, notice) {
|
|
205
|
+
const label = (repo) => (repo.explicit ? repo.name : `${repo.name} (this checkout's ${repo.remote} remote)`);
|
|
206
|
+
for (const [i, repo] of repos.entries()) {
|
|
207
|
+
try {
|
|
208
|
+
return { started: await client.startTask(workspaceId, { ...body, repo: repo.name }), repo };
|
|
209
|
+
}
|
|
210
|
+
catch (error) {
|
|
211
|
+
if (repo.explicit || !(error instanceof ApiError && error.code === "invalid_repo"))
|
|
212
|
+
throw error;
|
|
213
|
+
const next = repos[i + 1];
|
|
214
|
+
notice(next
|
|
215
|
+
? `${label(repo)} isn't connected to this workspace; trying ${label(next)}.`
|
|
216
|
+
: `${label(repo)} isn't connected to this workspace, so Sinatra will pick a repository. ` +
|
|
217
|
+
"To use it, connect it on the dashboard's Repositories page; or pass -r owner/name.");
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return { started: await client.startTask(workspaceId, body), repo: null };
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* `sinatra login`: read a token, check it, pick the default workspace, save. A `--workspace`
|
|
224
|
+
* that isn't one of the token's workspaces is refused before anything is saved, so a script's
|
|
225
|
+
* typo leaves the previous login as it was.
|
|
226
|
+
*/
|
|
227
|
+
export async function login(deps) {
|
|
228
|
+
const { out } = deps;
|
|
229
|
+
// The sign-in page sends a signed-in visitor straight on, and a signed-out one there after signing in.
|
|
230
|
+
out(deps.apiUrl === DEFAULT_API_URL
|
|
231
|
+
? `Create a personal access token at ${DEFAULT_APP_URL}/login?returnTo=%2Ftokens, then paste it here.\n`
|
|
232
|
+
: "Create a personal access token on your Sinatra dashboard's Access tokens page, then paste it here.\n");
|
|
233
|
+
const token = await deps.askSecret("Token (hidden): ");
|
|
234
|
+
if (!token)
|
|
235
|
+
throw new UsageError("No token given.");
|
|
236
|
+
const me = await deps.me(token);
|
|
237
|
+
const workspaceId = await loginWorkspace(me.workspaces, deps);
|
|
238
|
+
await deps.save({ apiUrl: deps.apiUrl, token, ...(workspaceId ? { workspaceId } : {}) });
|
|
239
|
+
const name = me.user.githubLogin ? `@${me.user.githubLogin}` : me.user.name ?? me.user.id;
|
|
240
|
+
const workspace = me.workspaces.find((w) => w.id === workspaceId)?.name;
|
|
241
|
+
out(printable(`Logged in as ${name}${workspace ? `, workspace ${workspace}` : ""}.\n`));
|
|
242
|
+
}
|
|
243
|
+
/** The default workspace to save at login, if any. */
|
|
244
|
+
async function loginWorkspace(workspaces, deps) {
|
|
245
|
+
const { out } = deps;
|
|
246
|
+
if (deps.workspace !== undefined) {
|
|
247
|
+
const chosen = workspaces.find((w) => w.id === deps.workspace);
|
|
248
|
+
if (chosen)
|
|
249
|
+
return chosen.id;
|
|
250
|
+
const yours = workspaces.map((w) => `${w.name} (${w.id})`).join(", ");
|
|
251
|
+
throw new UsageError(printable(`${deps.workspace} isn't one of this token's workspaces${yours ? ` (${yours})` : ""}. Nothing was saved.`));
|
|
252
|
+
}
|
|
253
|
+
if (workspaces.length === 1)
|
|
254
|
+
return workspaces[0].id;
|
|
255
|
+
if (workspaces.length === 0)
|
|
256
|
+
return undefined;
|
|
257
|
+
if (!deps.interactive) {
|
|
258
|
+
// Piped stdin has nothing left after the token: asking would only read end-of-input.
|
|
259
|
+
out("No default workspace saved: you belong to more than one. Set one with `sinatra workspace <id>`, or log in with --workspace <id>.\n");
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
workspaces.forEach((w, i) => out(printable(` ${i + 1}. ${w.name} (${w.id})\n`)));
|
|
263
|
+
for (let tries = 0; tries < 3; tries++) {
|
|
264
|
+
const id = workspaces[Number(await deps.ask("Default workspace number: ")) - 1]?.id;
|
|
265
|
+
if (id)
|
|
266
|
+
return id;
|
|
267
|
+
}
|
|
268
|
+
out("No default workspace saved; pass -w <id> to commands, or set one with `sinatra workspace <id>`.\n");
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
/** Where to make (or revoke) a token, for the API a config points at. */
|
|
272
|
+
export function tokensPage(apiUrl) {
|
|
273
|
+
return apiUrl === DEFAULT_API_URL ? `${DEFAULT_APP_URL}/tokens` : "your Sinatra dashboard's Access tokens page";
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Revoking the saved token at logout: one attempt, bounded, so an unreachable server can't hold
|
|
277
|
+
* up forgetting it here (a retry would only add to the wait).
|
|
278
|
+
*/
|
|
279
|
+
export function revokeSavedToken(config, fetch) {
|
|
280
|
+
return createClient({ ...config, timeoutMs: 10_000, attempts: 1, ...(fetch ? { fetch } : {}) }).revokeToken();
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Logging out: revoke the saved token on the server, then forget it here whatever happened. A
|
|
284
|
+
* token the server already rejects is as good as revoked; any other failure leaves it possibly
|
|
285
|
+
* still working, which the person is told along with where to revoke it.
|
|
286
|
+
*/
|
|
287
|
+
export async function logout(deps) {
|
|
288
|
+
let config;
|
|
289
|
+
try {
|
|
290
|
+
config = await deps.read();
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
if (!(error instanceof ConfigError))
|
|
294
|
+
throw error;
|
|
295
|
+
await deps.forget();
|
|
296
|
+
return {
|
|
297
|
+
message: "Removed the damaged config.",
|
|
298
|
+
warning: `If it held a token, revoke it on ${tokensPage(DEFAULT_API_URL)} (or your dashboard's Access tokens page).`,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
if (!config) {
|
|
302
|
+
await deps.forget();
|
|
303
|
+
return { message: "Not logged in." };
|
|
304
|
+
}
|
|
305
|
+
let problem = null;
|
|
306
|
+
try {
|
|
307
|
+
await deps.revoke(config);
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
if (!(error instanceof ApiError && error.status === 401)) {
|
|
311
|
+
const cause = error instanceof Error && error.cause instanceof Error ? `: ${error.cause.message}` : "";
|
|
312
|
+
problem = error instanceof ApiError ? `HTTP ${error.status}` : `${error instanceof Error ? error.message : String(error)}${cause}`;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
await deps.forget();
|
|
316
|
+
if (problem === null)
|
|
317
|
+
return { message: "Logged out; the token is revoked." };
|
|
318
|
+
return {
|
|
319
|
+
message: "Logged out on this machine.",
|
|
320
|
+
warning: `Couldn't revoke the token (${problem}), so it may still be active. Revoke it on ${tokensPage(config.apiUrl)}.`,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/** Text from the agent, teammates or notices, safe to print: no terminal control sequences. */
|
|
324
|
+
export function printable(text) {
|
|
325
|
+
// Every C0 control but tab and newline, DEL, C1 controls (escape sequences start with these),
|
|
326
|
+
// and bidirectional overrides, which can make printed text read differently than it is.
|
|
327
|
+
return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g, "");
|
|
328
|
+
}
|
|
329
|
+
/** The running-task cap when the server doesn't say. */
|
|
330
|
+
const DEFAULT_RUNNING_CAP = "5";
|
|
331
|
+
export function classifyRefusal(error, context = {}) {
|
|
332
|
+
switch (error.code) {
|
|
333
|
+
case "invalid_token":
|
|
334
|
+
return { kind: context.during === "login" ? "token_rejected_at_login" : "token_invalid" };
|
|
335
|
+
case "not_found":
|
|
336
|
+
return { kind: context.during ? "task_api_off" : "not_found" };
|
|
337
|
+
case "too_many_running": {
|
|
338
|
+
const raw = error.detail.limit;
|
|
339
|
+
const limit = (typeof raw === "string" || typeof raw === "number") && /^\d+$/.test(String(raw)) ? String(raw) : DEFAULT_RUNNING_CAP;
|
|
340
|
+
return { kind: "too_many_running", limit };
|
|
341
|
+
}
|
|
342
|
+
case "unavailable":
|
|
343
|
+
if (typeof error.detail.taskId === "string")
|
|
344
|
+
return { kind: "created_not_started", taskId: error.detail.taskId };
|
|
345
|
+
if (typeof error.detail.messageId === "string")
|
|
346
|
+
return { kind: "message_saved_not_sent" };
|
|
347
|
+
return { kind: "unreachable" };
|
|
348
|
+
default:
|
|
349
|
+
return { kind: "code", code: error.code };
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/** What to tell a person about a refusal: the next step, not just the code. */
|
|
353
|
+
export function explain(error, context = {}) {
|
|
354
|
+
const refusal = classifyRefusal(error, context);
|
|
355
|
+
switch (refusal.kind) {
|
|
356
|
+
case "token_rejected_at_login":
|
|
357
|
+
return `Sinatra didn't accept that token: it may be mistyped, expired or revoked. Create one on ${tokensPage(context.apiUrl ?? DEFAULT_API_URL)}, then paste it again.`;
|
|
358
|
+
case "token_invalid": return "Your token is invalid or expired: run `sinatra login`.";
|
|
359
|
+
case "task_api_off":
|
|
360
|
+
return "The task API isn't available for this account. Write to contact@sinatra.dev if you think it should be.";
|
|
361
|
+
case "not_found": return "No such task or workspace, or you're not a member of it.";
|
|
362
|
+
case "too_many_running": return `You already have ${refusal.limit} CLI, MCP or API tasks starting, running or queued in this workspace; wait for one to finish its turn.`;
|
|
363
|
+
case "created_not_started":
|
|
364
|
+
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).`;
|
|
365
|
+
case "message_saved_not_sent":
|
|
366
|
+
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.";
|
|
367
|
+
case "unreachable": return "Sinatra couldn't be reached; try again shortly.";
|
|
368
|
+
}
|
|
369
|
+
switch (refusal.code) {
|
|
370
|
+
case "invalid_prompt": return "The message is empty or too long.";
|
|
371
|
+
case "invalid_repo": return "That repository isn't connected to this workspace (see the dashboard's Repositories page).";
|
|
372
|
+
case "invalid_status": return "That isn't a task status (some are: pending, implementing, replied, pr_open, completed, failed).";
|
|
373
|
+
case "invalid_limit": return "--limit takes a whole number from 1 to 100.";
|
|
374
|
+
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.";
|
|
375
|
+
case "not_running": return "That task isn't running.";
|
|
376
|
+
case "idempotency_conflict": return "That request conflicts with an earlier one; try again.";
|
|
377
|
+
default: return `Sinatra refused: ${error.code} (HTTP ${error.status}).`;
|
|
378
|
+
}
|
|
379
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the CLI keeps its token: one JSON file, readable only by you (0600), in the XDG config
|
|
3
|
+
* directory (`%APPDATA%\sinatra` on Windows). The token is never printed back.
|
|
4
|
+
*/
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { chmod, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { dirname, join, win32 } from "node:path";
|
|
9
|
+
export const DEFAULT_API_URL = "https://api.sinatra.dev";
|
|
10
|
+
export const DEFAULT_APP_URL = "https://app.sinatra.dev";
|
|
11
|
+
export function configPath(env = process.env, platform = process.platform) {
|
|
12
|
+
if (platform === "win32") {
|
|
13
|
+
return win32.join(env.APPDATA || win32.join(homedir(), "AppData", "Roaming"), "sinatra", "config.json");
|
|
14
|
+
}
|
|
15
|
+
const base = env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
16
|
+
return join(base, "sinatra", "config.json");
|
|
17
|
+
}
|
|
18
|
+
/** The config file is there but can't be used: unreadable, or not what the CLI wrote. */
|
|
19
|
+
export class ConfigError extends Error {
|
|
20
|
+
}
|
|
21
|
+
export async function readConfig(path = configPath()) {
|
|
22
|
+
let raw;
|
|
23
|
+
try {
|
|
24
|
+
raw = await readFile(path, "utf8");
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
const code = error.code;
|
|
28
|
+
if (code === "ENOENT")
|
|
29
|
+
return null;
|
|
30
|
+
throw new ConfigError(`Can't read ${path} (${code ?? "unknown error"}). Run \`sinatra login\` to save your token again.`);
|
|
31
|
+
}
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(raw);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
parsed = undefined;
|
|
38
|
+
}
|
|
39
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
40
|
+
throw new ConfigError(`${path} is damaged. Run \`sinatra login\` to save your token again.`);
|
|
41
|
+
}
|
|
42
|
+
const config = parsed;
|
|
43
|
+
if (typeof config.token !== "string" || typeof config.apiUrl !== "string")
|
|
44
|
+
return null;
|
|
45
|
+
return {
|
|
46
|
+
apiUrl: config.apiUrl,
|
|
47
|
+
token: config.token,
|
|
48
|
+
...(typeof config.workspaceId === "string" ? { workspaceId: config.workspaceId } : {}),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export async function writeConfig(config, path = configPath()) {
|
|
52
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
53
|
+
// A fresh 0600 file renamed into place: the token is never in a file anyone else can read,
|
|
54
|
+
// even when an older config had looser permissions.
|
|
55
|
+
// An unguessable name created exclusively, so nothing else can be at that path first.
|
|
56
|
+
const temp = `${path}.${randomBytes(8).toString("hex")}.tmp`;
|
|
57
|
+
try {
|
|
58
|
+
await writeFile(temp, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600, flag: "wx" });
|
|
59
|
+
await chmod(temp, 0o600);
|
|
60
|
+
await rename(temp, path);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
await rm(temp, { force: true });
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export async function deleteConfig(path = configPath()) {
|
|
68
|
+
await rm(path, { force: true });
|
|
69
|
+
}
|