@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.
@@ -0,0 +1,131 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ sanitizeLabel
4
+ } from "./chunk-4LFQXBWP.js";
5
+ import {
6
+ CONFIG_DIR
7
+ } from "./chunk-3DIGCVL4.js";
8
+
9
+ // src/session-state.ts
10
+ import {
11
+ chmodSync,
12
+ mkdirSync,
13
+ readFileSync,
14
+ readdirSync,
15
+ renameSync,
16
+ rmSync,
17
+ writeFileSync
18
+ } from "fs";
19
+ import { homedir } from "os";
20
+ import { join } from "path";
21
+ var SESSIONS_DIR = "sessions";
22
+ var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
23
+ var TOOL_PHRASES = {
24
+ AskUserQuestion: "asking a question",
25
+ Bash: "running a command",
26
+ BashOutput: "watching a command",
27
+ Edit: "editing a file",
28
+ ExitPlanMode: "presenting a plan",
29
+ Glob: "finding files",
30
+ Grep: "searching the code",
31
+ KillShell: "stopping a command",
32
+ NotebookEdit: "editing a notebook",
33
+ Read: "reading a file",
34
+ Skill: "running a skill",
35
+ SlashCommand: "running a command",
36
+ Task: "running a subagent",
37
+ TodoWrite: "planning",
38
+ WebFetch: "reading a page",
39
+ WebSearch: "searching the web",
40
+ Write: "writing a file"
41
+ };
42
+ function toolPhrase(toolName) {
43
+ const name = (toolName ?? "").trim();
44
+ if (!name) return "working";
45
+ if (TOOL_PHRASES[name]) return TOOL_PHRASES[name];
46
+ if (name.startsWith("mcp__")) {
47
+ const parts = name.split("__");
48
+ const server = parts[1] ?? "";
49
+ const tool = parts.slice(2).join(" ").replace(/_/g, " ").trim();
50
+ if (server && tool) return `${server} \xB7 ${tool}`;
51
+ }
52
+ if (/^[a-z0-9]+(_[a-z0-9]+)+$/.test(name)) return name.replace(/_/g, " ");
53
+ return name;
54
+ }
55
+ function sessionsDir() {
56
+ return process.env.CLOOP_SESSIONS_DIR ?? join(homedir(), CONFIG_DIR, SESSIONS_DIR);
57
+ }
58
+ function statePathFor(key) {
59
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(key)) return null;
60
+ return join(sessionsDir(), `${key}.json`);
61
+ }
62
+ function readSessionState(key) {
63
+ const path = statePathFor(key);
64
+ if (!path) return null;
65
+ try {
66
+ const parsed = JSON.parse(readFileSync(path, "utf-8"));
67
+ if (parsed.status !== "active" && parsed.status !== "idle") return null;
68
+ if (typeof parsed.at !== "string") return null;
69
+ return {
70
+ status: parsed.status,
71
+ event: typeof parsed.event === "string" ? parsed.event : "",
72
+ at: parsed.at
73
+ };
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+ function writeSessionState(key, status, event, at = /* @__PURE__ */ new Date()) {
79
+ const path = statePathFor(key);
80
+ if (!path) return;
81
+ const body = {
82
+ status,
83
+ // The event reaches the mesh and then a terminal status bar; keep it a
84
+ // short single-line label from the start.
85
+ event: sanitizeLabel(event, 32),
86
+ at: at.toISOString()
87
+ };
88
+ try {
89
+ mkdirSync(sessionsDir(), { recursive: true, mode: 448 });
90
+ const tmp = `${path}.${process.pid}.tmp`;
91
+ writeFileSync(tmp, `${JSON.stringify(body)}
92
+ `, { mode: 384 });
93
+ renameSync(tmp, path);
94
+ try {
95
+ chmodSync(path, 384);
96
+ } catch {
97
+ }
98
+ } catch {
99
+ }
100
+ }
101
+ function clearSessionState(key) {
102
+ const path = statePathFor(key);
103
+ if (!path) return;
104
+ try {
105
+ rmSync(path, { force: true });
106
+ } catch {
107
+ }
108
+ }
109
+ function pruneSessionStates(now = Date.now()) {
110
+ let entries;
111
+ try {
112
+ entries = readdirSync(sessionsDir());
113
+ } catch {
114
+ return;
115
+ }
116
+ for (const entry of entries) {
117
+ if (!entry.endsWith(".json")) continue;
118
+ const key = entry.slice(0, -".json".length);
119
+ const state = readSessionState(key);
120
+ const at = state ? Date.parse(state.at) : Number.NaN;
121
+ if (Number.isNaN(at) || now - at > MAX_AGE_MS) clearSessionState(key);
122
+ }
123
+ }
124
+
125
+ export {
126
+ toolPhrase,
127
+ readSessionState,
128
+ writeSessionState,
129
+ clearSessionState,
130
+ pruneSessionStates
131
+ };
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/version.ts
4
+ var VERSION = true ? "0.2.1" : "0.0.0-dev";
5
+
6
+ export {
7
+ VERSION
8
+ };
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/mesh-socket.ts
4
+ var WS_OPEN = 1;
5
+ function backoffDelay(attempt, { base = 1e3, max = 6e4, jitter = 0.2 } = {}, rand = Math.random) {
6
+ const raw = Math.min(base * 2 ** attempt, max);
7
+ const spread = raw * jitter;
8
+ return Math.round(raw - spread + rand() * spread * 2);
9
+ }
10
+ function wsUrl(meshUrl, sessionKey, kind) {
11
+ const base = meshUrl.replace(/^http/, "ws").replace(/\/+$/, "");
12
+ const kindParam = kind && kind !== "agent" ? `&kind=${encodeURIComponent(kind)}` : "";
13
+ return `${base}/mesh/agent?session_key=${encodeURIComponent(sessionKey)}${kindParam}`;
14
+ }
15
+ var MeshSocket = class {
16
+ constructor(opts) {
17
+ this.opts = opts;
18
+ this.token = opts.token;
19
+ }
20
+ opts;
21
+ ws = null;
22
+ attempt = 0;
23
+ timer = null;
24
+ stopped = false;
25
+ open = false;
26
+ token;
27
+ /** Connect again with a new device token, after a refusal of the old one. */
28
+ restart(token) {
29
+ this.token = token;
30
+ this.attempt = 0;
31
+ this.start();
32
+ }
33
+ /** Begin connecting (and keep reconnecting until close()). */
34
+ start() {
35
+ this.stopped = false;
36
+ this.connect();
37
+ }
38
+ connect() {
39
+ if (this.stopped) return;
40
+ let ws;
41
+ try {
42
+ ws = this.opts.factory(wsUrl(this.opts.meshUrl, this.opts.sessionKey, this.opts.kind), [
43
+ "cloop.v1",
44
+ this.token
45
+ ]);
46
+ } catch {
47
+ this.scheduleReconnect();
48
+ return;
49
+ }
50
+ this.ws = ws;
51
+ ws.on("open", () => {
52
+ this.open = true;
53
+ this.attempt = 0;
54
+ this.opts.onOpen?.();
55
+ });
56
+ ws.on("message", (data) => this.handleMessage(data));
57
+ ws.on("close", (code) => {
58
+ const wasOpen = this.open;
59
+ this.open = false;
60
+ if (wasOpen) this.opts.onClose?.(typeof code === "number" ? code : void 0);
61
+ this.scheduleReconnect();
62
+ });
63
+ ws.on("error", (err) => {
64
+ if (this.opts.onRefused && /Unexpected server response: 401\b/.test(String(err?.message))) {
65
+ this.stopped = true;
66
+ this.opts.onRefused();
67
+ }
68
+ });
69
+ }
70
+ handleMessage(data) {
71
+ let frame;
72
+ try {
73
+ const text = typeof data === "string" ? data : String(data);
74
+ frame = JSON.parse(text);
75
+ } catch {
76
+ return;
77
+ }
78
+ if (frame.type === "call") {
79
+ if (frame.id && frame.tool) {
80
+ this.opts.onCall?.({
81
+ type: "call",
82
+ id: frame.id,
83
+ tool: frame.tool,
84
+ args: frame.args ?? {}
85
+ });
86
+ }
87
+ return;
88
+ }
89
+ if (frame.type === "ack") {
90
+ if (typeof frame.of === "string") this.opts.onAck?.(frame.of, frame.ok !== false);
91
+ return;
92
+ }
93
+ if (frame.type !== "delegate" && frame.type !== "dm") return;
94
+ this.opts.onMessage({
95
+ type: frame.type,
96
+ id: frame.id ?? "",
97
+ at: frame.at ?? (/* @__PURE__ */ new Date()).toISOString(),
98
+ ...frame.from ? { from: frame.from } : {},
99
+ ...frame.type === "delegate" ? { task: frame.task } : { body: frame.body ?? "" }
100
+ });
101
+ }
102
+ scheduleReconnect() {
103
+ if (this.stopped || this.timer) return;
104
+ const delay = backoffDelay(this.attempt, this.opts.backoff, this.opts.rand);
105
+ this.attempt++;
106
+ this.timer = setTimeout(() => {
107
+ this.timer = null;
108
+ this.connect();
109
+ }, delay);
110
+ this.timer.unref?.();
111
+ }
112
+ isConnected() {
113
+ return this.open && this.ws?.readyState === WS_OPEN;
114
+ }
115
+ /** Send a presence beat over the socket. Returns false if not connected. */
116
+ sendPresence(body) {
117
+ return this.send({ type: "presence", ...body });
118
+ }
119
+ /** Send any client frame. Returns false if not connected. */
120
+ send(frame) {
121
+ if (!this.isConnected() || !this.ws) return false;
122
+ try {
123
+ this.ws.send(JSON.stringify(frame));
124
+ return true;
125
+ } catch {
126
+ return false;
127
+ }
128
+ }
129
+ close() {
130
+ this.stopped = true;
131
+ this.open = false;
132
+ if (this.timer) {
133
+ clearTimeout(this.timer);
134
+ this.timer = null;
135
+ }
136
+ try {
137
+ this.ws?.close();
138
+ } catch {
139
+ }
140
+ }
141
+ };
142
+ async function defaultSocketFactory() {
143
+ const { WebSocket } = await import("ws");
144
+ return (url, protocols) => new WebSocket(url, protocols);
145
+ }
146
+
147
+ export {
148
+ MeshSocket,
149
+ defaultSocketFactory
150
+ };
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DEFAULT_T3_URL,
4
+ askOrClosed,
5
+ askRepos,
6
+ awaitDaemon,
7
+ chooseDriver,
8
+ connectBox,
9
+ connectChosen,
10
+ connectCommand,
11
+ detect,
12
+ fallbackDriver,
13
+ fallbackLine,
14
+ findCheckouts,
15
+ harnessesFound,
16
+ installedService,
17
+ isWorkstation,
18
+ mintSession,
19
+ notACheckoutLine,
20
+ parsePicks,
21
+ programFor,
22
+ rerunCommand,
23
+ resolveRepos,
24
+ revokeReplaced,
25
+ runSteps,
26
+ systemdAssignment,
27
+ systemdWord,
28
+ tilde,
29
+ unitEnv,
30
+ unitFor
31
+ } from "./chunk-2ZVYM4JU.js";
32
+ import "./chunk-AQGBNKUG.js";
33
+ import "./chunk-JX6VG5FE.js";
34
+ import "./chunk-AG6SI6I2.js";
35
+ import "./chunk-OKF4BDBH.js";
36
+ import "./chunk-3DIGCVL4.js";
37
+ export {
38
+ DEFAULT_T3_URL,
39
+ askOrClosed,
40
+ askRepos,
41
+ awaitDaemon,
42
+ chooseDriver,
43
+ connectBox,
44
+ connectChosen,
45
+ connectCommand,
46
+ detect,
47
+ fallbackDriver,
48
+ fallbackLine,
49
+ findCheckouts,
50
+ harnessesFound,
51
+ installedService,
52
+ isWorkstation,
53
+ mintSession,
54
+ notACheckoutLine,
55
+ parsePicks,
56
+ programFor,
57
+ rerunCommand,
58
+ resolveRepos,
59
+ revokeReplaced,
60
+ runSteps,
61
+ systemdAssignment,
62
+ systemdWord,
63
+ tilde,
64
+ unitEnv,
65
+ unitFor
66
+ };
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ boxPath,
4
+ installedService,
5
+ localRunsFilePath,
6
+ readRunnerConfig,
7
+ revokeOwnDevice,
8
+ runSteps,
9
+ runnerStatePath,
10
+ threadsFilePath,
11
+ tokenGone
12
+ } from "./chunk-2ZVYM4JU.js";
13
+ import "./chunk-AQGBNKUG.js";
14
+ import "./chunk-JX6VG5FE.js";
15
+ import "./chunk-AG6SI6I2.js";
16
+ import "./chunk-OKF4BDBH.js";
17
+ import {
18
+ getOrigin
19
+ } from "./chunk-3DIGCVL4.js";
20
+
21
+ // src/commands/disconnect.ts
22
+ import { execFileSync } from "child_process";
23
+ import { existsSync, readFileSync, rmSync } from "fs";
24
+ import { homedir } from "os";
25
+ var DONE_LINE = "This computer is no longer a Cloop runner. To connect it again: npx -y @cloop/runner connect";
26
+ function unitOrigin(contents) {
27
+ const plist = /<key>CLOOP_ORIGIN<\/key><string>([^<]+)<\/string>/.exec(contents)?.[1];
28
+ if (plist) return plist.replace(/&amp;/g, "&");
29
+ const unit = /Environment="CLOOP_ORIGIN=([^"]+)"/.exec(contents)?.[1];
30
+ return unit ? unit.replace(/%%/g, "%") : null;
31
+ }
32
+ function disconnectPlan(opts) {
33
+ const exists = opts.exists ?? existsSync;
34
+ const read = opts.read ?? ((path) => readFileSync(path, "utf-8"));
35
+ const services = ["local", "workstation"].map((kind) => installedService({ ...opts, kind })).filter((service) => exists(service.path));
36
+ const fromUnit = services.map((service) => {
37
+ try {
38
+ return unitOrigin(read(service.path));
39
+ } catch {
40
+ return null;
41
+ }
42
+ }).find(Boolean);
43
+ return {
44
+ origin: opts.boxOrigin ?? fromUnit ?? opts.fallbackOrigin,
45
+ deviceToken: opts.deviceToken,
46
+ services,
47
+ box: exists(opts.box) ? opts.box : null,
48
+ files: opts.files.filter((file) => exists(file)),
49
+ isBox: opts.platform !== "darwin" && services.some((s) => s.path.endsWith("/cloop-box.service"))
50
+ };
51
+ }
52
+ function revokeLine(revoke, origin, box) {
53
+ const keep = box ? ` Kept ${box}, which holds the device token, so you can try again.` : "";
54
+ switch (revoke) {
55
+ case "revoked":
56
+ return [`Revoked this computer on Cloop (${origin}).`];
57
+ case "already_revoked":
58
+ return [`Cloop (${origin}) had already revoked this computer.`];
59
+ case "no_device":
60
+ return ["No runner device on this computer to revoke."];
61
+ case "unknown_device":
62
+ return [
63
+ `Cloop at ${origin} never issued this computer's device token, so it belongs to the other environment.${keep}`,
64
+ "Run `cloop disconnect --staging` for a staging runner, or `cloop disconnect` for production."
65
+ ];
66
+ case "failed":
67
+ return [
68
+ `Could not revoke this computer at ${origin}: Cloop did not answer as expected.${keep}`,
69
+ "Run `cloop disconnect` again when Cloop answers, or press Disconnect on its card on the Threads page and then delete that file."
70
+ ];
71
+ }
72
+ }
73
+ async function disconnect(plan, opts) {
74
+ const { say } = opts;
75
+ const run = opts.run ?? ((command) => void execFileSync(command[0], command.slice(1), {
76
+ stdio: "ignore",
77
+ timeout: 15e3
78
+ }));
79
+ if (plan.isBox && !opts.yes) {
80
+ say("This computer runs cloop-box.service, a Cloop box with T3 Code. Disconnect would:");
81
+ for (const s of plan.services) say(` stop and remove ${s.path}`);
82
+ if (plan.deviceToken) say(` revoke its runner device on Cloop (${plan.origin})`);
83
+ for (const f of [...plan.box ? [plan.box] : [], ...plan.files]) say(` delete ${f}`);
84
+ say("Run `cloop disconnect --yes` to do this.");
85
+ return 1;
86
+ }
87
+ for (const service of plan.services) {
88
+ await runSteps(service.steps, run);
89
+ let stillRunning = true;
90
+ try {
91
+ run(service.running);
92
+ } catch {
93
+ stillRunning = false;
94
+ }
95
+ if (stillRunning) {
96
+ say(
97
+ `Could not stop the service in ${service.path}. Nothing was removed. Stop it with \`${service.steps.map((s) => s.command.join(" ")).join(" && ")}\`, then run \`cloop disconnect\` again.`
98
+ );
99
+ return 1;
100
+ }
101
+ say(`Stopped the service in ${service.path}`);
102
+ }
103
+ const revoked = await opts.revoke(plan.origin, plan.deviceToken);
104
+ const gone = tokenGone(revoked);
105
+ for (const service of plan.services) {
106
+ rmSync(service.path, { force: true });
107
+ say(`Removed ${service.path}`);
108
+ }
109
+ for (const file of [...gone && plan.box ? [plan.box] : [], ...plan.files]) {
110
+ rmSync(file, { force: true });
111
+ say(`Deleted ${file}`);
112
+ }
113
+ for (const line of revokeLine(revoked, plan.origin, plan.box)) say(line);
114
+ if (!gone) return 1;
115
+ say(DONE_LINE);
116
+ return 0;
117
+ }
118
+ async function disconnectCommand(argv) {
119
+ const cfg = readRunnerConfig();
120
+ const plan = disconnectPlan({
121
+ platform: process.platform,
122
+ home: homedir(),
123
+ uid: process.getuid?.() ?? 0,
124
+ ...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {},
125
+ box: boxPath(),
126
+ deviceToken: cfg?.deviceToken ?? null,
127
+ ...cfg?.origin ? { boxOrigin: cfg.origin } : {},
128
+ fallbackOrigin: getOrigin(),
129
+ files: [localRunsFilePath(), runnerStatePath(), threadsFilePath()]
130
+ });
131
+ process.exitCode = await disconnect(plan, {
132
+ yes: argv.includes("--yes"),
133
+ revoke: (origin, token) => revokeOwnDevice(origin, token),
134
+ say: (line) => console.log(line)
135
+ });
136
+ }
137
+ export {
138
+ DONE_LINE,
139
+ disconnect,
140
+ disconnectCommand,
141
+ disconnectPlan,
142
+ unitOrigin
143
+ };
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ clearSessionState,
4
+ pruneSessionStates,
5
+ toolPhrase,
6
+ writeSessionState
7
+ } from "./chunk-OJ5AREUC.js";
8
+ import "./chunk-4LFQXBWP.js";
9
+ import {
10
+ HeartbeatClient,
11
+ detectPlatform,
12
+ getMachine,
13
+ getName,
14
+ getSurface,
15
+ sanitizeSessionKey
16
+ } from "./chunk-JX6VG5FE.js";
17
+ import "./chunk-AG6SI6I2.js";
18
+ import {
19
+ getToken
20
+ } from "./chunk-3DIGCVL4.js";
21
+
22
+ // src/commands/hook-activity.ts
23
+ async function readStdin() {
24
+ if (process.stdin.isTTY) return "";
25
+ const chunks = [];
26
+ for await (const chunk of process.stdin) {
27
+ chunks.push(chunk);
28
+ }
29
+ return Buffer.concat(chunks).toString("utf-8");
30
+ }
31
+ function activityFor(payload) {
32
+ switch (payload.hook_event_name) {
33
+ case "UserPromptSubmit":
34
+ return { status: "active", event: "starting a turn" };
35
+ case "PreToolUse":
36
+ return { status: "active", event: toolPhrase(payload.tool_name) };
37
+ // Not installed by default — PreToolUse already names the running tool,
38
+ // and each hook costs a process spawn per tool call. Handled anyway for
39
+ // anyone who wires it by hand.
40
+ case "PostToolUse":
41
+ return { status: "active", event: toolPhrase(payload.tool_name) };
42
+ case "Stop":
43
+ case "SubagentStop":
44
+ return { status: "idle", event: "awaiting input" };
45
+ case "Notification":
46
+ return { status: "idle", event: "needs input" };
47
+ default:
48
+ return null;
49
+ }
50
+ }
51
+ async function hookActivity() {
52
+ let payload = {};
53
+ try {
54
+ const raw = await readStdin();
55
+ if (raw.trim()) payload = JSON.parse(raw);
56
+ } catch {
57
+ return;
58
+ }
59
+ const key = sanitizeSessionKey(payload.session_id);
60
+ if (!key) return;
61
+ if (payload.hook_event_name === "SessionEnd") {
62
+ clearSessionState(key);
63
+ await endedBeat(key);
64
+ return;
65
+ }
66
+ const activity = activityFor(payload);
67
+ if (!activity) return;
68
+ writeSessionState(key, activity.status, activity.event);
69
+ if (payload.hook_event_name === "UserPromptSubmit") pruneSessionStates();
70
+ }
71
+ async function endedBeat(sessionKey) {
72
+ if (!getToken()) return;
73
+ try {
74
+ const platform = detectPlatform();
75
+ await new HeartbeatClient().send({
76
+ session_key: sessionKey,
77
+ name: getName(platform),
78
+ platform,
79
+ machine: getMachine(),
80
+ surface: getSurface(),
81
+ status: "ended",
82
+ event: "session ended",
83
+ event_at: (/* @__PURE__ */ new Date()).toISOString()
84
+ });
85
+ } catch {
86
+ }
87
+ }
88
+ export {
89
+ activityFor,
90
+ hookActivity
91
+ };