@cloop/runner 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # @cloop/runner
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `cloop` CLI: device login, a stdio MCP server (Cloop Skills), and a Claude Code hook that heartbeat your agents into the Cloop mesh. Harness- and domain-agnostic — Claude Code, Cowork, and Codex all get presence via the MCP server; Claude Code hooks add session-lifecycle detail.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g @cloop/runner
9
+ cloop login # approve the device in your browser
10
+ cloop install # register the MCP server with Claude Code / others
11
+ ```
12
+
13
+ Credentials live in `~/.cloop/credentials.json`. The API origin comes from `CLOOP_ORIGIN`, the stored value, or the staging default.
14
+
15
+ ## Commands
16
+
17
+ | Command | What it does |
18
+ | --- | --- |
19
+ | `cloop login [--name <device>]` | Device-code flow → long-lived token |
20
+ | `cloop install` | `claude mcp add cloop -- cloop serve` + Cowork/Codex instructions |
21
+ | `cloop serve [--platform <p>]` | Run the stdio MCP server (heartbeats presence) |
22
+ | `cloop hook session-start` | Claude Code SessionStart hook — **not registered in Phase 1** |
23
+
24
+ ### Presence model (Phase 1)
25
+
26
+ The MCP server (`cloop serve`) is the sole presence source: one `agent_sessions` row per live server process. Its `session_key` is `CLAUDE_SESSION_ID` when the harness provides it, otherwise a per-process UUID. `name` is the harness label ("Claude Code" / "Codex" / "Cowork"); `machine` is the hostname; login `deviceName` is separate (`cli_devices.name`).
27
+
28
+ `cloop hook session-start` exists in the tree but `cloop install` does **not** wire it up — Claude Code hooks are the Phase 2 coding adapter (richer session lifecycle detail). Leaving it unregistered keeps Phase 1 at one row per MCP process.
29
+
30
+ ## MCP tools
31
+
32
+ The server exposes one built-in tool plus every tool advertised by the shared
33
+ app-side registry — it fetches `GET {origin}/api/agent/mesh/tools` at startup and
34
+ registers each dynamically, proxying calls through `POST {origin}/api/agent/mesh/tools`
35
+ `{tool, input}`. New skills land with no CLI release.
36
+
37
+ - `cloop_status {}` — built-in: who's live on your mesh, on what surface (served
38
+ locally from `/api/agent/mesh/status`, not the registry)
39
+ - `cloop_inbox {action?}` — built-in: `drain` (default) returns and clears the
40
+ delegated tasks / DMs pushed to this agent over the mesh; `list` peeks
41
+ - registry tools — e.g. `search`, `list_tasks`, `get_task`, `get_task_context`,
42
+ `get_contact`, `list_cloops`, `get_cloop`
43
+
44
+ If the registry is unreachable at startup, the server runs status-only (warns once
45
+ on stderr). A `401` from any proxied call returns an `isError` result asking the
46
+ user to run `cloop login`.
47
+
48
+ ## Live presence mesh (`cloop serve`)
49
+
50
+ On start, `serve` opens a WebSocket to the cloop-mesh Worker's per-user Durable
51
+ Object at `{CLOOP_MESH_URL}/mesh/agent?session_key=…` (default
52
+ `https://mcp-staging.mycloop.com`; override via `CLOOP_MESH_URL` or the stored
53
+ `meshUrl`). The device token rides the first `Sec-WebSocket-Protocol` entry, never
54
+ the URL (query strings leak into edge logs). While it's up, presence
55
+ beats ride the socket (the DO mirrors them into the heartbeat route) and the HTTP
56
+ `HeartbeatClient` is the fallback; it reconnects with 1s→60s backoff + jitter.
57
+ Incoming `delegate` / `dm` frames are appended to `~/.cloop/inbox.jsonl` and the
58
+ statusline shows a `✉ N` pending badge; `cloop_inbox` drains them.
59
+
60
+ ## Develop
61
+
62
+ ```bash
63
+ npm install
64
+ npm run build
65
+ npm test
66
+ ```
@@ -0,0 +1,246 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ MeshSocket,
4
+ defaultSocketFactory
5
+ } from "./chunk-ZILLDYL4.js";
6
+ import {
7
+ getMachine
8
+ } from "./chunk-HS5CIDQF.js";
9
+ import {
10
+ BoxWatch,
11
+ LocalDriver,
12
+ T3Client,
13
+ T3Driver,
14
+ claudeDialect,
15
+ codexDialect,
16
+ connectCommand,
17
+ isLocal,
18
+ lockThreadsFile,
19
+ mintSession,
20
+ probeClaude,
21
+ probeCodex,
22
+ readRunnerConfig,
23
+ resolveT3Bin,
24
+ runBoxTool,
25
+ threadsFilePath,
26
+ writeBoxConfig,
27
+ writeRunnerState
28
+ } from "./chunk-IIUHGZKX.js";
29
+ import "./chunk-CMOMRXTA.js";
30
+ import "./chunk-7K5W6ELQ.js";
31
+ import "./chunk-4UE33DYW.js";
32
+ import {
33
+ getMeshUrl,
34
+ getToken,
35
+ readCredentials
36
+ } from "./chunk-SQJ7ZO4G.js";
37
+
38
+ // src/commands/box.ts
39
+ var BEAT_MS = 6e4;
40
+ var RESEND_MS = 5 * 6e4;
41
+ var REPAIR_BEFORE_MS = 2 * 24 * 36e5;
42
+ var out = (line) => console.log(line);
43
+ var red = (s) => `\x1B[31m${s}\x1B[0m`;
44
+ var log = (line) => console.error(`[workstation:daemon] ${line}`);
45
+ var REVOKED_CLOSE = 4001;
46
+ var REFUSED_LINE = "refused: Cloop no longer accepts this runner. It was disconnected, or its login expired. Run `cloop connect` on it to connect it again.";
47
+ async function awaitNewDeviceToken(current, read, { tries = 3, delayMs = 2e3 } = {}) {
48
+ for (let i = 0; i < tries; i++) {
49
+ const next = read();
50
+ if (next && next !== current) return next;
51
+ if (i < tries - 1) await new Promise((r) => setTimeout(r, delayMs));
52
+ }
53
+ return null;
54
+ }
55
+ async function machineHarnesses(cfg) {
56
+ const [claude, codex] = await Promise.all([
57
+ probeClaude(cfg.driver === "claude-code" ? cfg.bin : void 0),
58
+ probeCodex(cfg.driver === "codex" ? cfg.bin : void 0)
59
+ ]);
60
+ return [claude, codex].filter((h) => h !== null);
61
+ }
62
+ function localDriver(cfg, name) {
63
+ const bin = cfg.driver === name ? cfg.bin : void 0;
64
+ return new LocalDriver({
65
+ dialect: name === "claude-code" ? claudeDialect(bin) : codexDialect(bin),
66
+ repos: cfg.repos,
67
+ label: cfg.label,
68
+ harnesses: () => machineHarnesses(cfg),
69
+ log
70
+ });
71
+ }
72
+ function recordConnected(logLine, write = writeRunnerState) {
73
+ try {
74
+ write({ pid: process.pid, connected_at: (/* @__PURE__ */ new Date()).toISOString() });
75
+ } catch (err) {
76
+ logLine(`state write failed: ${err.code ?? "unknown"}`);
77
+ }
78
+ }
79
+ async function run() {
80
+ let cfg = readRunnerConfig();
81
+ let token = cfg?.deviceToken ?? getToken();
82
+ if (!token || !cfg) {
83
+ out(`${red("\u2717")} Not connected. Run \`cloop connect\` first.`);
84
+ process.exit(1);
85
+ }
86
+ if (!cfg.deviceToken) {
87
+ log("no runner device on this machine; run `cloop connect` so the Agent can reach it");
88
+ }
89
+ const name = process.env.CLOOP_DRIVER ?? cfg.driver ?? "t3";
90
+ const local = isLocal(cfg) ? cfg : null;
91
+ if (name === "t3" === Boolean(local)) {
92
+ out(
93
+ `${red("\u2717")} This machine is not connected for ${name}. Run \`cloop connect --driver ${name}\` first.`
94
+ );
95
+ process.exit(1);
96
+ }
97
+ const t3 = { client: isLocal(cfg) ? null : new T3Client(cfg.t3Url, cfg.token) };
98
+ const machine = getMachine();
99
+ const sessionKey = `box:${machine}`;
100
+ const factory = await defaultSocketFactory();
101
+ const lock = lockThreadsFile(threadsFilePath());
102
+ if (!lock.ok) {
103
+ out(`${red("\u2717")} Another \`cloop box run\` is running (pid ${lock.heldBy}). Stop it first.`);
104
+ process.exit(1);
105
+ }
106
+ const driver = local && name !== "t3" ? localDriver(local, name) : new T3Driver({
107
+ client: () => t3.client,
108
+ t3Bin: isLocal(cfg) ? null : cfg.t3Bin,
109
+ scope: () => cfg && !isLocal(cfg) ? cfg.scope : void 0,
110
+ log,
111
+ watched: ({ work_id, thread_id }) => {
112
+ const e = watch.list().find((x) => work_id ? x.work_id === work_id : x.thread_id === thread_id);
113
+ return e && { thread_id: e.thread_id, settled: Boolean(e.settled_at) };
114
+ }
115
+ });
116
+ const watch = new BoxWatch({
117
+ file: threadsFilePath(),
118
+ watch: (id, onEvent) => driver.watch(id, onEvent),
119
+ send: (frame) => socket.send({ ...frame }),
120
+ log
121
+ });
122
+ const onCall = async (frame) => {
123
+ const started = Date.now();
124
+ const result = await runBoxTool(
125
+ { driver, onLaunch: (workId, threadId) => watch.add(workId, threadId) },
126
+ frame.tool,
127
+ frame.args
128
+ );
129
+ socket.send({ type: "result", id: frame.id, ...result });
130
+ log(
131
+ `call tool=${frame.tool} ok=${result.ok} ms=${Date.now() - started}${result.ok ? "" : ` error=${result.error} detail=${result.detail.slice(0, 300)}`}`
132
+ );
133
+ };
134
+ const socket = new MeshSocket({
135
+ meshUrl: getMeshUrl(),
136
+ token,
137
+ sessionKey,
138
+ kind: "workstation",
139
+ factory,
140
+ onMessage: () => {
141
+ },
142
+ onCall: (frame) => void onCall(frame),
143
+ onAck: (of, ok) => watch.ack(of, ok),
144
+ onOpen: () => {
145
+ log(`connected to ${getMeshUrl()}`);
146
+ recordConnected(log);
147
+ watch.flush();
148
+ },
149
+ onClose: (code) => log(
150
+ code === REVOKED_CLOSE ? "disconnected by Cloop (revoked), checking" : "disconnected, reconnecting"
151
+ ),
152
+ onRefused: () => void (async () => {
153
+ const fresh = await awaitNewDeviceToken(token ?? "", () => readRunnerConfig()?.deviceToken);
154
+ const next = fresh ? readRunnerConfig() : null;
155
+ if (fresh && next) {
156
+ log("reconnecting with the device token `cloop connect` just wrote");
157
+ token = fresh;
158
+ cfg = next;
159
+ if (!isLocal(next)) t3.client = new T3Client(next.t3Url, next.token);
160
+ socket.restart(fresh);
161
+ return;
162
+ }
163
+ log(REFUSED_LINE);
164
+ stop(1);
165
+ })()
166
+ });
167
+ socket.start();
168
+ log(
169
+ `connecting to ${getMeshUrl()} as ${sessionKey} (${readCredentials()?.deviceName ?? machine}) driver=${driver.name}`
170
+ );
171
+ watch.start();
172
+ setInterval(() => watch.flush(), RESEND_MS).unref();
173
+ const renewT3 = async () => {
174
+ if (!cfg || isLocal(cfg) || Date.parse(cfg.expiresAt) - Date.now() >= REPAIR_BEFORE_MS) return;
175
+ try {
176
+ const disk = readRunnerConfig();
177
+ const renewed = {
178
+ ...await mintSession(cfg.t3Url, resolveT3Bin() ?? cfg.t3Bin),
179
+ // Read from disk: `cloop connect` may have replaced it since.
180
+ deviceToken: disk?.deviceToken ?? cfg.deviceToken
181
+ };
182
+ cfg = renewed;
183
+ writeBoxConfig(renewed);
184
+ t3.client = new T3Client(renewed.t3Url, renewed.token);
185
+ log(`T3 session renewed until ${renewed.expiresAt}`);
186
+ } catch (err) {
187
+ log(`T3 session renewal failed: ${err instanceof Error ? err.message : String(err)}`);
188
+ }
189
+ };
190
+ const beat = async () => {
191
+ await renewT3();
192
+ let running = 0;
193
+ try {
194
+ running = (await driver.listThreads({ scope: "unsettled", limit: 1 })).running;
195
+ } catch (err) {
196
+ log(`${driver.name} unreachable: ${err instanceof Error ? err.message : String(err)}`);
197
+ }
198
+ socket.sendPresence({
199
+ session_key: sessionKey,
200
+ name: driver.name === "t3" ? "Cloop box" : "Cloop runner",
201
+ kind: "workstation",
202
+ capabilities: [...driver.capabilities],
203
+ platform: "workstation",
204
+ machine,
205
+ surface: {},
206
+ status: running > 0 ? "active" : "idle",
207
+ event: running > 0 ? `${running} running` : ""
208
+ });
209
+ };
210
+ void beat();
211
+ setInterval(() => void beat(), BEAT_MS);
212
+ const stop = (code = 0) => {
213
+ log("stopping");
214
+ watch.stop();
215
+ if (driver instanceof LocalDriver) driver.stop();
216
+ lock.release();
217
+ socket.close();
218
+ process.exit(code);
219
+ };
220
+ process.on("SIGINT", () => stop());
221
+ process.on("SIGTERM", () => stop());
222
+ await new Promise(() => {
223
+ });
224
+ }
225
+ async function boxCommand(argv) {
226
+ switch (argv[0]) {
227
+ case "connect":
228
+ await connectCommand(["--driver", "t3", ...argv.slice(1)]);
229
+ break;
230
+ case "run":
231
+ await run();
232
+ break;
233
+ default:
234
+ console.error(
235
+ "Usage: cloop box connect [--t3-url <url>] [--t3-bin <path>] [--no-service] | cloop box run"
236
+ );
237
+ process.exit(1);
238
+ }
239
+ }
240
+ export {
241
+ REFUSED_LINE,
242
+ awaitNewDeviceToken,
243
+ boxCommand,
244
+ recordConnected,
245
+ run
246
+ };
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/sanitize.ts
4
+ function stripControl(text) {
5
+ let out = "";
6
+ for (const ch of text) {
7
+ const code = ch.codePointAt(0) ?? 0;
8
+ const isControl = code <= 31 || code >= 127 && code <= 159;
9
+ if (!isControl || ch === "\n" || ch === " ") out += ch;
10
+ }
11
+ return out;
12
+ }
13
+ var MAX_ITEM_CHARS = 4e3;
14
+ function sanitizeUntrusted(text, max = MAX_ITEM_CHARS) {
15
+ const stripped = stripControl(text);
16
+ return stripped.length > max ? `${stripped.slice(0, max)}\u2026 [truncated]` : stripped;
17
+ }
18
+ function sanitizeLabel(text, max = 48) {
19
+ const flat = stripControl(text).replace(/\s+/g, " ").trim();
20
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
21
+ }
22
+
23
+ export {
24
+ sanitizeUntrusted,
25
+ sanitizeLabel
26
+ };
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getOrigin,
4
+ getToken
5
+ } from "./chunk-SQJ7ZO4G.js";
6
+
7
+ // src/api.ts
8
+ var REAUTH_MESSAGE = "Cloop session expired or unauthenticated. Run `cloop login`.";
9
+ var ReauthError = class extends Error {
10
+ constructor(message = REAUTH_MESSAGE) {
11
+ super(message);
12
+ this.name = "ReauthError";
13
+ }
14
+ };
15
+ var ApiError = class extends Error {
16
+ constructor(status, message, body = "") {
17
+ super(message);
18
+ this.status = status;
19
+ this.body = body;
20
+ this.name = "ApiError";
21
+ }
22
+ status;
23
+ body;
24
+ };
25
+ function buildUrl(origin, path, query) {
26
+ const url = new URL(path, `${origin}/`);
27
+ if (query) {
28
+ for (const [key, value] of Object.entries(query)) {
29
+ if (value !== void 0) url.searchParams.set(key, value);
30
+ }
31
+ }
32
+ return url.toString();
33
+ }
34
+ async function api(path, opts = {}) {
35
+ const {
36
+ method = "GET",
37
+ body,
38
+ query,
39
+ auth = true,
40
+ fetchFn = fetch,
41
+ origin = getOrigin(),
42
+ timeoutMs
43
+ } = opts;
44
+ const headers = { accept: "application/json" };
45
+ if (auth) {
46
+ const token = getToken();
47
+ if (!token) throw new ReauthError();
48
+ headers.authorization = `Bearer ${token}`;
49
+ }
50
+ if (body !== void 0) headers["content-type"] = "application/json";
51
+ const url = buildUrl(origin, path, query);
52
+ const init = {
53
+ method,
54
+ headers,
55
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
56
+ };
57
+ const attempt = () => fetchFn(url, timeoutMs ? { ...init, signal: AbortSignal.timeout(timeoutMs) } : init);
58
+ let res;
59
+ try {
60
+ res = await attempt();
61
+ } catch (err) {
62
+ try {
63
+ res = await attempt();
64
+ } catch {
65
+ const detail = err instanceof Error ? err.message : String(err);
66
+ throw new ApiError(0, `Network error reaching ${url}: ${detail}`);
67
+ }
68
+ }
69
+ if (res.status === 401) throw new ReauthError();
70
+ if (!res.ok) {
71
+ const text2 = await res.text().catch(() => "");
72
+ throw new ApiError(
73
+ res.status,
74
+ `Cloop API ${res.status} for ${path}: ${text2.slice(0, 300)}`,
75
+ text2
76
+ );
77
+ }
78
+ if (res.status === 204) return void 0;
79
+ const text = await res.text();
80
+ if (!text) return void 0;
81
+ return JSON.parse(text);
82
+ }
83
+
84
+ export {
85
+ ReauthError,
86
+ ApiError,
87
+ api
88
+ };
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/version.ts
4
+ var VERSION = true ? "0.2.0" : "0.0.0-dev";
5
+
6
+ export {
7
+ VERSION
8
+ };
@@ -0,0 +1,161 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ApiError,
4
+ api
5
+ } from "./chunk-4UE33DYW.js";
6
+ import {
7
+ getOrigin,
8
+ readCredentials,
9
+ writeCredentials
10
+ } from "./chunk-SQJ7ZO4G.js";
11
+
12
+ // src/commands/login.ts
13
+ import { execFile } from "child_process";
14
+ import { hostname } from "os";
15
+ var POLL_INTERVAL_MS = 3e3;
16
+ var POLL_TIMEOUT_MS = 5 * 60 * 1e3;
17
+ var BOUND_ELSEWHERE = "This box is connected to another Cloop account. Disconnect it there first.";
18
+ var dim = (s) => `\x1B[2m${s}\x1B[22m`;
19
+ var green = (s) => `\x1B[32m${s}\x1B[39m`;
20
+ var red = (s) => `\x1B[31m${s}\x1B[39m`;
21
+ var blue = (s) => `\x1B[34m${s}\x1B[39m`;
22
+ var underline = (s) => `\x1B[4m${s}\x1B[24m`;
23
+ var mark = `${blue("o")}${green("0")}`;
24
+ var out = (s) => process.stdout.write(`${s}
25
+ `);
26
+ function formatCode(code) {
27
+ if (code.length < 6) return code;
28
+ const mid = Math.ceil(code.length / 2);
29
+ return `${code.slice(0, mid)}-${code.slice(mid)}`;
30
+ }
31
+ function spinner(text) {
32
+ if (!process.stdout.isTTY) {
33
+ out(text);
34
+ return {
35
+ stop: (finalLine) => {
36
+ if (finalLine) out(finalLine);
37
+ }
38
+ };
39
+ }
40
+ const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
41
+ let i = 0;
42
+ process.stdout.write("\x1B[?25l");
43
+ const render = () => process.stdout.write(`\r\x1B[2K${dim(frames[i++ % frames.length] ?? "")} ${text}`);
44
+ render();
45
+ const timer = setInterval(render, 90);
46
+ return {
47
+ stop: (finalLine) => {
48
+ clearInterval(timer);
49
+ process.stdout.write("\r\x1B[2K\x1B[?25h");
50
+ if (finalLine) out(finalLine);
51
+ }
52
+ };
53
+ }
54
+ function openUrl(url) {
55
+ let parsed;
56
+ try {
57
+ parsed = new URL(url);
58
+ } catch {
59
+ return;
60
+ }
61
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
62
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
63
+ const args = process.platform === "win32" ? ["/c", "start", "", parsed.href] : [parsed.href];
64
+ execFile(cmd, args, () => {
65
+ });
66
+ }
67
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
68
+ async function loginCommand(argv = process.argv.slice(2)) {
69
+ const origin = getOrigin();
70
+ const deviceName = parseDeviceName(argv) ?? hostname();
71
+ const existing = readCredentials();
72
+ const token = await deviceLogin({ origin, deviceName });
73
+ const chosen = process.env.CLOOP_ORIGIN ? origin : existing?.origin ?? origin;
74
+ const creds = { origin: chosen, token, deviceName };
75
+ writeCredentials(creds);
76
+ if (!existing?.token) out(dim(" Run `cloop install` to register the MCP server."));
77
+ }
78
+ async function deviceLogin(opts) {
79
+ const { origin, deviceName, device } = opts;
80
+ let start;
81
+ try {
82
+ start = await api("/api/agent/mesh/link", {
83
+ method: "POST",
84
+ auth: false,
85
+ origin,
86
+ body: {
87
+ action: "start",
88
+ device_name: deviceName,
89
+ ...device ? {
90
+ kind: device.kind,
91
+ environment_id: device.environmentId,
92
+ t3_label: device.label,
93
+ t3_version: device.version
94
+ } : {}
95
+ }
96
+ });
97
+ } catch (err) {
98
+ out(`${red("\u2717")} Could not start login: ${err instanceof Error ? err.message : String(err)}`);
99
+ process.exit(1);
100
+ }
101
+ const code = formatCode(start.code);
102
+ out(`${mark} Approve ${deviceName} in your browser. Code ${code}.`);
103
+ out(` ${dim(underline(start.approve_url))}`);
104
+ openUrl(start.approve_url);
105
+ const wait = spinner("Waiting for approval");
106
+ const deadline = Date.now() + POLL_TIMEOUT_MS;
107
+ let token;
108
+ while (Date.now() < deadline) {
109
+ await sleep(POLL_INTERVAL_MS);
110
+ let poll;
111
+ try {
112
+ poll = await api("/api/agent/mesh/link", {
113
+ method: "POST",
114
+ auth: false,
115
+ origin,
116
+ body: { action: "poll", code: start.code, poll_token: start.poll_token }
117
+ });
118
+ } catch (err) {
119
+ if (err instanceof ApiError && err.status === 410) {
120
+ wait.stop(`${red("\u2717")} Code expired. Run \`cloop login\` again.`);
121
+ process.exit(1);
122
+ }
123
+ if (err instanceof ApiError && err.status === 409) {
124
+ wait.stop(`${red("\u2717")} ${refusalSentence(err.body)}`);
125
+ process.exit(1);
126
+ }
127
+ continue;
128
+ }
129
+ if (poll.token) {
130
+ token = poll.token;
131
+ break;
132
+ }
133
+ }
134
+ if (!token) {
135
+ wait.stop(`${red("\u2717")} No approval within 5 minutes. Run \`cloop login\` again.`);
136
+ process.exit(1);
137
+ }
138
+ wait.stop(`${mark} Linked as ${deviceName}.`);
139
+ return token;
140
+ }
141
+ function refusalSentence(body) {
142
+ try {
143
+ const message = JSON.parse(body).message;
144
+ if (typeof message === "string" && message) return message;
145
+ } catch {
146
+ }
147
+ return BOUND_ELSEWHERE;
148
+ }
149
+ function parseDeviceName(argv) {
150
+ const flag = argv.find((a) => a.startsWith("--name="));
151
+ if (flag) return flag.slice("--name=".length);
152
+ const idx = argv.indexOf("--name");
153
+ if (idx >= 0) return argv[idx + 1];
154
+ return void 0;
155
+ }
156
+
157
+ export {
158
+ loginCommand,
159
+ deviceLogin,
160
+ refusalSentence
161
+ };