@cloop/runner 0.3.67 → 0.3.69
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/dist/{box-NMG35YB2.js → box-UOJ6ET2B.js} +203 -522
- package/dist/{chunk-7LPSTDZE.js → chunk-4JTIWZHB.js} +1 -1
- package/dist/{chunk-IK7YYRMU.js → chunk-57E5WOOP.js} +574 -1673
- package/dist/{chunk-5RB7XKPB.js → chunk-AZQGERT7.js} +13 -1
- package/dist/{chunk-TCNIRZLU.js → chunk-CLOYOD2X.js} +10 -6
- package/dist/{chunk-6LYMSWSB.js → chunk-DN6TQALA.js} +265 -1961
- package/dist/{chunk-KYDTE53W.js → chunk-DTUNRKBC.js} +1 -1
- package/dist/chunk-EEG5JOZ7.js +939 -0
- package/dist/chunk-GAEZIKCK.js +626 -0
- package/dist/chunk-HIBAH65V.js +1178 -0
- package/dist/{chunk-7ZL3Z3IO.js → chunk-JI5FWLDU.js} +6 -6
- package/dist/chunk-JJWSPBM4.js +40 -0
- package/dist/{chunk-OIHUQBA4.js → chunk-KIYCULVE.js} +4 -2
- package/dist/{chunk-QKRGJKJN.js → chunk-SJAGZNFF.js} +3 -83
- package/dist/chunk-TPKYD3JF.js +43 -0
- package/dist/chunk-WCKW2Z2G.js +459 -0
- package/dist/chunk-ZHQSGJCE.js +85 -0
- package/dist/{connect-3GG5D7XC.js → connect-HVOAYXWM.js} +12 -48
- package/dist/disconnect-DQ6WSDR7.js +163 -0
- package/dist/existing-runner-BSSRQFFP.js +15 -0
- package/dist/index.js +14 -14
- package/dist/{login-COK223KI.js → login-4HWP4PF4.js} +3 -2
- package/dist/{mcp-server-5525QT5K.js → mcp-server-DTJVCFRG.js} +10 -10
- package/dist/{runner-NSFLXWNP.js → runner-4XWS2RJL.js} +4 -3
- package/dist/{runs-DOFU45TW.js → runs-TWUGWGNU.js} +4 -2
- package/dist/{statusline-QHEED6IO.js → statusline-C2FH3YQ4.js} +1 -1
- package/dist/{takeover-U2EHJ5GW.js → takeover-5QSP6YAG.js} +6 -4
- package/dist/{use-J6CNF6JU.js → use-U3E55XBK.js} +20 -13
- package/package.json +1 -1
- package/dist/disconnect-VK3CZIDQ.js +0 -30
- package/dist/existing-runner-NNXJGK2R.js +0 -20
|
@@ -2,17 +2,17 @@
|
|
|
2
2
|
import {
|
|
3
3
|
findRun,
|
|
4
4
|
ownHarness
|
|
5
|
-
} from "./chunk-
|
|
6
|
-
import {
|
|
7
|
-
lockThreadsFile,
|
|
8
|
-
threadsFilePath
|
|
9
|
-
} from "./chunk-7LPSTDZE.js";
|
|
5
|
+
} from "./chunk-CLOYOD2X.js";
|
|
10
6
|
import {
|
|
11
7
|
localRunsFilePath,
|
|
12
8
|
readRunRecords,
|
|
13
9
|
runHarness,
|
|
14
10
|
takeoverSummary
|
|
15
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-HIBAH65V.js";
|
|
12
|
+
import {
|
|
13
|
+
lockThreadsFile,
|
|
14
|
+
threadsFilePath
|
|
15
|
+
} from "./chunk-4JTIWZHB.js";
|
|
16
16
|
import {
|
|
17
17
|
sanitizeLabel
|
|
18
18
|
} from "./chunk-VK6GV757.js";
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/device-revoke.ts
|
|
4
|
+
function tokenGone(revoke) {
|
|
5
|
+
return revoke === "revoked" || revoke === "already_revoked" || revoke === "no_device";
|
|
6
|
+
}
|
|
7
|
+
async function revokeOwnDevice(origin, deviceToken, fetchFn = fetch) {
|
|
8
|
+
if (!deviceToken) return "no_device";
|
|
9
|
+
try {
|
|
10
|
+
const res = await fetchFn(`${origin}/api/agent/mesh/device-revoke`, {
|
|
11
|
+
method: "POST",
|
|
12
|
+
headers: { authorization: `Bearer ${deviceToken}` },
|
|
13
|
+
signal: AbortSignal.timeout(1e4)
|
|
14
|
+
});
|
|
15
|
+
const body = await res.json().catch(() => null);
|
|
16
|
+
if (res.ok && body?.outcome === "revoked") return "revoked";
|
|
17
|
+
if (res.ok && body?.outcome === "already_revoked") return "already_revoked";
|
|
18
|
+
if (res.status === 401 && body?.error === "unknown_device") return "unknown_device";
|
|
19
|
+
return "failed";
|
|
20
|
+
} catch {
|
|
21
|
+
return "failed";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/harness-home.ts
|
|
26
|
+
import { homedir } from "os";
|
|
27
|
+
import { join } from "path";
|
|
28
|
+
function claudeHome() {
|
|
29
|
+
return process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
|
|
30
|
+
}
|
|
31
|
+
function codexHome() {
|
|
32
|
+
return process.env.CODEX_HOME || join(homedir(), ".codex");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export {
|
|
36
|
+
tokenGone,
|
|
37
|
+
revokeOwnDevice,
|
|
38
|
+
claudeHome,
|
|
39
|
+
codexHome
|
|
40
|
+
};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
ConnectFailure
|
|
4
|
+
} from "./chunk-ZHQSGJCE.js";
|
|
2
5
|
import {
|
|
3
6
|
ApiError,
|
|
4
7
|
api,
|
|
5
8
|
defaultDeviceName
|
|
6
9
|
} from "./chunk-SBYSVZ7J.js";
|
|
7
|
-
import {
|
|
8
|
-
VERSION
|
|
9
|
-
} from "./chunk-KYDTE53W.js";
|
|
10
10
|
import {
|
|
11
11
|
getOrigin,
|
|
12
12
|
readCredentials,
|
|
@@ -15,82 +15,6 @@ import {
|
|
|
15
15
|
|
|
16
16
|
// src/commands/login.ts
|
|
17
17
|
import { execFile } from "child_process";
|
|
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
|
-
workFolder: false,
|
|
40
|
-
codexInstall: null,
|
|
41
|
-
codexInstallReason: null,
|
|
42
|
-
claudeInstall: null,
|
|
43
|
-
mcpRegistered: [],
|
|
44
|
-
mcpSignedIn: [],
|
|
45
|
-
deviceToken: null,
|
|
46
|
-
deviceLogin: null,
|
|
47
|
-
relink: null
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
function shortMachineLabel(machine) {
|
|
51
|
-
return machine.split(".")[0]?.replace(/[^A-Za-z0-9-]/g, "-").slice(0, 63) || "unknown";
|
|
52
|
-
}
|
|
53
|
-
function connectReport(attempt, error, machine, now = Date.now()) {
|
|
54
|
-
return {
|
|
55
|
-
attempt_id: attempt.id,
|
|
56
|
-
cli_version: VERSION,
|
|
57
|
-
os: process.platform,
|
|
58
|
-
arch: process.arch,
|
|
59
|
-
node_version: process.version,
|
|
60
|
-
machine: shortMachineLabel(machine),
|
|
61
|
-
harnesses: attempt.harnesses,
|
|
62
|
-
driver: attempt.driver,
|
|
63
|
-
fell_back: attempt.fellBack,
|
|
64
|
-
work_folder: attempt.workFolder,
|
|
65
|
-
codex_install: attempt.codexInstall,
|
|
66
|
-
codex_install_reason: attempt.codexInstallReason,
|
|
67
|
-
claude_install: attempt.claudeInstall,
|
|
68
|
-
mcp_registered: attempt.mcpRegistered,
|
|
69
|
-
mcp_signed_in: attempt.mcpSignedIn,
|
|
70
|
-
device_login: attempt.deviceLogin,
|
|
71
|
-
relink: attempt.relink,
|
|
72
|
-
step: attempt.step,
|
|
73
|
-
outcome: error ? "failed" : "ok",
|
|
74
|
-
error_code: error,
|
|
75
|
-
seconds: Math.round((now - attempt.startedAt) / 1e3)
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
async function sendConnectReport(origin, report, deviceToken, fetchFn = fetch) {
|
|
79
|
-
try {
|
|
80
|
-
await fetchFn(`${origin}/api/agent/mesh/connect-report`, {
|
|
81
|
-
method: "POST",
|
|
82
|
-
headers: {
|
|
83
|
-
"content-type": "application/json",
|
|
84
|
-
...deviceToken ? { authorization: `Bearer ${deviceToken}` } : {}
|
|
85
|
-
},
|
|
86
|
-
body: JSON.stringify(report),
|
|
87
|
-
signal: AbortSignal.timeout(3e3)
|
|
88
|
-
});
|
|
89
|
-
} catch {
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// src/commands/login.ts
|
|
94
18
|
var POLL_INTERVAL_MS = 3e3;
|
|
95
19
|
var POLL_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
96
20
|
var BOUND_ELSEWHERE = "This box is connected to another Cloop account. Disconnect it there first.";
|
|
@@ -245,10 +169,6 @@ function parseDeviceName(argv) {
|
|
|
245
169
|
}
|
|
246
170
|
|
|
247
171
|
export {
|
|
248
|
-
ConnectFailure,
|
|
249
|
-
newAttempt,
|
|
250
|
-
connectReport,
|
|
251
|
-
sendConnectReport,
|
|
252
172
|
loginCommand,
|
|
253
173
|
deviceLogin,
|
|
254
174
|
refusalSentence
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
legacyStagingRunner,
|
|
4
|
+
runnerOrigin
|
|
5
|
+
} from "./chunk-WCKW2Z2G.js";
|
|
6
|
+
import {
|
|
7
|
+
ENVIRONMENTS,
|
|
8
|
+
boxPath,
|
|
9
|
+
environmentOf,
|
|
10
|
+
runnerEnvironment
|
|
11
|
+
} from "./chunk-GAEZIKCK.js";
|
|
12
|
+
import {
|
|
13
|
+
pinRunnerEnvironment
|
|
14
|
+
} from "./chunk-D5UZW42X.js";
|
|
15
|
+
|
|
16
|
+
// src/existing-runner.ts
|
|
17
|
+
import { existsSync } from "fs";
|
|
18
|
+
var ALL = Object.keys(ENVIRONMENTS);
|
|
19
|
+
function runnersOnThisComputer() {
|
|
20
|
+
if (legacyStagingRunner()) return ["staging"];
|
|
21
|
+
return ALL.filter((env) => existsSync(boxPath(env)));
|
|
22
|
+
}
|
|
23
|
+
function existingRunnerEnvironment() {
|
|
24
|
+
const named = process.env.CLOOP_ORIGIN;
|
|
25
|
+
if (named) return environmentOf(named);
|
|
26
|
+
const found = runnersOnThisComputer();
|
|
27
|
+
return found.length === 1 && found[0] ? found[0] : "production";
|
|
28
|
+
}
|
|
29
|
+
var BOTH_RUNNERS_LINE = "This computer is a production machine and a staging machine. This acts on the production machine. Add --staging for the staging machine.";
|
|
30
|
+
function pinExistingRunner() {
|
|
31
|
+
const named = Boolean(process.env.CLOOP_ORIGIN);
|
|
32
|
+
const environment = existingRunnerEnvironment();
|
|
33
|
+
pinRunnerEnvironment(runnerOrigin(environment) ?? ENVIRONMENTS[environment].origin);
|
|
34
|
+
return {
|
|
35
|
+
environment: runnerEnvironment(),
|
|
36
|
+
note: !named && runnersOnThisComputer().length === ALL.length ? BOTH_RUNNERS_LINE : null
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export {
|
|
41
|
+
existingRunnerEnvironment,
|
|
42
|
+
pinExistingRunner
|
|
43
|
+
};
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
readRunnerState,
|
|
4
|
+
runnerStatePath
|
|
5
|
+
} from "./chunk-4JTIWZHB.js";
|
|
6
|
+
import {
|
|
7
|
+
boxPath,
|
|
8
|
+
environmentOf,
|
|
9
|
+
readRunnerConfig,
|
|
10
|
+
runnerDir,
|
|
11
|
+
serviceIdentity,
|
|
12
|
+
which,
|
|
13
|
+
windowsPowerShellEnv
|
|
14
|
+
} from "./chunk-GAEZIKCK.js";
|
|
15
|
+
import {
|
|
16
|
+
ConnectFailure
|
|
17
|
+
} from "./chunk-ZHQSGJCE.js";
|
|
18
|
+
import {
|
|
19
|
+
getOrigin
|
|
20
|
+
} from "./chunk-D5UZW42X.js";
|
|
21
|
+
|
|
22
|
+
// src/service.ts
|
|
23
|
+
import { execFileSync } from "child_process";
|
|
24
|
+
import { existsSync, readFileSync, realpathSync } from "fs";
|
|
25
|
+
import { homedir } from "os";
|
|
26
|
+
import { dirname, join } from "path";
|
|
27
|
+
function systemdAssignment(assignment) {
|
|
28
|
+
return `"${assignment.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
|
|
29
|
+
}
|
|
30
|
+
function systemdWord(arg) {
|
|
31
|
+
const escaped = arg.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$");
|
|
32
|
+
return `"${escaped}"`;
|
|
33
|
+
}
|
|
34
|
+
function cmdValue(value) {
|
|
35
|
+
return value.replace(/%/g, "%%");
|
|
36
|
+
}
|
|
37
|
+
function cmdWord(arg) {
|
|
38
|
+
return `"${cmdValue(arg)}"`;
|
|
39
|
+
}
|
|
40
|
+
var psQuote = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
41
|
+
function registerTaskScript(task, launcher) {
|
|
42
|
+
return [
|
|
43
|
+
"$ErrorActionPreference = 'Stop'",
|
|
44
|
+
"$user = [Security.Principal.WindowsIdentity]::GetCurrent().Name",
|
|
45
|
+
`$launcher = ${psQuote(launcher)}`,
|
|
46
|
+
[
|
|
47
|
+
"try {",
|
|
48
|
+
`Register-ScheduledTask -TaskName ${psQuote(task)} -Force`,
|
|
49
|
+
"-Action (New-ScheduledTaskAction -Execute (Join-Path $env:WINDIR 'System32\\conhost.exe') -Argument ('--headless ' + (Join-Path $env:WINDIR 'System32\\cmd.exe') + ' /d /c ' + [char]34 + $launcher + [char]34))",
|
|
50
|
+
"-Trigger (New-ScheduledTaskTrigger -AtLogOn -User $user)",
|
|
51
|
+
"-Principal (New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited)",
|
|
52
|
+
"-Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable)",
|
|
53
|
+
"| Out-Null",
|
|
54
|
+
"} catch {",
|
|
55
|
+
`$kept = Get-ScheduledTask -TaskName ${psQuote(task)} -ErrorAction SilentlyContinue;`,
|
|
56
|
+
"if (-not ($kept.Actions | Where-Object { ($_.Execute + ' ' + $_.Arguments).Contains($launcher) })) { throw }",
|
|
57
|
+
"}"
|
|
58
|
+
].join(" ")
|
|
59
|
+
].join("; ");
|
|
60
|
+
}
|
|
61
|
+
function endDaemonScript(statePath) {
|
|
62
|
+
return [
|
|
63
|
+
`$f = ${psQuote(statePath)}`,
|
|
64
|
+
[
|
|
65
|
+
"if (Test-Path -LiteralPath $f) {",
|
|
66
|
+
"$id = [int](Get-Content -Raw -LiteralPath $f | ConvertFrom-Json).pid;",
|
|
67
|
+
"$p = Get-CimInstance Win32_Process -Filter ('ProcessId=' + $id);",
|
|
68
|
+
"if ($p -and $p.CommandLine -match 'box run') { taskkill /pid $id /t /f | Out-Null }",
|
|
69
|
+
"}"
|
|
70
|
+
].join(" ")
|
|
71
|
+
].join("; ");
|
|
72
|
+
}
|
|
73
|
+
var endDaemonStep = (environment) => ({
|
|
74
|
+
command: [
|
|
75
|
+
"powershell",
|
|
76
|
+
"-NoProfile",
|
|
77
|
+
"-NonInteractive",
|
|
78
|
+
"-Command",
|
|
79
|
+
endDaemonScript(runnerStatePath(environment))
|
|
80
|
+
],
|
|
81
|
+
mayFail: true
|
|
82
|
+
});
|
|
83
|
+
function programFor(script, node, npx, version) {
|
|
84
|
+
if (!isRelease(script)) return [node, script, "box", "run"];
|
|
85
|
+
if (!npx)
|
|
86
|
+
return "npx is not on PATH, so the service cannot run Cloop. Install Node.js with npm, which ships npx, and run `cloop connect` again.";
|
|
87
|
+
return [npx, "-y", `@cloop/runner@${version}`, "box", "run"];
|
|
88
|
+
}
|
|
89
|
+
function isRelease(script) {
|
|
90
|
+
const published = (path) => /[\\/](_npx|node_modules)[\\/]/.test(path);
|
|
91
|
+
try {
|
|
92
|
+
return published(realpathSync(script));
|
|
93
|
+
} catch {
|
|
94
|
+
return published(script);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
var NPX = process.platform === "win32" ? "npx.cmd" : "npx";
|
|
98
|
+
function findNpx(execPath = process.execPath, onPath = which(NPX)) {
|
|
99
|
+
const beside = join(dirname(execPath), NPX);
|
|
100
|
+
if (!existsSync(beside)) return onPath;
|
|
101
|
+
const opt = beside.replace(/\/Cellar\/([^/]+)\/[^/]+\//, "/opt/$1/");
|
|
102
|
+
return [onPath, opt].find((path) => path && path !== beside && sameFile(path, beside)) ?? beside;
|
|
103
|
+
}
|
|
104
|
+
function sameFile(a, b) {
|
|
105
|
+
try {
|
|
106
|
+
return realpathSync(a) === realpathSync(b);
|
|
107
|
+
} catch {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
var FIRST_CONNECT_MS = 9e4;
|
|
112
|
+
async function awaitDaemon(since, read = readRunnerState, { timeoutMs = FIRST_CONNECT_MS, pollMs = 500 } = {}) {
|
|
113
|
+
for (let waited = 0; ; waited += pollMs) {
|
|
114
|
+
const state = read();
|
|
115
|
+
if (state && Date.parse(state.connected_at) >= since) return true;
|
|
116
|
+
if (waited >= timeoutMs) return false;
|
|
117
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
var UNIT_ENV = [
|
|
121
|
+
"PATH",
|
|
122
|
+
"CLOOP_BOX_FILE",
|
|
123
|
+
"CLOOP_BOX_THREADS_FILE",
|
|
124
|
+
"CLOOP_LOCAL_RUNS_FILE",
|
|
125
|
+
"CLOOP_UPDATE_DIR",
|
|
126
|
+
"CLOOP_MESH_URL",
|
|
127
|
+
"CLOOP_ORIGIN",
|
|
128
|
+
"T3CODE_HOME"
|
|
129
|
+
];
|
|
130
|
+
function unitEnv(env) {
|
|
131
|
+
const picked = { PATH: "/usr/bin:/bin" };
|
|
132
|
+
const byName = new Map(Object.entries(env).map(([key, value]) => [key.toUpperCase(), value]));
|
|
133
|
+
for (const key of UNIT_ENV) {
|
|
134
|
+
const value = env[key] ?? byName.get(key);
|
|
135
|
+
if (value) picked[key] = value;
|
|
136
|
+
}
|
|
137
|
+
return picked;
|
|
138
|
+
}
|
|
139
|
+
function serviceEnv(env = process.env) {
|
|
140
|
+
const origin = getOrigin();
|
|
141
|
+
return unitEnv({ ...env, CLOOP_ORIGIN: origin, CLOOP_MESH_URL: env.CLOOP_MESH_URL || origin });
|
|
142
|
+
}
|
|
143
|
+
function installedService(opts) {
|
|
144
|
+
const { label, unit, task, file } = serviceIdentity(opts.kind, opts.environment);
|
|
145
|
+
if (opts.platform === "darwin") {
|
|
146
|
+
return {
|
|
147
|
+
path: join(opts.dir ?? join(opts.home, "Library", "LaunchAgents"), `${label}.plist`),
|
|
148
|
+
steps: [{ command: ["launchctl", "bootout", `gui/${opts.uid}/${label}`], mayFail: true }],
|
|
149
|
+
running: ["launchctl", "print", `gui/${opts.uid}/${label}`]
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
if (opts.platform === "win32") {
|
|
153
|
+
return {
|
|
154
|
+
path: join(opts.dir ?? join(opts.home, "AppData", "Local", "Cloop"), `${file}.cmd`),
|
|
155
|
+
steps: [
|
|
156
|
+
{ command: ["schtasks", "/end", "/tn", task], mayFail: true },
|
|
157
|
+
endDaemonStep(opts.environment),
|
|
158
|
+
{ command: ["schtasks", "/delete", "/tn", task, "/f"], mayFail: true }
|
|
159
|
+
],
|
|
160
|
+
running: ["schtasks", "/query", "/tn", task]
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
path: join(opts.dir ?? join(opts.home, ".config", "systemd", "user"), unit),
|
|
165
|
+
steps: [{ command: ["systemctl", "--user", "disable", "--now", unit], mayFail: true }],
|
|
166
|
+
running: ["systemctl", "--user", "is-active", "--quiet", unit]
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function unitFor(opts) {
|
|
170
|
+
const env = Object.entries(opts.env);
|
|
171
|
+
const { label, unit, task, file } = serviceIdentity(opts.kind, opts.environment);
|
|
172
|
+
const retire = installedService({
|
|
173
|
+
...opts,
|
|
174
|
+
kind: opts.kind === "workstation" ? "local" : "workstation"
|
|
175
|
+
});
|
|
176
|
+
if (opts.platform === "darwin") {
|
|
177
|
+
const agents = opts.dir ?? join(opts.home, "Library", "LaunchAgents");
|
|
178
|
+
const path2 = join(agents, `${label}.plist`);
|
|
179
|
+
const log = join(opts.home, "Library", "Logs", `${file}.log`);
|
|
180
|
+
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
181
|
+
const contents2 = [
|
|
182
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
183
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
184
|
+
'<plist version="1.0">',
|
|
185
|
+
"<dict>",
|
|
186
|
+
` <key>Label</key><string>${label}</string>`,
|
|
187
|
+
" <key>ProgramArguments</key>",
|
|
188
|
+
" <array>",
|
|
189
|
+
...opts.program.map((arg) => ` <string>${xml(arg)}</string>`),
|
|
190
|
+
" </array>",
|
|
191
|
+
" <key>EnvironmentVariables</key>",
|
|
192
|
+
` <dict>${env.map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join("")}</dict>`,
|
|
193
|
+
" <key>RunAtLoad</key><true/>",
|
|
194
|
+
" <key>KeepAlive</key><true/>",
|
|
195
|
+
" <key>ThrottleInterval</key><integer>10</integer>",
|
|
196
|
+
` <key>StandardOutPath</key><string>${xml(log)}</string>`,
|
|
197
|
+
` <key>StandardErrorPath</key><string>${xml(log)}</string>`,
|
|
198
|
+
"</dict>",
|
|
199
|
+
"</plist>",
|
|
200
|
+
""
|
|
201
|
+
].join("\n");
|
|
202
|
+
const domain = `gui/${opts.uid}`;
|
|
203
|
+
return {
|
|
204
|
+
path: path2,
|
|
205
|
+
contents: contents2,
|
|
206
|
+
start: [
|
|
207
|
+
{ command: ["launchctl", "bootout", `${domain}/${label}`], mayFail: true },
|
|
208
|
+
{ command: ["launchctl", "bootstrap", domain, path2], tries: 5 }
|
|
209
|
+
],
|
|
210
|
+
retire,
|
|
211
|
+
logs: `tail -f ${log}`,
|
|
212
|
+
tail: ["tail", "-n", "20", log]
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
if (opts.platform === "win32") {
|
|
216
|
+
const dir = opts.dir ?? join(opts.home, "AppData", "Local", "Cloop");
|
|
217
|
+
const path2 = join(dir, `${file}.cmd`);
|
|
218
|
+
const log = join(dir, `${file}.log`);
|
|
219
|
+
const psLog = log.replace(/'/g, "''");
|
|
220
|
+
const contents2 = [
|
|
221
|
+
"@echo off",
|
|
222
|
+
...env.map(([key, value]) => `set "${key}=${cmdValue(value)}"`),
|
|
223
|
+
":run",
|
|
224
|
+
`call ${opts.program.map(cmdWord).join(" ")} >> ${cmdWord(log)} 2>&1`,
|
|
225
|
+
"rem timeout needs a console, and a scheduled task has none.",
|
|
226
|
+
"ping -n 6 127.0.0.1 >nul",
|
|
227
|
+
"goto run",
|
|
228
|
+
""
|
|
229
|
+
].join("\r\n");
|
|
230
|
+
return {
|
|
231
|
+
path: path2,
|
|
232
|
+
contents: contents2,
|
|
233
|
+
start: [
|
|
234
|
+
{ command: ["schtasks", "/end", "/tn", task], mayFail: true },
|
|
235
|
+
endDaemonStep(opts.environment),
|
|
236
|
+
{
|
|
237
|
+
command: [
|
|
238
|
+
"powershell",
|
|
239
|
+
"-NoProfile",
|
|
240
|
+
"-NonInteractive",
|
|
241
|
+
"-Command",
|
|
242
|
+
registerTaskScript(task, path2)
|
|
243
|
+
]
|
|
244
|
+
},
|
|
245
|
+
{ command: ["schtasks", "/run", "/tn", task] }
|
|
246
|
+
],
|
|
247
|
+
retire,
|
|
248
|
+
logs: `Get-Content -Wait '${psLog}'`,
|
|
249
|
+
tail: [
|
|
250
|
+
"powershell",
|
|
251
|
+
"-NoProfile",
|
|
252
|
+
"-NonInteractive",
|
|
253
|
+
"-Command",
|
|
254
|
+
`Get-Content -Tail 20 '${psLog}'`
|
|
255
|
+
]
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
const units = opts.dir ?? join(opts.home, ".config", "systemd", "user");
|
|
259
|
+
const path = join(units, unit);
|
|
260
|
+
const contents = [
|
|
261
|
+
"[Unit]",
|
|
262
|
+
`Description=${task}: answers the Cloop Agent over the mesh`,
|
|
263
|
+
"After=network-online.target",
|
|
264
|
+
// A disconnected runner exits 1 on every start. Three in ten minutes and
|
|
265
|
+
// systemd marks the unit failed instead of restarting it forever.
|
|
266
|
+
"StartLimitIntervalSec=600",
|
|
267
|
+
"StartLimitBurst=3",
|
|
268
|
+
"",
|
|
269
|
+
"[Service]",
|
|
270
|
+
...env.map(([key, value]) => `Environment=${systemdAssignment(`${key}=${value}`)}`),
|
|
271
|
+
`ExecStart=${opts.program.map(systemdWord).join(" ")}`,
|
|
272
|
+
"Restart=always",
|
|
273
|
+
"RestartSec=5",
|
|
274
|
+
"",
|
|
275
|
+
"[Install]",
|
|
276
|
+
"WantedBy=default.target",
|
|
277
|
+
""
|
|
278
|
+
].join("\n");
|
|
279
|
+
return {
|
|
280
|
+
path,
|
|
281
|
+
contents,
|
|
282
|
+
start: [
|
|
283
|
+
{ command: ["systemctl", "--user", "reset-failed", unit], mayFail: true },
|
|
284
|
+
{ command: ["systemctl", "--user", "daemon-reload"] },
|
|
285
|
+
{ command: ["systemctl", "--user", "enable", unit] },
|
|
286
|
+
{ command: ["systemctl", "--user", "restart", unit] }
|
|
287
|
+
],
|
|
288
|
+
retire,
|
|
289
|
+
logs: `journalctl --user -u ${unit} -f`,
|
|
290
|
+
tail: ["journalctl", "--user", "-u", unit, "-n", "20", "--no-pager"]
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
async function runSteps(steps, run = (command) => void execFileSync(command[0], command.slice(1), { stdio: "ignore", timeout: 15e3 }), wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
|
|
294
|
+
for (const step of steps) {
|
|
295
|
+
const tries = step.tries ?? 1;
|
|
296
|
+
for (let attempt = 1; ; attempt++) {
|
|
297
|
+
try {
|
|
298
|
+
run(step.command);
|
|
299
|
+
break;
|
|
300
|
+
} catch (err) {
|
|
301
|
+
if (step.mayFail) break;
|
|
302
|
+
if (attempt >= tries) throw err;
|
|
303
|
+
await wait(1e3);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
var systemServices = {
|
|
309
|
+
platform: process.platform,
|
|
310
|
+
run: (command) => execFileSync(command[0], command.slice(1), {
|
|
311
|
+
encoding: "utf-8",
|
|
312
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
313
|
+
timeout: 15e3,
|
|
314
|
+
...command[0] === "powershell" ? { env: windowsPowerShellEnv() } : {}
|
|
315
|
+
}),
|
|
316
|
+
awaitUp: (since) => awaitDaemon(since)
|
|
317
|
+
};
|
|
318
|
+
async function stopService(service, run, waitMs = 1e4) {
|
|
319
|
+
await runSteps(service.steps, run);
|
|
320
|
+
const until = Date.now() + waitMs;
|
|
321
|
+
for (; ; ) {
|
|
322
|
+
try {
|
|
323
|
+
run(service.running);
|
|
324
|
+
} catch {
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
if (Date.now() >= until) return false;
|
|
328
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
function installedServices(opts, exists = existsSync) {
|
|
332
|
+
return ["local", "workstation"].map((kind) => ({ kind, service: installedService({ ...opts, kind }) })).filter(({ service }) => exists(service.path));
|
|
333
|
+
}
|
|
334
|
+
function unitOrigin(contents) {
|
|
335
|
+
const plist = /<key>CLOOP_ORIGIN<\/key><string>([^<]+)<\/string>/.exec(contents)?.[1];
|
|
336
|
+
if (plist) return plist.replace(/&/g, "&");
|
|
337
|
+
const unit = /Environment="CLOOP_ORIGIN=([^"]+)"/.exec(contents)?.[1];
|
|
338
|
+
if (unit) return unit.replace(/%%/g, "%");
|
|
339
|
+
const launcher = /^set "CLOOP_ORIGIN=(.+)"\r?$/m.exec(contents)?.[1];
|
|
340
|
+
return launcher ? launcher.replace(/%%/g, "%") : null;
|
|
341
|
+
}
|
|
342
|
+
function servicesOrigin(services, read = (path) => readFileSync(path, "utf-8")) {
|
|
343
|
+
return services.map((service) => {
|
|
344
|
+
try {
|
|
345
|
+
return unitOrigin(read(service.path));
|
|
346
|
+
} catch {
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
}).find(Boolean) ?? null;
|
|
350
|
+
}
|
|
351
|
+
function runnerOrigin(env) {
|
|
352
|
+
const installed = installedServices({
|
|
353
|
+
platform: process.platform,
|
|
354
|
+
environment: env,
|
|
355
|
+
home: homedir(),
|
|
356
|
+
uid: process.getuid?.() ?? 0,
|
|
357
|
+
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
358
|
+
});
|
|
359
|
+
return readRunnerConfig(env)?.origin || servicesOrigin(installed.map(({ service }) => service)) || void 0;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// src/legacy-staging.ts
|
|
363
|
+
import { existsSync as existsSync2, mkdirSync, renameSync, rmSync } from "fs";
|
|
364
|
+
import { homedir as homedir2 } from "os";
|
|
365
|
+
import { join as join2 } from "path";
|
|
366
|
+
var MOVED = [
|
|
367
|
+
"box-threads.json",
|
|
368
|
+
"runner-state.json",
|
|
369
|
+
"local-runs.json",
|
|
370
|
+
"runs",
|
|
371
|
+
"takeover",
|
|
372
|
+
"update.json",
|
|
373
|
+
"update.log",
|
|
374
|
+
"box.json"
|
|
375
|
+
];
|
|
376
|
+
function legacyStagingRunner() {
|
|
377
|
+
if (existsSync2(boxPath("staging"))) return false;
|
|
378
|
+
const origin = runnerOrigin("production");
|
|
379
|
+
return origin !== void 0 && environmentOf(origin) === "staging";
|
|
380
|
+
}
|
|
381
|
+
function moveRunnerFiles(from, to) {
|
|
382
|
+
mkdirSync(to, { recursive: true, mode: 448 });
|
|
383
|
+
for (const name of MOVED) {
|
|
384
|
+
const source = join2(from, name);
|
|
385
|
+
const target = join2(to, name);
|
|
386
|
+
if (existsSync2(source) && !existsSync2(target)) renameSync(source, target);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
function legacyServices(platform) {
|
|
390
|
+
return installedServices({
|
|
391
|
+
platform,
|
|
392
|
+
environment: "production",
|
|
393
|
+
home: homedir2(),
|
|
394
|
+
uid: process.getuid?.() ?? 0,
|
|
395
|
+
...process.env.CLOOP_UNIT_DIR ? { dir: process.env.CLOOP_UNIT_DIR } : {}
|
|
396
|
+
}).map(({ service }) => service);
|
|
397
|
+
}
|
|
398
|
+
async function moveLegacyStagingRunner(services) {
|
|
399
|
+
if (!legacyStagingRunner()) return false;
|
|
400
|
+
const run = (command) => void services.run(command);
|
|
401
|
+
const units = legacyServices(services.platform);
|
|
402
|
+
for (const unit of units)
|
|
403
|
+
if (!await stopService(unit, run))
|
|
404
|
+
throw new Error(
|
|
405
|
+
`Could not stop the staging machine in ${unit.path}. Stop it with \`${unit.steps.map((s) => s.command.join(" ")).join(" && ")}\`, then run this again.`
|
|
406
|
+
);
|
|
407
|
+
for (const unit of units) rmSync(unit.path, { force: true });
|
|
408
|
+
moveRunnerFiles(runnerDir("production"), runnerDir("staging"));
|
|
409
|
+
console.error("[runner:environment] moved staging runner from ~/.cloop to ~/.cloop/staging");
|
|
410
|
+
return true;
|
|
411
|
+
}
|
|
412
|
+
async function moveLegacyStagingRunnerBack(where, run) {
|
|
413
|
+
const added = installedService(where);
|
|
414
|
+
if (!await stopService(added, run)) throw new Error(`${added.path} did not stop`);
|
|
415
|
+
rmSync(added.path, { force: true });
|
|
416
|
+
moveRunnerFiles(runnerDir(where.environment), runnerDir("production"));
|
|
417
|
+
}
|
|
418
|
+
async function moveLegacyStagingRunnerOnConnect(attempt, services, connecting, say) {
|
|
419
|
+
attempt.step = "legacy_move";
|
|
420
|
+
try {
|
|
421
|
+
if (await moveLegacyStagingRunner(services)) say(movedLine(connecting));
|
|
422
|
+
} catch (err) {
|
|
423
|
+
throw new ConnectFailure(
|
|
424
|
+
"legacy_move_failed",
|
|
425
|
+
err instanceof Error ? err.message : String(err)
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
function legacyNotConnectedLine() {
|
|
430
|
+
return legacyStagingRunner() ? "This staging machine is still in ~/.cloop from before 0.3.9. Run `cloop connect --staging` to move it to ~/.cloop/staging." : null;
|
|
431
|
+
}
|
|
432
|
+
function movedLine(connecting) {
|
|
433
|
+
const line = "Moved the staging machine from ~/.cloop to ~/.cloop/staging, so a production machine can run beside it.";
|
|
434
|
+
return connecting === "staging" ? line : `${line} It is stopped. Start it again with: cloop connect --staging`;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export {
|
|
438
|
+
cmdWord,
|
|
439
|
+
psQuote,
|
|
440
|
+
programFor,
|
|
441
|
+
isRelease,
|
|
442
|
+
findNpx,
|
|
443
|
+
FIRST_CONNECT_MS,
|
|
444
|
+
awaitDaemon,
|
|
445
|
+
serviceEnv,
|
|
446
|
+
installedService,
|
|
447
|
+
unitFor,
|
|
448
|
+
runSteps,
|
|
449
|
+
systemServices,
|
|
450
|
+
stopService,
|
|
451
|
+
installedServices,
|
|
452
|
+
servicesOrigin,
|
|
453
|
+
runnerOrigin,
|
|
454
|
+
legacyStagingRunner,
|
|
455
|
+
moveLegacyStagingRunner,
|
|
456
|
+
moveLegacyStagingRunnerBack,
|
|
457
|
+
moveLegacyStagingRunnerOnConnect,
|
|
458
|
+
legacyNotConnectedLine
|
|
459
|
+
};
|