@cloop/runner 0.0.0-stage → 0.2.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 +65 -2
- package/dist/box-HBQ4ZM2Y.js +247 -0
- package/dist/chunk-2ZVYM4JU.js +2755 -0
- package/dist/chunk-3DIGCVL4.js +70 -0
- package/dist/chunk-4LFQXBWP.js +26 -0
- package/dist/chunk-AG6SI6I2.js +88 -0
- package/dist/chunk-AQGBNKUG.js +239 -0
- package/dist/chunk-J6AEO3GT.js +97 -0
- package/dist/chunk-JX6VG5FE.js +150 -0
- package/dist/chunk-OJ5AREUC.js +131 -0
- package/dist/chunk-OKF4BDBH.js +8 -0
- package/dist/chunk-ZILLDYL4.js +150 -0
- package/dist/connect-LRQ4C3KK.js +66 -0
- package/dist/disconnect-FQ6ODTTE.js +143 -0
- package/dist/hook-activity-O2NNKTOE.js +91 -0
- package/dist/hook-session-start-MT67MMDM.js +153 -0
- package/dist/index.js +111 -0
- package/dist/install-HTDTCELB.js +100 -0
- package/dist/login-4GUYT5MR.js +14 -0
- package/dist/mcp-server-TV7MHVHZ.js +399 -0
- package/dist/runner-5H7ECAZ6.js +147 -0
- package/dist/statusline-6JMHIL54.js +177 -0
- package/package.json +57 -5
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/config.ts
|
|
4
|
+
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
5
|
+
import { homedir } from "os";
|
|
6
|
+
import { join } from "path";
|
|
7
|
+
var CONFIG_DIR = ".cloop";
|
|
8
|
+
var CREDENTIALS_FILE = "credentials.json";
|
|
9
|
+
var PRODUCTION_ORIGIN = "https://mcp.mycloop.com";
|
|
10
|
+
var STAGING_ORIGIN = "https://mcp-staging.mycloop.com";
|
|
11
|
+
var DEFAULT_ORIGIN = PRODUCTION_ORIGIN;
|
|
12
|
+
var DEFAULT_MESH_URL = PRODUCTION_ORIGIN;
|
|
13
|
+
function applyEnvironmentFlag(argv) {
|
|
14
|
+
if (!argv.includes("--staging")) return argv;
|
|
15
|
+
process.env.CLOOP_ORIGIN ??= STAGING_ORIGIN;
|
|
16
|
+
process.env.CLOOP_MESH_URL ??= process.env.CLOOP_ORIGIN;
|
|
17
|
+
return argv.filter((arg) => arg !== "--staging");
|
|
18
|
+
}
|
|
19
|
+
function configDir() {
|
|
20
|
+
return join(homedir(), CONFIG_DIR);
|
|
21
|
+
}
|
|
22
|
+
function credentialsPath() {
|
|
23
|
+
return join(configDir(), CREDENTIALS_FILE);
|
|
24
|
+
}
|
|
25
|
+
function readCredentials() {
|
|
26
|
+
try {
|
|
27
|
+
const raw = readFileSync(credentialsPath(), "utf-8");
|
|
28
|
+
const parsed = JSON.parse(raw);
|
|
29
|
+
if (typeof parsed.origin !== "string") return null;
|
|
30
|
+
return {
|
|
31
|
+
origin: parsed.origin,
|
|
32
|
+
...typeof parsed.token === "string" ? { token: parsed.token } : {},
|
|
33
|
+
...typeof parsed.deviceName === "string" ? { deviceName: parsed.deviceName } : {},
|
|
34
|
+
...typeof parsed.meshUrl === "string" ? { meshUrl: parsed.meshUrl } : {}
|
|
35
|
+
};
|
|
36
|
+
} catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function writeCredentials(creds) {
|
|
41
|
+
const dir = configDir();
|
|
42
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
43
|
+
const path = credentialsPath();
|
|
44
|
+
writeFileSync(path, `${JSON.stringify(creds, null, 2)}
|
|
45
|
+
`, { mode: 384 });
|
|
46
|
+
chmodSync(path, 384);
|
|
47
|
+
}
|
|
48
|
+
function getOrigin() {
|
|
49
|
+
const raw = process.env.CLOOP_ORIGIN ?? readCredentials()?.origin ?? DEFAULT_ORIGIN;
|
|
50
|
+
return raw.replace(/\/+$/, "");
|
|
51
|
+
}
|
|
52
|
+
function getToken() {
|
|
53
|
+
return readCredentials()?.token ?? process.env.CLOOP_TOKEN ?? void 0;
|
|
54
|
+
}
|
|
55
|
+
function getMeshUrl() {
|
|
56
|
+
const stored = readCredentials();
|
|
57
|
+
const raw = process.env.CLOOP_MESH_URL ?? stored?.meshUrl ?? stored?.origin ?? DEFAULT_MESH_URL;
|
|
58
|
+
return raw.replace(/\/+$/, "");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export {
|
|
62
|
+
CONFIG_DIR,
|
|
63
|
+
STAGING_ORIGIN,
|
|
64
|
+
applyEnvironmentFlag,
|
|
65
|
+
readCredentials,
|
|
66
|
+
writeCredentials,
|
|
67
|
+
getOrigin,
|
|
68
|
+
getToken,
|
|
69
|
+
getMeshUrl
|
|
70
|
+
};
|
|
@@ -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-3DIGCVL4.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,239 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
ApiError,
|
|
4
|
+
api
|
|
5
|
+
} from "./chunk-AG6SI6I2.js";
|
|
6
|
+
import {
|
|
7
|
+
VERSION
|
|
8
|
+
} from "./chunk-OKF4BDBH.js";
|
|
9
|
+
import {
|
|
10
|
+
getOrigin,
|
|
11
|
+
readCredentials,
|
|
12
|
+
writeCredentials
|
|
13
|
+
} from "./chunk-3DIGCVL4.js";
|
|
14
|
+
|
|
15
|
+
// src/commands/login.ts
|
|
16
|
+
import { execFile } from "child_process";
|
|
17
|
+
import { hostname } from "os";
|
|
18
|
+
|
|
19
|
+
// src/connect-report.ts
|
|
20
|
+
import { randomUUID } from "crypto";
|
|
21
|
+
var ConnectFailure = class extends Error {
|
|
22
|
+
constructor(code, message, shown = false) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.shown = shown;
|
|
26
|
+
this.name = "ConnectFailure";
|
|
27
|
+
}
|
|
28
|
+
code;
|
|
29
|
+
shown;
|
|
30
|
+
};
|
|
31
|
+
function newAttempt(now = Date.now()) {
|
|
32
|
+
return {
|
|
33
|
+
id: randomUUID(),
|
|
34
|
+
startedAt: now,
|
|
35
|
+
step: "detect",
|
|
36
|
+
harnesses: [],
|
|
37
|
+
driver: null,
|
|
38
|
+
fellBack: false,
|
|
39
|
+
deviceToken: null
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function shortMachineLabel(machine) {
|
|
43
|
+
return machine.split(".")[0]?.replace(/[^A-Za-z0-9-]/g, "-").slice(0, 63) || "unknown";
|
|
44
|
+
}
|
|
45
|
+
function connectReport(attempt, error, machine, now = Date.now()) {
|
|
46
|
+
return {
|
|
47
|
+
attempt_id: attempt.id,
|
|
48
|
+
cli_version: VERSION,
|
|
49
|
+
os: process.platform,
|
|
50
|
+
arch: process.arch,
|
|
51
|
+
node_version: process.version,
|
|
52
|
+
machine: shortMachineLabel(machine),
|
|
53
|
+
harnesses: attempt.harnesses,
|
|
54
|
+
driver: attempt.driver,
|
|
55
|
+
fell_back: attempt.fellBack,
|
|
56
|
+
step: attempt.step,
|
|
57
|
+
outcome: error ? "failed" : "ok",
|
|
58
|
+
error_code: error,
|
|
59
|
+
seconds: Math.round((now - attempt.startedAt) / 1e3)
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
async function sendConnectReport(origin, report, deviceToken, fetchFn = fetch) {
|
|
63
|
+
try {
|
|
64
|
+
await fetchFn(`${origin}/api/agent/mesh/connect-report`, {
|
|
65
|
+
method: "POST",
|
|
66
|
+
headers: {
|
|
67
|
+
"content-type": "application/json",
|
|
68
|
+
...deviceToken ? { authorization: `Bearer ${deviceToken}` } : {}
|
|
69
|
+
},
|
|
70
|
+
body: JSON.stringify(report),
|
|
71
|
+
signal: AbortSignal.timeout(3e3)
|
|
72
|
+
});
|
|
73
|
+
} catch {
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// src/commands/login.ts
|
|
78
|
+
var POLL_INTERVAL_MS = 3e3;
|
|
79
|
+
var POLL_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
80
|
+
var BOUND_ELSEWHERE = "This box is connected to another Cloop account. Disconnect it there first.";
|
|
81
|
+
var dim = (s) => `\x1B[2m${s}\x1B[22m`;
|
|
82
|
+
var green = (s) => `\x1B[32m${s}\x1B[39m`;
|
|
83
|
+
var red = (s) => `\x1B[31m${s}\x1B[39m`;
|
|
84
|
+
var blue = (s) => `\x1B[34m${s}\x1B[39m`;
|
|
85
|
+
var underline = (s) => `\x1B[4m${s}\x1B[24m`;
|
|
86
|
+
var mark = `${blue("o")}${green("0")}`;
|
|
87
|
+
var out = (s) => process.stdout.write(`${s}
|
|
88
|
+
`);
|
|
89
|
+
function formatCode(code) {
|
|
90
|
+
if (code.length < 6) return code;
|
|
91
|
+
const mid = Math.ceil(code.length / 2);
|
|
92
|
+
return `${code.slice(0, mid)}-${code.slice(mid)}`;
|
|
93
|
+
}
|
|
94
|
+
function spinner(text) {
|
|
95
|
+
if (!process.stdout.isTTY) {
|
|
96
|
+
out(text);
|
|
97
|
+
return {
|
|
98
|
+
stop: (finalLine) => {
|
|
99
|
+
if (finalLine) out(finalLine);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
104
|
+
let i = 0;
|
|
105
|
+
process.stdout.write("\x1B[?25l");
|
|
106
|
+
const render = () => process.stdout.write(`\r\x1B[2K${dim(frames[i++ % frames.length] ?? "")} ${text}`);
|
|
107
|
+
render();
|
|
108
|
+
const timer = setInterval(render, 90);
|
|
109
|
+
return {
|
|
110
|
+
stop: (finalLine) => {
|
|
111
|
+
clearInterval(timer);
|
|
112
|
+
process.stdout.write("\r\x1B[2K\x1B[?25h");
|
|
113
|
+
if (finalLine) out(finalLine);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function openUrl(url) {
|
|
118
|
+
let parsed;
|
|
119
|
+
try {
|
|
120
|
+
parsed = new URL(url);
|
|
121
|
+
} catch {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return;
|
|
125
|
+
const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
|
|
126
|
+
const args = process.platform === "win32" ? ["/c", "start", "", parsed.href] : [parsed.href];
|
|
127
|
+
execFile(cmd, args, () => {
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
131
|
+
async function loginCommand(argv = process.argv.slice(2)) {
|
|
132
|
+
const origin = getOrigin();
|
|
133
|
+
const deviceName = parseDeviceName(argv) ?? hostname();
|
|
134
|
+
const existing = readCredentials();
|
|
135
|
+
let token;
|
|
136
|
+
try {
|
|
137
|
+
token = await deviceLogin({ origin, deviceName });
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if (!(err instanceof ConnectFailure)) throw err;
|
|
140
|
+
out(`${red("\u2717")} ${err.message}`);
|
|
141
|
+
process.exit(1);
|
|
142
|
+
}
|
|
143
|
+
const chosen = process.env.CLOOP_ORIGIN ? origin : existing?.origin ?? origin;
|
|
144
|
+
const creds = { origin: chosen, token, deviceName };
|
|
145
|
+
writeCredentials(creds);
|
|
146
|
+
if (!existing?.token) out(dim(" Run `cloop install` to register the MCP server."));
|
|
147
|
+
}
|
|
148
|
+
async function deviceLogin(opts) {
|
|
149
|
+
const { origin, deviceName, device } = opts;
|
|
150
|
+
let start;
|
|
151
|
+
try {
|
|
152
|
+
start = await api("/api/agent/mesh/link", {
|
|
153
|
+
method: "POST",
|
|
154
|
+
auth: false,
|
|
155
|
+
origin,
|
|
156
|
+
body: {
|
|
157
|
+
action: "start",
|
|
158
|
+
device_name: deviceName,
|
|
159
|
+
...device ? {
|
|
160
|
+
kind: device.kind,
|
|
161
|
+
environment_id: device.environmentId,
|
|
162
|
+
t3_label: device.label,
|
|
163
|
+
t3_version: device.version
|
|
164
|
+
} : {}
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
} catch (err) {
|
|
168
|
+
throw new ConnectFailure(
|
|
169
|
+
"login_failed",
|
|
170
|
+
`Could not start login: ${err instanceof Error ? err.message : String(err)}`
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
const code = formatCode(start.code);
|
|
174
|
+
out(`${mark} Approve ${deviceName} in your browser. Code ${code}.`);
|
|
175
|
+
out(` ${dim(underline(start.approve_url))}`);
|
|
176
|
+
openUrl(start.approve_url);
|
|
177
|
+
const wait = spinner("Waiting for approval");
|
|
178
|
+
const deadline = Date.now() + POLL_TIMEOUT_MS;
|
|
179
|
+
let token;
|
|
180
|
+
while (Date.now() < deadline) {
|
|
181
|
+
await sleep(POLL_INTERVAL_MS);
|
|
182
|
+
let poll;
|
|
183
|
+
try {
|
|
184
|
+
poll = await api("/api/agent/mesh/link", {
|
|
185
|
+
method: "POST",
|
|
186
|
+
auth: false,
|
|
187
|
+
origin,
|
|
188
|
+
body: { action: "poll", code: start.code, poll_token: start.poll_token }
|
|
189
|
+
});
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (err instanceof ApiError && (err.status === 410 || err.status === 409)) {
|
|
192
|
+
wait.stop();
|
|
193
|
+
throw new ConnectFailure(
|
|
194
|
+
"login_failed",
|
|
195
|
+
err.status === 410 ? "Code expired. Run the command again." : refusalSentence(err.body)
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (poll.token) {
|
|
201
|
+
token = poll.token;
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (!token) {
|
|
206
|
+
wait.stop();
|
|
207
|
+
throw new ConnectFailure(
|
|
208
|
+
"login_failed",
|
|
209
|
+
"No approval within 5 minutes. Run the command again."
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
wait.stop(`${mark} Linked as ${deviceName}.`);
|
|
213
|
+
return token;
|
|
214
|
+
}
|
|
215
|
+
function refusalSentence(body) {
|
|
216
|
+
try {
|
|
217
|
+
const message = JSON.parse(body).message;
|
|
218
|
+
if (typeof message === "string" && message) return message;
|
|
219
|
+
} catch {
|
|
220
|
+
}
|
|
221
|
+
return BOUND_ELSEWHERE;
|
|
222
|
+
}
|
|
223
|
+
function parseDeviceName(argv) {
|
|
224
|
+
const flag = argv.find((a) => a.startsWith("--name="));
|
|
225
|
+
if (flag) return flag.slice("--name=".length);
|
|
226
|
+
const idx = argv.indexOf("--name");
|
|
227
|
+
if (idx >= 0) return argv[idx + 1];
|
|
228
|
+
return void 0;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export {
|
|
232
|
+
ConnectFailure,
|
|
233
|
+
newAttempt,
|
|
234
|
+
connectReport,
|
|
235
|
+
sendConnectReport,
|
|
236
|
+
loginCommand,
|
|
237
|
+
deviceLogin,
|
|
238
|
+
refusalSentence
|
|
239
|
+
};
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
CONFIG_DIR
|
|
4
|
+
} from "./chunk-3DIGCVL4.js";
|
|
5
|
+
|
|
6
|
+
// src/inbox.ts
|
|
7
|
+
import { appendFileSync, mkdirSync, readFileSync, rmSync } from "fs";
|
|
8
|
+
import { homedir } from "os";
|
|
9
|
+
import { dirname, join } from "path";
|
|
10
|
+
var INBOX_FILE = "inbox.jsonl";
|
|
11
|
+
function inboxPath() {
|
|
12
|
+
return process.env.CLOOP_INBOX_PATH ?? join(homedir(), CONFIG_DIR, INBOX_FILE);
|
|
13
|
+
}
|
|
14
|
+
function appendInbox(item) {
|
|
15
|
+
const path = inboxPath();
|
|
16
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
17
|
+
appendFileSync(path, `${JSON.stringify(item)}
|
|
18
|
+
`, { mode: 384 });
|
|
19
|
+
}
|
|
20
|
+
function readInbox() {
|
|
21
|
+
let raw;
|
|
22
|
+
try {
|
|
23
|
+
raw = readFileSync(inboxPath(), "utf-8");
|
|
24
|
+
} catch {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
const items = [];
|
|
28
|
+
for (const line of raw.split("\n")) {
|
|
29
|
+
const trimmed = line.trim();
|
|
30
|
+
if (!trimmed) continue;
|
|
31
|
+
try {
|
|
32
|
+
items.push(JSON.parse(trimmed));
|
|
33
|
+
} catch {
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return items;
|
|
37
|
+
}
|
|
38
|
+
function inboxCount() {
|
|
39
|
+
return readInbox().length;
|
|
40
|
+
}
|
|
41
|
+
function drainInbox() {
|
|
42
|
+
const items = readInbox();
|
|
43
|
+
try {
|
|
44
|
+
rmSync(inboxPath(), { force: true });
|
|
45
|
+
} catch {
|
|
46
|
+
}
|
|
47
|
+
return items;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/state.ts
|
|
51
|
+
import { chmodSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync } from "fs";
|
|
52
|
+
import { homedir as homedir2 } from "os";
|
|
53
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
54
|
+
var STATE_FILE = "state.json";
|
|
55
|
+
function statePath() {
|
|
56
|
+
return process.env.CLOOP_STATE_PATH ?? join2(homedir2(), CONFIG_DIR, STATE_FILE);
|
|
57
|
+
}
|
|
58
|
+
function readState() {
|
|
59
|
+
try {
|
|
60
|
+
const raw = readFileSync2(statePath(), "utf-8");
|
|
61
|
+
const parsed = JSON.parse(raw);
|
|
62
|
+
if (typeof parsed.updatedAt !== "string" || !Array.isArray(parsed.sessions)) return null;
|
|
63
|
+
return {
|
|
64
|
+
updatedAt: parsed.updatedAt,
|
|
65
|
+
sessions: parsed.sessions,
|
|
66
|
+
...typeof parsed.inboxPending === "number" ? { inboxPending: parsed.inboxPending } : {},
|
|
67
|
+
...typeof parsed.machine === "string" ? { machine: parsed.machine } : {}
|
|
68
|
+
};
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function writeState(state) {
|
|
74
|
+
const path = statePath();
|
|
75
|
+
mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
|
|
76
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
77
|
+
writeFileSync(tmp, `${JSON.stringify(state, null, 2)}
|
|
78
|
+
`, { mode: 384 });
|
|
79
|
+
renameSync(tmp, path);
|
|
80
|
+
try {
|
|
81
|
+
chmodSync(path, 384);
|
|
82
|
+
} catch {
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function syncInboxPending() {
|
|
86
|
+
const current = readState() ?? { updatedAt: (/* @__PURE__ */ new Date()).toISOString(), sessions: [] };
|
|
87
|
+
writeState({ ...current, inboxPending: inboxCount() });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export {
|
|
91
|
+
appendInbox,
|
|
92
|
+
readInbox,
|
|
93
|
+
drainInbox,
|
|
94
|
+
readState,
|
|
95
|
+
writeState,
|
|
96
|
+
syncInboxPending
|
|
97
|
+
};
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
api
|
|
4
|
+
} from "./chunk-AG6SI6I2.js";
|
|
5
|
+
|
|
6
|
+
// src/presence.ts
|
|
7
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
8
|
+
import { randomUUID } from "crypto";
|
|
9
|
+
import { hostname, platform as osPlatform } from "os";
|
|
10
|
+
|
|
11
|
+
// src/git.ts
|
|
12
|
+
import { execFileSync } from "child_process";
|
|
13
|
+
import { basename } from "path";
|
|
14
|
+
var GIT_OPTS = {
|
|
15
|
+
encoding: "utf-8",
|
|
16
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
17
|
+
timeout: 2e3
|
|
18
|
+
};
|
|
19
|
+
function getRepoName() {
|
|
20
|
+
try {
|
|
21
|
+
const remote = execFileSync("git", ["remote", "get-url", "origin"], GIT_OPTS).trim();
|
|
22
|
+
const slug = parseRemoteSlug(remote);
|
|
23
|
+
if (slug) return slug;
|
|
24
|
+
} catch {
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const top = execFileSync("git", ["rev-parse", "--show-toplevel"], GIT_OPTS).trim();
|
|
28
|
+
if (top) return basename(top);
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
function getBranch() {
|
|
34
|
+
try {
|
|
35
|
+
const branch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], GIT_OPTS).trim();
|
|
36
|
+
return branch && branch !== "HEAD" ? branch : null;
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
var SLUG_PART = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/;
|
|
42
|
+
function parseRemoteSlug(url) {
|
|
43
|
+
const ssh = url.match(/[^:/]+[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
|
|
44
|
+
if (ssh) {
|
|
45
|
+
const owner = ssh[1];
|
|
46
|
+
const name = ssh[2];
|
|
47
|
+
if (owner && name && SLUG_PART.test(owner) && SLUG_PART.test(name)) return `${owner}/${name}`;
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/presence.ts
|
|
53
|
+
var SCUTIL_OPTS = {
|
|
54
|
+
encoding: "utf-8",
|
|
55
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
56
|
+
timeout: 2e3
|
|
57
|
+
};
|
|
58
|
+
var cachedMachine = null;
|
|
59
|
+
function getMachine() {
|
|
60
|
+
if (cachedMachine === null) cachedMachine = resolveMachine();
|
|
61
|
+
return cachedMachine;
|
|
62
|
+
}
|
|
63
|
+
function resolveMachine() {
|
|
64
|
+
if (osPlatform() === "darwin") {
|
|
65
|
+
try {
|
|
66
|
+
const local = execFileSync2("scutil", ["--get", "LocalHostName"], SCUTIL_OPTS).trim();
|
|
67
|
+
if (local) return local;
|
|
68
|
+
} catch {
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return hostname().replace(/\.local$/i, "");
|
|
72
|
+
}
|
|
73
|
+
function shortMachineName(machine = getMachine()) {
|
|
74
|
+
return machine.split(".")[0] || machine;
|
|
75
|
+
}
|
|
76
|
+
var PLATFORM_LABELS = {
|
|
77
|
+
claude: "Claude Code",
|
|
78
|
+
codex: "Codex",
|
|
79
|
+
cowork: "Cowork"
|
|
80
|
+
};
|
|
81
|
+
function getName(platform) {
|
|
82
|
+
if (PLATFORM_LABELS[platform]) return PLATFORM_LABELS[platform];
|
|
83
|
+
if (!platform || platform === "unknown") return "Agent";
|
|
84
|
+
return platform.charAt(0).toUpperCase() + platform.slice(1);
|
|
85
|
+
}
|
|
86
|
+
function getSurface() {
|
|
87
|
+
const surface = {};
|
|
88
|
+
const repo = getRepoName();
|
|
89
|
+
if (repo) surface.repo = repo;
|
|
90
|
+
const branch = getBranch();
|
|
91
|
+
if (branch) surface.branch = branch;
|
|
92
|
+
return surface;
|
|
93
|
+
}
|
|
94
|
+
function detectPlatform(argv = process.argv.slice(2)) {
|
|
95
|
+
const flag = argv.find((a) => a.startsWith("--platform="));
|
|
96
|
+
if (flag) return flag.slice("--platform=".length) || "unknown";
|
|
97
|
+
const idx = argv.indexOf("--platform");
|
|
98
|
+
if (idx >= 0 && argv[idx + 1]) return argv[idx + 1];
|
|
99
|
+
if (process.env.CLAUDECODE === "1" || process.env.CLAUDE_CODE) return "claude";
|
|
100
|
+
if (process.env.CODEX || process.env.CODEX_CI) return "codex";
|
|
101
|
+
return "unknown";
|
|
102
|
+
}
|
|
103
|
+
function sanitizeSessionKey(value) {
|
|
104
|
+
if (!value) return null;
|
|
105
|
+
const trimmed = value.trim();
|
|
106
|
+
return /^[A-Za-z0-9_-]{1,128}$/.test(trimmed) ? trimmed : null;
|
|
107
|
+
}
|
|
108
|
+
function newSessionKey() {
|
|
109
|
+
return sanitizeSessionKey(process.env.CLAUDE_CODE_SESSION_ID) ?? sanitizeSessionKey(process.env.CLAUDE_SESSION_ID) ?? randomUUID();
|
|
110
|
+
}
|
|
111
|
+
var HeartbeatClient = class {
|
|
112
|
+
constructor(deps = {}) {
|
|
113
|
+
this.deps = deps;
|
|
114
|
+
}
|
|
115
|
+
deps;
|
|
116
|
+
warned = false;
|
|
117
|
+
async send(body) {
|
|
118
|
+
try {
|
|
119
|
+
await api("/api/agent/mesh/heartbeat", {
|
|
120
|
+
method: "POST",
|
|
121
|
+
body: { kind: "agent", capabilities: ["receive"], ...body },
|
|
122
|
+
...this.deps.fetchFn ? { fetchFn: this.deps.fetchFn } : {}
|
|
123
|
+
});
|
|
124
|
+
return true;
|
|
125
|
+
} catch (err) {
|
|
126
|
+
if (!this.warned) {
|
|
127
|
+
this.warned = true;
|
|
128
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
129
|
+
process.stderr.write(`cloop: heartbeat failed (${msg}). Presence may be stale.
|
|
130
|
+
`);
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** Test/introspection helper. */
|
|
136
|
+
hasWarned() {
|
|
137
|
+
return this.warned;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
export {
|
|
142
|
+
getMachine,
|
|
143
|
+
shortMachineName,
|
|
144
|
+
getName,
|
|
145
|
+
getSurface,
|
|
146
|
+
detectPlatform,
|
|
147
|
+
sanitizeSessionKey,
|
|
148
|
+
newSessionKey,
|
|
149
|
+
HeartbeatClient
|
|
150
|
+
};
|