@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.
@@ -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-SQJ7ZO4G.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,69 @@
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
+ applyEnvironmentFlag,
64
+ readCredentials,
65
+ writeCredentials,
66
+ getOrigin,
67
+ getToken,
68
+ getMeshUrl
69
+ };
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CONFIG_DIR
4
+ } from "./chunk-SQJ7ZO4G.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
+
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,41 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ DEFAULT_T3_URL,
4
+ awaitDaemon,
5
+ chooseDriver,
6
+ compareVersions,
7
+ connectBox,
8
+ connectCommand,
9
+ detect,
10
+ mintSession,
11
+ programFor,
12
+ resolveRepos,
13
+ resolveT3Bin,
14
+ startService,
15
+ systemdAssignment,
16
+ systemdWord,
17
+ unitEnv,
18
+ unitFor
19
+ } from "./chunk-IIUHGZKX.js";
20
+ import "./chunk-CMOMRXTA.js";
21
+ import "./chunk-7K5W6ELQ.js";
22
+ import "./chunk-4UE33DYW.js";
23
+ import "./chunk-SQJ7ZO4G.js";
24
+ export {
25
+ DEFAULT_T3_URL,
26
+ awaitDaemon,
27
+ chooseDriver,
28
+ compareVersions,
29
+ connectBox,
30
+ connectCommand,
31
+ detect,
32
+ mintSession,
33
+ programFor,
34
+ resolveRepos,
35
+ resolveT3Bin,
36
+ startService,
37
+ systemdAssignment,
38
+ systemdWord,
39
+ unitEnv,
40
+ unitFor
41
+ };
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ clearSessionState,
4
+ pruneSessionStates,
5
+ toolPhrase,
6
+ writeSessionState
7
+ } from "./chunk-IR3P526R.js";
8
+ import "./chunk-4LFQXBWP.js";
9
+ import {
10
+ HeartbeatClient,
11
+ detectPlatform,
12
+ getMachine,
13
+ getName,
14
+ getSurface,
15
+ sanitizeSessionKey
16
+ } from "./chunk-HS5CIDQF.js";
17
+ import "./chunk-4UE33DYW.js";
18
+ import {
19
+ getToken
20
+ } from "./chunk-SQJ7ZO4G.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
+ };