@codingfrees/uap-device-control 0.1.5 → 0.1.6
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 +1 -1
- package/dist/uap-device-control.mjs +174 -68
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ You can also provide the origin through `UAP_DEVICE_CONTROL_ORIGIN`.
|
|
|
28
28
|
npx @codingfrees/uap-device-control@latest remote
|
|
29
29
|
```
|
|
30
30
|
|
|
31
|
-
The interactive CLI uses concise human-readable status lines by default (`✅`, `❌`, `⚠️`, `🔐`, `🌐`, `🔌`, `🔧`). Use `--json` for stable JSONL output in scripts and log collectors.
|
|
31
|
+
The interactive CLI uses concise human-readable status lines by default (`✅`, `❌`, `⚠️`, `🔐`, `🌐`, `🔌`, `🔧`). Use `--json` for stable JSONL output in scripts and log collectors. Only one `remote` process may use a state directory at a time; starting a second process with the same device identity fails locally instead of replacing the live broker session. OAuth refresh is serialized across processes, and access-token renewal is retried in the existing broker session rather than forcing a device reconnect.
|
|
32
32
|
|
|
33
33
|
By default the Remote process also starts the loopback-only semantic browser bridge on port `8800`. Until the UAP Browser Extension is paired, the CLI prints a short-lived pairing code. Browser control can be disabled with `--no-browser-control` or moved to another loopback port with `--browser-port <port>`.
|
|
34
34
|
|
|
@@ -128,6 +128,66 @@ async function saveRemoteAuth(stateDirectory, value) {
|
|
|
128
128
|
async function clearRemoteAuth(stateDirectory) {
|
|
129
129
|
await rm(path.join(stateDirectory, "auth.json"), { force: true });
|
|
130
130
|
}
|
|
131
|
+
function acquireRemoteProcessLock(stateDirectory) {
|
|
132
|
+
return acquireStateLock(stateDirectory, "remote.lock", 0, "another UAP Device Control remote process is already running for this state directory");
|
|
133
|
+
}
|
|
134
|
+
async function withRemoteAuthRefreshLock(stateDirectory, task) {
|
|
135
|
+
const lease = await acquireStateLock(stateDirectory, "auth-refresh.lock", 2e4, "Device Control authorization refresh is busy");
|
|
136
|
+
try {
|
|
137
|
+
return await task();
|
|
138
|
+
} finally {
|
|
139
|
+
await lease.release();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async function acquireStateLock(stateDirectory, name, waitMs, busyMessage) {
|
|
143
|
+
await mkdir(stateDirectory, { recursive: true, mode: 448 });
|
|
144
|
+
const file = path.join(stateDirectory, name);
|
|
145
|
+
const owner = { pid: process.pid, token: randomUUID(), createdAt: Date.now() };
|
|
146
|
+
const deadline = Date.now() + waitMs;
|
|
147
|
+
for (; ; ) {
|
|
148
|
+
try {
|
|
149
|
+
await writeFile(file, JSON.stringify(owner), { encoding: "utf8", flag: "wx", mode: 384 });
|
|
150
|
+
return { release: () => removeOwnedLock(file, owner.token) };
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (!exists(error)) throw error;
|
|
153
|
+
}
|
|
154
|
+
const current = await readLock(file);
|
|
155
|
+
if (!current) throw new TypeError("Device Control state lock is invalid: " + file);
|
|
156
|
+
if (!processAlive(current.pid)) {
|
|
157
|
+
await removeOwnedLock(file, current.token);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (Date.now() >= deadline) throw new TypeError(busyMessage);
|
|
161
|
+
await sleep(25);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async function readLock(file) {
|
|
165
|
+
try {
|
|
166
|
+
const raw = JSON.parse(await readFile(file, "utf8"));
|
|
167
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
168
|
+
const value = raw;
|
|
169
|
+
if (!Number.isSafeInteger(value.pid) || Number(value.pid) < 1 || typeof value.token !== "string" || !/^[0-9a-f-]{36}$/.test(value.token) || !Number.isSafeInteger(value.createdAt)) return void 0;
|
|
170
|
+
return { pid: Number(value.pid), token: value.token, createdAt: Number(value.createdAt) };
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (missing(error)) return void 0;
|
|
173
|
+
return void 0;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async function removeOwnedLock(file, token) {
|
|
177
|
+
const current = await readLock(file);
|
|
178
|
+
if (current?.token === token) await rm(file, { force: true });
|
|
179
|
+
}
|
|
180
|
+
function processAlive(pid) {
|
|
181
|
+
try {
|
|
182
|
+
process.kill(pid, 0);
|
|
183
|
+
return true;
|
|
184
|
+
} catch (error) {
|
|
185
|
+
return !Boolean(error && typeof error === "object" && "code" in error && error.code === "ESRCH");
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function sleep(ms) {
|
|
189
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
190
|
+
}
|
|
131
191
|
function missing(error) {
|
|
132
192
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
133
193
|
}
|
|
@@ -186,27 +246,30 @@ async function loginDeviceControl(origin, stateDirectory, options = {}) {
|
|
|
186
246
|
}
|
|
187
247
|
}
|
|
188
248
|
async function accessToken(stateDirectory, fetcher = fetch, forceRefresh = false) {
|
|
189
|
-
const
|
|
190
|
-
if (!
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
249
|
+
const observed = await requiredDeviceAuth(stateDirectory);
|
|
250
|
+
if (!forceRefresh && usableAccessToken(observed)) return { auth: observed, token: observed.accessToken };
|
|
251
|
+
return withRemoteAuthRefreshLock(stateDirectory, async () => {
|
|
252
|
+
const auth = await requiredDeviceAuth(stateDirectory);
|
|
253
|
+
const refreshedElsewhere = authorizationChanged(observed, auth);
|
|
254
|
+
if (usableAccessToken(auth) && (!forceRefresh || refreshedElsewhere)) return { auth, token: auth.accessToken };
|
|
255
|
+
const tokenEndpoint = new URL("/oauth/token", auth.origin);
|
|
256
|
+
const token = await json(
|
|
257
|
+
fetcher(tokenEndpoint, {
|
|
258
|
+
method: "POST",
|
|
259
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
260
|
+
body: new URLSearchParams({ grant_type: "refresh_token", client_id: auth.clientId, refresh_token: auth.refreshToken, resource: auth.origin + "/mcp" })
|
|
261
|
+
})
|
|
262
|
+
);
|
|
263
|
+
const next = {
|
|
264
|
+
...auth,
|
|
265
|
+
refreshToken: text(token.refresh_token, "OAuth refresh token"),
|
|
266
|
+
accessToken: text(token.access_token, "OAuth access token"),
|
|
267
|
+
accessExpiresAt: Date.now() + integer(token.expires_in, "OAuth expiry") * 1e3,
|
|
268
|
+
scope: typeof token.scope === "string" ? token.scope : auth.scope
|
|
269
|
+
};
|
|
270
|
+
await saveRemoteAuth(stateDirectory, next);
|
|
271
|
+
return { auth: next, token: next.accessToken };
|
|
272
|
+
});
|
|
210
273
|
}
|
|
211
274
|
async function logoutDeviceControl(stateDirectory, fetcher = fetch) {
|
|
212
275
|
const auth = await loadRemoteAuth(stateDirectory);
|
|
@@ -286,6 +349,18 @@ async function openBrowser(url) {
|
|
|
286
349
|
const launch = browserOpenCommand(process.platform, url);
|
|
287
350
|
await execute(launch.command, launch.args, { windowsHide: true });
|
|
288
351
|
}
|
|
352
|
+
async function requiredDeviceAuth(stateDirectory) {
|
|
353
|
+
const auth = await loadRemoteAuth(stateDirectory);
|
|
354
|
+
if (!auth) throw new TypeError("not logged in");
|
|
355
|
+
if (!auth.scope.split(" ").includes("device-control:device")) throw new TypeError("device authorization is required; run login again");
|
|
356
|
+
return auth;
|
|
357
|
+
}
|
|
358
|
+
function usableAccessToken(auth) {
|
|
359
|
+
return Boolean(auth.accessToken && auth.accessExpiresAt && auth.accessExpiresAt > Date.now() + 3e4);
|
|
360
|
+
}
|
|
361
|
+
function authorizationChanged(before, after) {
|
|
362
|
+
return before.accessToken !== after.accessToken || before.accessExpiresAt !== after.accessExpiresAt || before.refreshToken !== after.refreshToken;
|
|
363
|
+
}
|
|
289
364
|
async function json(response) {
|
|
290
365
|
const value = await response;
|
|
291
366
|
if (!value.ok) {
|
|
@@ -1641,15 +1716,17 @@ async function runRemote(options) {
|
|
|
1641
1716
|
delay = 500;
|
|
1642
1717
|
continue;
|
|
1643
1718
|
}
|
|
1644
|
-
if (error instanceof RemoteAuthorizationError)
|
|
1645
|
-
options.log?.({ event: "remote.session", status: "reauthorizing", deviceId });
|
|
1646
|
-
await accessToken(options.stateDirectory, fetcher, true);
|
|
1647
|
-
delay = 500;
|
|
1648
|
-
continue;
|
|
1649
|
-
}
|
|
1719
|
+
if (error instanceof RemoteAuthorizationError) throw new TypeError("Device Control authorization was rejected after refresh; run login again");
|
|
1650
1720
|
if (!(error instanceof RemoteUnavailableError)) throw error;
|
|
1651
|
-
options.log?.({
|
|
1652
|
-
|
|
1721
|
+
options.log?.({
|
|
1722
|
+
event: "remote.session",
|
|
1723
|
+
status: "reconnecting",
|
|
1724
|
+
deviceId,
|
|
1725
|
+
retryMs: delay,
|
|
1726
|
+
...error.httpStatus === void 0 ? {} : { httpStatus: error.httpStatus },
|
|
1727
|
+
...error.pathname === void 0 ? {} : { pathname: error.pathname }
|
|
1728
|
+
});
|
|
1729
|
+
await sleep2(delay, options.signal);
|
|
1653
1730
|
delay = Math.min(delay * 2, 15e3);
|
|
1654
1731
|
} finally {
|
|
1655
1732
|
refreshSession = () => {
|
|
@@ -1662,34 +1739,39 @@ async function runRemote(options) {
|
|
|
1662
1739
|
}
|
|
1663
1740
|
}
|
|
1664
1741
|
async function remoteSession(origin, stateDirectory, engine, fetcher = fetch, signal, log) {
|
|
1665
|
-
const
|
|
1666
|
-
const
|
|
1742
|
+
const deviceId = engine.options.deviceId;
|
|
1743
|
+
const invoke2 = (pathname, body, requestSignal = signal, timeoutMs = 15e3, requestLog = log) => authorizedRequest(fetcher, origin, stateDirectory, pathname, body, requestSignal, timeoutMs, requestLog, deviceId);
|
|
1744
|
+
const connected = await invoke2("/device-control/remote/connect", { device: engine.info() });
|
|
1667
1745
|
const sessionId = bounded2(connected.sessionId, "remote session id");
|
|
1668
|
-
log?.({ event: "remote.session", status: "connected", deviceId
|
|
1746
|
+
log?.({ event: "remote.session", status: "connected", deviceId });
|
|
1669
1747
|
try {
|
|
1670
1748
|
while (!signal?.aborted) {
|
|
1671
|
-
const next = await
|
|
1749
|
+
const next = await invoke2("/device-control/remote/poll", { sessionId, deviceId }, signal, 35e3);
|
|
1672
1750
|
if (next.notice !== void 0) log?.({ event: "plugin.tool", ...noticeValue(next.notice) });
|
|
1673
1751
|
if (next.command === null || next.command === void 0) continue;
|
|
1674
1752
|
const command = commandValue(next.command);
|
|
1675
1753
|
const startedAt = Date.now();
|
|
1676
1754
|
try {
|
|
1677
1755
|
const output = await engine.execute(command.capability, command.parameters, { workspaceId: bounded2(next.workspaceId, "workspace id") });
|
|
1678
|
-
await
|
|
1756
|
+
await invoke2("/device-control/remote/result", { sessionId, deviceId, requestId: command.requestId, ok: true, output, executionMs: elapsed(startedAt) });
|
|
1679
1757
|
} catch (error) {
|
|
1680
|
-
await
|
|
1681
|
-
fetcher,
|
|
1682
|
-
origin,
|
|
1683
|
-
"/device-control/remote/result",
|
|
1684
|
-
token,
|
|
1685
|
-
{ sessionId, deviceId: engine.options.deviceId, requestId: command.requestId, ok: false, error: safeError(error), executionMs: elapsed(startedAt) },
|
|
1686
|
-
signal
|
|
1687
|
-
);
|
|
1758
|
+
await invoke2("/device-control/remote/result", { sessionId, deviceId, requestId: command.requestId, ok: false, error: safeError(error), executionMs: elapsed(startedAt) });
|
|
1688
1759
|
}
|
|
1689
1760
|
}
|
|
1690
1761
|
} finally {
|
|
1691
|
-
await
|
|
1692
|
-
log?.({ event: "remote.session", status: "disconnected", deviceId
|
|
1762
|
+
await invoke2("/device-control/remote/disconnect", { sessionId, deviceId }, void 0, 5e3, void 0).catch(() => void 0);
|
|
1763
|
+
log?.({ event: "remote.session", status: "disconnected", deviceId });
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
async function authorizedRequest(fetcher, origin, stateDirectory, pathname, body, signal, timeoutMs = 15e3, log, deviceId) {
|
|
1767
|
+
const current = await accessToken(stateDirectory, fetcher);
|
|
1768
|
+
try {
|
|
1769
|
+
return await request(fetcher, origin, pathname, current.token, body, signal, timeoutMs);
|
|
1770
|
+
} catch (error) {
|
|
1771
|
+
if (!(error instanceof RemoteAuthorizationError)) throw error;
|
|
1772
|
+
log?.({ event: "remote.session", status: "reauthorizing", ...deviceId ? { deviceId } : {}, httpStatus: error.httpStatus, pathname: error.pathname });
|
|
1773
|
+
const refreshed = await accessToken(stateDirectory, fetcher, true);
|
|
1774
|
+
return request(fetcher, origin, pathname, refreshed.token, body, signal, timeoutMs);
|
|
1693
1775
|
}
|
|
1694
1776
|
}
|
|
1695
1777
|
async function request(fetcher, origin, pathname, token, body, signal, timeoutMs = 15e3) {
|
|
@@ -1709,10 +1791,10 @@ async function request(fetcher, origin, pathname, token, body, signal, timeoutMs
|
|
|
1709
1791
|
signal: controller.signal
|
|
1710
1792
|
});
|
|
1711
1793
|
} catch {
|
|
1712
|
-
throw new RemoteUnavailableError();
|
|
1794
|
+
throw new RemoteUnavailableError(void 0, pathname);
|
|
1713
1795
|
}
|
|
1714
|
-
if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError();
|
|
1715
|
-
if (!response.ok) throw new RemoteUnavailableError();
|
|
1796
|
+
if (response.status === 401 || response.status === 403) throw new RemoteAuthorizationError(response.status, pathname);
|
|
1797
|
+
if (!response.ok) throw new RemoteUnavailableError(response.status, pathname);
|
|
1716
1798
|
const raw = await response.json();
|
|
1717
1799
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new TypeError("remote response is invalid");
|
|
1718
1800
|
return raw;
|
|
@@ -1733,8 +1815,22 @@ function defaultRemoteRoots(cwd = process.cwd()) {
|
|
|
1733
1815
|
return [{ id: "cwd", label: "Current directory", path: path4.resolve(cwd), readOnly: false }];
|
|
1734
1816
|
}
|
|
1735
1817
|
var RemoteUnavailableError = class extends Error {
|
|
1818
|
+
constructor(httpStatus, pathname) {
|
|
1819
|
+
super("remote endpoint is unavailable");
|
|
1820
|
+
this.httpStatus = httpStatus;
|
|
1821
|
+
this.pathname = pathname;
|
|
1822
|
+
}
|
|
1823
|
+
httpStatus;
|
|
1824
|
+
pathname;
|
|
1736
1825
|
};
|
|
1737
1826
|
var RemoteAuthorizationError = class extends Error {
|
|
1827
|
+
constructor(httpStatus, pathname) {
|
|
1828
|
+
super("remote authorization was rejected");
|
|
1829
|
+
this.httpStatus = httpStatus;
|
|
1830
|
+
this.pathname = pathname;
|
|
1831
|
+
}
|
|
1832
|
+
httpStatus;
|
|
1833
|
+
pathname;
|
|
1738
1834
|
};
|
|
1739
1835
|
function canonicalOrigin2(value) {
|
|
1740
1836
|
const url = new URL(value);
|
|
@@ -1775,7 +1871,7 @@ function elapsed(startedAt) {
|
|
|
1775
1871
|
function safeError(error) {
|
|
1776
1872
|
return error instanceof TypeError ? error.message.slice(0, 256) : "device operation failed";
|
|
1777
1873
|
}
|
|
1778
|
-
function
|
|
1874
|
+
function sleep2(ms, signal) {
|
|
1779
1875
|
return new Promise((resolve) => {
|
|
1780
1876
|
const timer = setTimeout(resolve, ms);
|
|
1781
1877
|
const abort = () => {
|
|
@@ -1936,25 +2032,30 @@ async function runDeviceControlCli(args = process.argv.slice(2)) {
|
|
|
1936
2032
|
output({ status: "installed", ...await installRemoteService(resolvedOrigin, config.stateDirectory) });
|
|
1937
2033
|
return;
|
|
1938
2034
|
}
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
2035
|
+
const lease = await acquireRemoteProcessLock(config.stateDirectory);
|
|
2036
|
+
try {
|
|
2037
|
+
if (!existingAuth) {
|
|
2038
|
+
if (config.service) throw new TypeError("service mode requires login");
|
|
2039
|
+
await loginDeviceControl(resolvedOrigin, config.stateDirectory);
|
|
2040
|
+
}
|
|
2041
|
+
const controller = new AbortController();
|
|
2042
|
+
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
|
|
2043
|
+
const remoteOrigin = resolvedOrigin;
|
|
2044
|
+
output({ status: "connecting", origin: remoteOrigin, platform: process.platform });
|
|
2045
|
+
await runRemote({
|
|
2046
|
+
origin: remoteOrigin,
|
|
2047
|
+
stateDirectory: config.stateDirectory,
|
|
2048
|
+
roots: config.roots,
|
|
2049
|
+
allowedExecutables: config.allowedExecutables,
|
|
2050
|
+
allowedServices: config.allowedServices,
|
|
2051
|
+
browserControl: config.browserControl,
|
|
2052
|
+
browserPort: config.browserPort,
|
|
2053
|
+
signal: controller.signal,
|
|
2054
|
+
log: output
|
|
2055
|
+
});
|
|
2056
|
+
} finally {
|
|
2057
|
+
await lease.release();
|
|
1942
2058
|
}
|
|
1943
|
-
const controller = new AbortController();
|
|
1944
|
-
for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => controller.abort());
|
|
1945
|
-
const remoteOrigin = resolvedOrigin;
|
|
1946
|
-
output({ status: "connecting", origin: remoteOrigin, platform: process.platform });
|
|
1947
|
-
await runRemote({
|
|
1948
|
-
origin: remoteOrigin,
|
|
1949
|
-
stateDirectory: config.stateDirectory,
|
|
1950
|
-
roots: config.roots,
|
|
1951
|
-
allowedExecutables: config.allowedExecutables,
|
|
1952
|
-
allowedServices: config.allowedServices,
|
|
1953
|
-
browserControl: config.browserControl,
|
|
1954
|
-
browserPort: config.browserPort,
|
|
1955
|
-
signal: controller.signal,
|
|
1956
|
-
log: output
|
|
1957
|
-
});
|
|
1958
2059
|
}
|
|
1959
2060
|
function formatCliEvent(event, json2 = false) {
|
|
1960
2061
|
if (json2) return JSON.stringify(event);
|
|
@@ -1977,8 +2078,8 @@ function formatCliEvent(event, json2 = false) {
|
|
|
1977
2078
|
if (event.event === "remote.session") {
|
|
1978
2079
|
if (status === "connected") return "\u2705 Device connected \xB7 " + String(event.deviceId);
|
|
1979
2080
|
if (status === "disconnected") return "\u{1F50C} Device disconnected \xB7 " + String(event.deviceId);
|
|
1980
|
-
if (status === "reconnecting") return "\u26A0\uFE0F Connection interrupted \xB7 retrying in " + String(event.retryMs) + " ms";
|
|
1981
|
-
if (status === "reauthorizing") return "\u{1F510} Refreshing Device Control authorization";
|
|
2081
|
+
if (status === "reconnecting") return "\u26A0\uFE0F Connection interrupted" + httpDetail(event) + " \xB7 retrying in " + String(event.retryMs) + " ms";
|
|
2082
|
+
if (status === "reauthorizing") return "\u{1F510} Refreshing Device Control authorization" + httpDetail(event);
|
|
1982
2083
|
}
|
|
1983
2084
|
if (status === "connecting") return "\u{1F310} Connecting to " + String(event.origin) + " \xB7 " + String(event.platform);
|
|
1984
2085
|
if (status === "authenticated") return "\u2705 Authenticated \xB7 " + String(event.origin);
|
|
@@ -1988,6 +2089,11 @@ function formatCliEvent(event, json2 = false) {
|
|
|
1988
2089
|
if ("authenticated" in event) return (event.authenticated ? "\u2705" : "\u26A0\uFE0F") + " Device " + String(event.deviceId) + " \xB7 " + String(event.origin) + " \xB7 remote=" + JSON.stringify(event.remote);
|
|
1989
2090
|
return "\u2139\uFE0F " + JSON.stringify(event);
|
|
1990
2091
|
}
|
|
2092
|
+
function httpDetail(event) {
|
|
2093
|
+
const status = Number(event.httpStatus);
|
|
2094
|
+
const pathname = typeof event.pathname === "string" && /^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]{1,255}$/.test(event.pathname) ? event.pathname : "";
|
|
2095
|
+
return Number.isInteger(status) && status >= 100 && status <= 599 ? " \xB7 HTTP " + status + (pathname ? " " + pathname : "") : pathname ? " \xB7 " + pathname : "";
|
|
2096
|
+
}
|
|
1991
2097
|
function resolveConfiguredOrigin(explicit, stored) {
|
|
1992
2098
|
if (explicit && stored && explicit !== stored) throw new TypeError("configured origin does not match the authenticated origin; logout before changing environments");
|
|
1993
2099
|
return explicit ?? stored ?? DEFAULT_DEVICE_CONTROL_ORIGIN;
|