@ainecto/mcp 0.15.0 → 0.15.2
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/bin/ainecto.js +831 -602
- package/dist/bin/ainecto.js.map +1 -1
- package/dist/bin/mcp.js +10 -7
- package/dist/bin/mcp.js.map +1 -1
- package/package.json +2 -2
package/dist/bin/ainecto.js
CHANGED
|
@@ -5541,6 +5541,19 @@ function tokenKey(endpoint) {
|
|
|
5541
5541
|
return createHash("sha256").update(endpoint).digest("hex");
|
|
5542
5542
|
}
|
|
5543
5543
|
|
|
5544
|
+
// src/core/async/stopSignals.ts
|
|
5545
|
+
var STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
5546
|
+
function onStopSignals(handler) {
|
|
5547
|
+
for (const signal of STOP_SIGNALS) {
|
|
5548
|
+
process.on(signal, handler);
|
|
5549
|
+
}
|
|
5550
|
+
return () => {
|
|
5551
|
+
for (const signal of STOP_SIGNALS) {
|
|
5552
|
+
process.off(signal, handler);
|
|
5553
|
+
}
|
|
5554
|
+
};
|
|
5555
|
+
}
|
|
5556
|
+
|
|
5544
5557
|
// src/core/auth/oauth.ts
|
|
5545
5558
|
import { createHash as createHash3, randomBytes } from "crypto";
|
|
5546
5559
|
import { createServer } from "http";
|
|
@@ -5686,8 +5699,8 @@ function legacyRoleInput(flag, envVars = process.env) {
|
|
|
5686
5699
|
|
|
5687
5700
|
// src/core/version.ts
|
|
5688
5701
|
var UNBUNDLED_VERSION = "dev";
|
|
5689
|
-
var CLI_VERSION = true ? "0.15.
|
|
5690
|
-
var CLI_BUILD = true ? "
|
|
5702
|
+
var CLI_VERSION = true ? "0.15.2" : UNBUNDLED_VERSION;
|
|
5703
|
+
var CLI_BUILD = true ? "cdf776d" : void 0;
|
|
5691
5704
|
function cliVersionLabel(version, build, release2) {
|
|
5692
5705
|
return release2 || build === void 0 ? version : `${version}-dev+${build}`;
|
|
5693
5706
|
}
|
|
@@ -6606,19 +6619,22 @@ function launchBrowser(url, deps = {}) {
|
|
|
6606
6619
|
reject(unavailable(error instanceof Error ? error.message : String(error)));
|
|
6607
6620
|
return;
|
|
6608
6621
|
}
|
|
6609
|
-
|
|
6622
|
+
const settle = (finish) => {
|
|
6623
|
+
child.unref();
|
|
6624
|
+
finish();
|
|
6625
|
+
};
|
|
6626
|
+
child.once("error", (error) => settle(() => reject(unavailable(error.message))));
|
|
6610
6627
|
if (platform === "win32") {
|
|
6611
|
-
child.once("spawn", () => resolve4
|
|
6628
|
+
child.once("spawn", () => settle(resolve4));
|
|
6612
6629
|
} else {
|
|
6613
6630
|
child.once("exit", (code, signal) => {
|
|
6614
6631
|
if (code === 0) {
|
|
6615
|
-
resolve4
|
|
6632
|
+
settle(resolve4);
|
|
6616
6633
|
} else {
|
|
6617
|
-
reject(unavailable(code === null ? `stopped by ${signal ?? "a signal"}` : `exited with code ${code}`));
|
|
6634
|
+
settle(() => reject(unavailable(code === null ? `stopped by ${signal ?? "a signal"}` : `exited with code ${code}`)));
|
|
6618
6635
|
}
|
|
6619
6636
|
});
|
|
6620
6637
|
}
|
|
6621
|
-
child.unref();
|
|
6622
6638
|
});
|
|
6623
6639
|
}
|
|
6624
6640
|
function openBrowser(url) {
|
|
@@ -10145,6 +10161,13 @@ function runQuiet(file, args) {
|
|
|
10145
10161
|
execFile(file, [...args], { windowsHide: true }, (error) => error ? reject(error) : resolve4());
|
|
10146
10162
|
});
|
|
10147
10163
|
}
|
|
10164
|
+
function endedFromOutside(exitCode2, signal, platform = process.platform) {
|
|
10165
|
+
if (signal !== 0) return true;
|
|
10166
|
+
return platform === "win32" && exitCode2 !== 0;
|
|
10167
|
+
}
|
|
10168
|
+
function controllingTerminal(platform = process.platform) {
|
|
10169
|
+
return platform === "win32" ? { input: "\\\\.\\CONIN$", inputFlags: "r+", output: "\\\\.\\CONOUT$", outputFlags: "r+" } : { input: "/dev/tty", inputFlags: "r", output: "/dev/tty", outputFlags: "w" };
|
|
10170
|
+
}
|
|
10148
10171
|
function notifyTool(platform = process.platform) {
|
|
10149
10172
|
if (platform === "darwin") {
|
|
10150
10173
|
return {
|
|
@@ -10165,10 +10188,29 @@ function notifyTool(platform = process.platform) {
|
|
|
10165
10188
|
if (platform === "linux") {
|
|
10166
10189
|
return { name: "notify-send", file: "notify-send", args: (title, body) => ["--", title, body] };
|
|
10167
10190
|
}
|
|
10191
|
+
if (platform === "win32") {
|
|
10192
|
+
return { name: "powershell", file: "powershell.exe", args: (title, body) => ["-NoProfile", "-NonInteractive", "-EncodedCommand", windowsToastScript(title, body)] };
|
|
10193
|
+
}
|
|
10168
10194
|
return void 0;
|
|
10169
10195
|
}
|
|
10196
|
+
function windowsToastScript(title, body) {
|
|
10197
|
+
const b64 = (text2) => Buffer.from(text2, "utf8").toString("base64");
|
|
10198
|
+
const script = [
|
|
10199
|
+
"$ErrorActionPreference = 'Stop'",
|
|
10200
|
+
`$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title)}'))`,
|
|
10201
|
+
`$b = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(body)}'))`,
|
|
10202
|
+
"[void][Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]",
|
|
10203
|
+
"$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)",
|
|
10204
|
+
"$n = $x.GetElementsByTagName('text')",
|
|
10205
|
+
"[void]$n.Item(0).AppendChild($x.CreateTextNode($t))",
|
|
10206
|
+
"[void]$n.Item(1).AppendChild($x.CreateTextNode($b))",
|
|
10207
|
+
"$app = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'",
|
|
10208
|
+
"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show([Windows.UI.Notifications.ToastNotification]::new($x))"
|
|
10209
|
+
].join("\n");
|
|
10210
|
+
return Buffer.from(script, "utf16le").toString("base64");
|
|
10211
|
+
}
|
|
10170
10212
|
function notificationHint(platform = process.platform) {
|
|
10171
|
-
return platform === "darwin" ? "macOS: allow notifications for \xABScript Editor\xBB (System Settings \u203A Notifications) so this PC can alert you when a browser
|
|
10213
|
+
return platform === "darwin" ? "macOS: allow notifications for \xABScript Editor\xBB (System Settings \u203A Notifications) so this PC can alert you when a browser is registered or opens a terminal here." : void 0;
|
|
10172
10214
|
}
|
|
10173
10215
|
|
|
10174
10216
|
// src/core/setup/accountSummary.ts
|
|
@@ -12819,12 +12861,13 @@ var TermDaemon = class {
|
|
|
12819
12861
|
}
|
|
12820
12862
|
}
|
|
12821
12863
|
/**
|
|
12822
|
-
* 세션이 스스로 끝났다. ★매니페스트에서 지우는 것은
|
|
12823
|
-
* 시스템이 보낸 SIGTERM·SIGHUP 포함)은 `restore` 가 다시 띄울 수 있게
|
|
12864
|
+
* 세션이 스스로 끝났다. ★매니페스트에서 지우는 것은 «바깥 사정 없이» 끝났을 때만이다 — 신호로 끝난 세션(재부팅·로그아웃 때
|
|
12865
|
+
* 시스템이 보낸 SIGTERM·SIGHUP 포함 · Windows 는 콘솔 닫힘 끝 코드 — launch.endedFromOutside)은 `restore` 가 다시 띄울 수 있게
|
|
12866
|
+
* 남긴다. kill 로 지운 세션은 이미 표에 없다.
|
|
12824
12867
|
*/
|
|
12825
12868
|
sessionEnded(session, exitCode2, signal) {
|
|
12826
12869
|
const current = this.sessions.get(session.name) === session;
|
|
12827
|
-
const kept = current && signal
|
|
12870
|
+
const kept = current && endedFromOutside(exitCode2, signal);
|
|
12828
12871
|
if (current) {
|
|
12829
12872
|
this.sessions.delete(session.name);
|
|
12830
12873
|
if (!kept) {
|
|
@@ -14794,12 +14837,16 @@ async function release(lockPath, token) {
|
|
|
14794
14837
|
}
|
|
14795
14838
|
|
|
14796
14839
|
// src/core/term/e2e.ts
|
|
14797
|
-
import { webcrypto } from "crypto";
|
|
14840
|
+
import { timingSafeEqual as timingSafeEqual2, webcrypto } from "crypto";
|
|
14798
14841
|
var subtle = webcrypto.subtle;
|
|
14799
14842
|
var VERSION = "ainecto-e2e-v1";
|
|
14800
14843
|
var PAIR_LABEL = "ainecto-pair-v1";
|
|
14801
14844
|
var PAIR_DONE_LABEL = "ainecto-pair-v1/done";
|
|
14802
14845
|
var PAIR_CODE_INFO = { a: "ainecto-pair-code-A", b: "ainecto-pair-code-B" };
|
|
14846
|
+
var REGISTER_INFO = { browser: "ainecto-register-v1 browser", pc: "ainecto-register-v1 pc", account: "ainecto-register-v1 account" };
|
|
14847
|
+
var REGISTER_OFFER_LABEL = "ainecto-register-v1/offer";
|
|
14848
|
+
var REGISTER_REVEAL_LABEL = "ainecto-register-v1/reveal";
|
|
14849
|
+
var REGISTER_TAG_BYTES = 8;
|
|
14803
14850
|
var KEY_INFO = { browserToPc: "ainecto-e2e-v1 b2p", pcToBrowser: "ainecto-e2e-v1 p2b", connId: "ainecto-e2e-v1 conn-id" };
|
|
14804
14851
|
var PAIR_CODE_LIMIT = 4294e6;
|
|
14805
14852
|
var MAX_MESSAGES_PER_KEY = 2 ** 32;
|
|
@@ -14985,7 +15032,7 @@ async function pairCodes(transcript) {
|
|
|
14985
15032
|
const block = new Uint8Array(await subtle.sign("HMAC", prk, concatBytes(utf8(info), Uint8Array.of(1))));
|
|
14986
15033
|
const value = pairCodeFromBlock(block);
|
|
14987
15034
|
if (value === void 0) {
|
|
14988
|
-
throw new E2eError("E2E_PAIR_CODE_UNAVAILABLE", "No usable
|
|
15035
|
+
throw new E2eError("E2E_PAIR_CODE_UNAVAILABLE", "No usable registration code in this attempt \u2014 run `ainecto pair` again.");
|
|
14989
15036
|
}
|
|
14990
15037
|
return value;
|
|
14991
15038
|
};
|
|
@@ -14995,6 +15042,48 @@ function pairDoneInput(transcript) {
|
|
|
14995
15042
|
expectLength("transcript", transcript, 32);
|
|
14996
15043
|
return enc(PAIR_DONE_LABEL, transcript);
|
|
14997
15044
|
}
|
|
15045
|
+
async function registerKeys(secret) {
|
|
15046
|
+
expectLength("register secret", secret, NONCE_SEED_BYTES);
|
|
15047
|
+
const ikm = await subtle.importKey("raw", secret, "HKDF", false, ["deriveBits"]);
|
|
15048
|
+
const derive = async (info) => new Uint8Array(await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: utf8(info) }, ikm, 256));
|
|
15049
|
+
return { browser: await derive(REGISTER_INFO.browser), pc: await derive(REGISTER_INFO.pc), account: await derive(REGISTER_INFO.account) };
|
|
15050
|
+
}
|
|
15051
|
+
async function hmac(key, data) {
|
|
15052
|
+
expectLength("mac key", key, 32);
|
|
15053
|
+
const imported = await subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
15054
|
+
return new Uint8Array(await subtle.sign("HMAC", imported, data));
|
|
15055
|
+
}
|
|
15056
|
+
async function registerOfferMac(browserKey, input) {
|
|
15057
|
+
expectLength("commit", input.commit, 32);
|
|
15058
|
+
expectLength("browserPub", input.browserPublicRaw, PUBLIC_KEY_BYTES);
|
|
15059
|
+
expectLength("nB", input.nB, NONCE_SEED_BYTES);
|
|
15060
|
+
return await hmac(browserKey, enc(
|
|
15061
|
+
REGISTER_OFFER_LABEL,
|
|
15062
|
+
input.userId,
|
|
15063
|
+
input.pcId,
|
|
15064
|
+
input.attemptId,
|
|
15065
|
+
input.commit,
|
|
15066
|
+
input.browserPublicRaw,
|
|
15067
|
+
input.keyId,
|
|
15068
|
+
input.nB,
|
|
15069
|
+
input.name
|
|
15070
|
+
));
|
|
15071
|
+
}
|
|
15072
|
+
async function registerRevealMac(pcKey, input) {
|
|
15073
|
+
expectLength("transcript", input.transcript, 32);
|
|
15074
|
+
return await hmac(pcKey, enc(REGISTER_REVEAL_LABEL, input.transcript, input.attemptId));
|
|
15075
|
+
}
|
|
15076
|
+
async function registerTag(accountKey2, userId) {
|
|
15077
|
+
return base64url((await hmac(accountKey2, utf8(userId))).subarray(0, REGISTER_TAG_BYTES));
|
|
15078
|
+
}
|
|
15079
|
+
var REGISTER_PATH = "/api/v1/public/term-register";
|
|
15080
|
+
function registerFragment(input) {
|
|
15081
|
+
expectLength("register secret", input.secret, NONCE_SEED_BYTES);
|
|
15082
|
+
return `1.${input.pcId}.${input.tag}.${base64url(input.secret)}`;
|
|
15083
|
+
}
|
|
15084
|
+
function macEquals(a, b) {
|
|
15085
|
+
return a.length === b.length && timingSafeEqual2(a, b);
|
|
15086
|
+
}
|
|
14998
15087
|
function assertHello(hello) {
|
|
14999
15088
|
expectUserId(hello.userId);
|
|
15000
15089
|
expectLength("eB", hello.eB, PUBLIC_KEY_BYTES);
|
|
@@ -15151,7 +15240,7 @@ async function loadPcKeys(path) {
|
|
|
15151
15240
|
try {
|
|
15152
15241
|
return normalizePcKeys(JSON.parse(raw));
|
|
15153
15242
|
} catch (error) {
|
|
15154
|
-
throw new Error(`${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}). Delete it
|
|
15243
|
+
throw new Error(`${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}). Delete it and register your browsers again with \`ainecto pair\`.`);
|
|
15155
15244
|
}
|
|
15156
15245
|
}
|
|
15157
15246
|
var PC_KEYS_LOCK = { waitMs: 5e3, pollMs: 50 };
|
|
@@ -16654,9 +16743,213 @@ function pcOutcome(lines) {
|
|
|
16654
16743
|
return failed === void 0 ? void 0 : { kind: "failed", line: failed };
|
|
16655
16744
|
}
|
|
16656
16745
|
|
|
16746
|
+
// src/core/pc/pcPairing.ts
|
|
16747
|
+
var PAIR_WAIT_MS = 5 * 6e4;
|
|
16748
|
+
async function runPairing(input) {
|
|
16749
|
+
const deadline = new AbortController();
|
|
16750
|
+
const timer = setTimeout(() => deadline.abort(), input.waitMs);
|
|
16751
|
+
let cancelled = false;
|
|
16752
|
+
const onCancel = () => {
|
|
16753
|
+
cancelled = true;
|
|
16754
|
+
deadline.abort();
|
|
16755
|
+
};
|
|
16756
|
+
input.cancel?.addEventListener("abort", onCancel, { once: true });
|
|
16757
|
+
if (input.cancel?.aborted) onCancel();
|
|
16758
|
+
const { signal } = deadline;
|
|
16759
|
+
const relayed = async (step) => {
|
|
16760
|
+
try {
|
|
16761
|
+
return await step();
|
|
16762
|
+
} catch (error) {
|
|
16763
|
+
if (signal.aborted) return "timeout";
|
|
16764
|
+
throw error;
|
|
16765
|
+
}
|
|
16766
|
+
};
|
|
16767
|
+
let outcome;
|
|
16768
|
+
try {
|
|
16769
|
+
outcome = await pairOnce();
|
|
16770
|
+
if (cancelled && outcome.kind === "timeout") outcome = { kind: "cancelled" };
|
|
16771
|
+
return outcome;
|
|
16772
|
+
} finally {
|
|
16773
|
+
clearTimeout(timer);
|
|
16774
|
+
input.cancel?.removeEventListener("abort", onCancel);
|
|
16775
|
+
if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
|
|
16776
|
+
}
|
|
16777
|
+
async function pairOnce() {
|
|
16778
|
+
const pcPublicRaw = publicRawFromJwk(input.pcKey);
|
|
16779
|
+
const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
|
|
16780
|
+
const commit = await pairCommitment(pcPublicRaw, nP);
|
|
16781
|
+
const { check } = input;
|
|
16782
|
+
if (check.kind === "codes") {
|
|
16783
|
+
check.prompt.show(`Waiting up to ${Math.round(input.waitMs / 6e4)} min for a browser \u2014 in AiNecto on the web, open Terminal, pick this PC and start the browser registration there.`);
|
|
16784
|
+
}
|
|
16785
|
+
const offer = await relayed(() => input.transport.offer(commit, signal));
|
|
16786
|
+
if (offer === "timeout") return { kind: "timeout" };
|
|
16787
|
+
const publicJwk = publicJwkFromRaw(offer.publicRaw);
|
|
16788
|
+
await assertSigningPublicKey(publicJwk);
|
|
16789
|
+
if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
|
|
16790
|
+
throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 browser registration aborted.");
|
|
16791
|
+
}
|
|
16792
|
+
const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
|
|
16793
|
+
const transcript = () => pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
|
|
16794
|
+
if (check.kind === "secret") {
|
|
16795
|
+
const keys = await registerKeys(check.secret);
|
|
16796
|
+
const expected = await registerOfferMac(keys.browser, {
|
|
16797
|
+
userId: input.userId,
|
|
16798
|
+
pcId: input.pcId,
|
|
16799
|
+
attemptId: offer.attemptId,
|
|
16800
|
+
commit,
|
|
16801
|
+
browserPublicRaw: offer.publicRaw,
|
|
16802
|
+
keyId: offer.keyId,
|
|
16803
|
+
nB: offer.nB,
|
|
16804
|
+
name: offer.name
|
|
16805
|
+
});
|
|
16806
|
+
if (!offer.macB || !macEquals(offer.macB, expected)) return { kind: "code-mismatch" };
|
|
16807
|
+
const t2 = await transcript();
|
|
16808
|
+
await input.pin(browser);
|
|
16809
|
+
const macP = await registerRevealMac(keys.pc, { transcript: t2, attemptId: offer.attemptId });
|
|
16810
|
+
return await finish(browser, t2, () => input.transport.reveal(pcPublicRaw, nP, signal, macP));
|
|
16811
|
+
}
|
|
16812
|
+
if (await relayed(() => input.transport.reveal(pcPublicRaw, nP, signal)) === "timeout") return { kind: "timeout" };
|
|
16813
|
+
const t = await transcript();
|
|
16814
|
+
const codes = await pairCodes(t);
|
|
16815
|
+
check.prompt.show(`A browser asked to be registered: ${browser.name}`);
|
|
16816
|
+
check.prompt.show(`Type this code in the browser: ${codes.a}`);
|
|
16817
|
+
const answer = await check.prompt.ask("Then type the code the browser shows (one try): ", signal);
|
|
16818
|
+
if (signal.aborted) return { kind: "timeout" };
|
|
16819
|
+
const typed = pairCodeInput(answer);
|
|
16820
|
+
if (typed.kind === "empty") return { kind: "cancelled" };
|
|
16821
|
+
if (typed.kind !== "code" || typed.code !== codes.b) return { kind: "code-mismatch" };
|
|
16822
|
+
await input.pin(browser);
|
|
16823
|
+
return await finish(browser, t);
|
|
16824
|
+
}
|
|
16825
|
+
async function finish(browser, transcript, before) {
|
|
16826
|
+
const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
|
|
16827
|
+
let doneError;
|
|
16828
|
+
try {
|
|
16829
|
+
await before?.();
|
|
16830
|
+
await input.transport.done(signature, signal);
|
|
16831
|
+
} catch (error) {
|
|
16832
|
+
doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
|
|
16833
|
+
}
|
|
16834
|
+
return { kind: "paired", browser, doneError };
|
|
16835
|
+
}
|
|
16836
|
+
}
|
|
16837
|
+
|
|
16657
16838
|
// src/adapters/cli/pcCommand.ts
|
|
16658
16839
|
import { readFile as readFile13 } from "fs/promises";
|
|
16659
16840
|
|
|
16841
|
+
// src/adapters/cli/pairCommand.ts
|
|
16842
|
+
import { randomUUID as randomUUID7 } from "crypto";
|
|
16843
|
+
import { closeSync as closeSync3, openSync as openSync3 } from "fs";
|
|
16844
|
+
import { ReadStream, WriteStream } from "tty";
|
|
16845
|
+
|
|
16846
|
+
// src/core/pc/pcPairRelay.ts
|
|
16847
|
+
var PairRelayError = class extends Error {
|
|
16848
|
+
constructor(code, message2) {
|
|
16849
|
+
super(message2);
|
|
16850
|
+
this.code = code;
|
|
16851
|
+
}
|
|
16852
|
+
code;
|
|
16853
|
+
};
|
|
16854
|
+
function createPairRelay(input) {
|
|
16855
|
+
const http = createPcHttp({
|
|
16856
|
+
endpoint: input.endpoint,
|
|
16857
|
+
path: "term/pc",
|
|
16858
|
+
tokenProvider: input.tokenProvider,
|
|
16859
|
+
timeoutMs: CALL_TIMEOUT_MS,
|
|
16860
|
+
sessionHeader: "X-Remote-Token",
|
|
16861
|
+
fetchImpl: input.fetchImpl,
|
|
16862
|
+
logging: {
|
|
16863
|
+
log: input.log,
|
|
16864
|
+
request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
|
|
16865
|
+
response: ({ callId, op, ms }, outcome) => ({
|
|
16866
|
+
event: "remote_call_response",
|
|
16867
|
+
callId,
|
|
16868
|
+
op,
|
|
16869
|
+
...outcome.ok ? {
|
|
16870
|
+
ok: true,
|
|
16871
|
+
status: outcome.status,
|
|
16872
|
+
...Array.isArray(outcome.body.msgs) ? { commands: outcome.body.msgs.length } : {},
|
|
16873
|
+
...outcome.body.closed === true ? { state: "CLOSED" } : {}
|
|
16874
|
+
} : outcome,
|
|
16875
|
+
ms
|
|
16876
|
+
})
|
|
16877
|
+
}
|
|
16878
|
+
});
|
|
16879
|
+
let attemptId;
|
|
16880
|
+
let finished = false;
|
|
16881
|
+
const send = async (msg, signal) => {
|
|
16882
|
+
if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The browser registration was not opened.");
|
|
16883
|
+
await http.call("pair/send", { attemptId, msg }, signal ? { signal } : void 0);
|
|
16884
|
+
};
|
|
16885
|
+
return {
|
|
16886
|
+
async offer(commit, signal) {
|
|
16887
|
+
const opened = await http.call("pair/open", { pcId: input.pcId }, { signal });
|
|
16888
|
+
if (typeof opened.attemptId !== "string" || opened.attemptId === "") {
|
|
16889
|
+
throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "AiNecto answered pair/open without an attemptId.");
|
|
16890
|
+
}
|
|
16891
|
+
attemptId = opened.attemptId;
|
|
16892
|
+
await send({ type: "commit", commit: b64u2(commit) }, signal);
|
|
16893
|
+
for (; ; ) {
|
|
16894
|
+
const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
|
|
16895
|
+
if (answer.closed === true) {
|
|
16896
|
+
finished = true;
|
|
16897
|
+
throw new PairRelayError("PAIR_CLOSED", "The browser registration ended on AiNecto (the browser cancelled it, or it expired).");
|
|
16898
|
+
}
|
|
16899
|
+
const offer = offerOf(Array.isArray(answer.msgs) ? answer.msgs : []);
|
|
16900
|
+
if (offer === "abort") {
|
|
16901
|
+
finished = true;
|
|
16902
|
+
throw new PairRelayError("PAIR_CLOSED", "The browser cancelled the registration.");
|
|
16903
|
+
}
|
|
16904
|
+
if (offer) return { ...offer, attemptId };
|
|
16905
|
+
}
|
|
16906
|
+
},
|
|
16907
|
+
async reveal(pcPublicRaw, nP, signal, macP) {
|
|
16908
|
+
await send({ type: "reveal", publicKey: b64u2(pcPublicRaw), nP: b64u2(nP), ...macP ? { macP: b64u2(macP) } : {} }, signal);
|
|
16909
|
+
},
|
|
16910
|
+
async done(signature, signal) {
|
|
16911
|
+
await send({ type: "done", signature: b64u2(signature) }, signal);
|
|
16912
|
+
finished = true;
|
|
16913
|
+
},
|
|
16914
|
+
async abort(reason) {
|
|
16915
|
+
if (!attemptId || finished) return;
|
|
16916
|
+
finished = true;
|
|
16917
|
+
try {
|
|
16918
|
+
await send({ type: "abort", reason });
|
|
16919
|
+
} catch {
|
|
16920
|
+
}
|
|
16921
|
+
}
|
|
16922
|
+
};
|
|
16923
|
+
}
|
|
16924
|
+
function offerOf(msgs) {
|
|
16925
|
+
if (msgs.length === 0) return void 0;
|
|
16926
|
+
const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
|
|
16927
|
+
if (items.some((item2) => item2.type === "abort")) return "abort";
|
|
16928
|
+
if (items.length > 1) {
|
|
16929
|
+
throw new PairRelayError("PAIR_DUPLICATE", "More than one browser registration request arrived \u2014 this try was ended. Run `ainecto pair` again.");
|
|
16930
|
+
}
|
|
16931
|
+
const [item] = items;
|
|
16932
|
+
const publicRaw = fromB64u2(item?.publicKey, PUBLIC_KEY_BYTES);
|
|
16933
|
+
const nB = fromB64u2(item?.nB, NONCE_SEED_BYTES);
|
|
16934
|
+
const macB = item?.macB === void 0 ? void 0 : fromB64u2(
|
|
16935
|
+
item.macB,
|
|
16936
|
+
32
|
|
16937
|
+
/* HMAC-SHA256 */
|
|
16938
|
+
);
|
|
16939
|
+
if (item?.type !== "offer" || !publicRaw || !nB || typeof item.keyId !== "string" || typeof item.name !== "string" || item.macB !== void 0 && !macB) {
|
|
16940
|
+
throw new PairRelayError("PAIR_BAD_MESSAGE", "AiNecto relayed a browser registration message this CLI does not understand \u2014 this try was ended.");
|
|
16941
|
+
}
|
|
16942
|
+
return { keyId: item.keyId, publicRaw, nB, name: item.name, ...macB ? { macB } : {} };
|
|
16943
|
+
}
|
|
16944
|
+
function b64u2(bytes) {
|
|
16945
|
+
return Buffer.from(bytes).toString("base64url");
|
|
16946
|
+
}
|
|
16947
|
+
function fromB64u2(value, length) {
|
|
16948
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) return void 0;
|
|
16949
|
+
const bytes = new Uint8Array(Buffer.from(value, "base64url"));
|
|
16950
|
+
return bytes.length === length ? bytes : void 0;
|
|
16951
|
+
}
|
|
16952
|
+
|
|
16660
16953
|
// src/adapters/cli/pcStartText.ts
|
|
16661
16954
|
var DOCTOR_ONLY = /* @__PURE__ */ new Set(["AiNecto job title"]);
|
|
16662
16955
|
var NOT_CONNECTED = "not connected to AiNecto";
|
|
@@ -16688,72 +16981,270 @@ function pcResultText(result) {
|
|
|
16688
16981
|
const use = result.agentMissing ? "From AiNecto on the web you can open a terminal on this PC and run commands. No Claude Code or Codex was found, so AiNecto agent work cannot run here yet \u2014 install one, then run `ainecto` again." : "From AiNecto on the web you can open a terminal on this PC and run commands, and your AiNecto agent can run work here (Claude Code or Codex).";
|
|
16689
16982
|
return `This PC is now connected to AiNecto. ${use} It keeps running after you close this window. ${STOP} Log: ${result.log}`;
|
|
16690
16983
|
}
|
|
16984
|
+
function pcNotApprovedText(hostName, then) {
|
|
16985
|
+
return `This PC (${hostName}) is not connected to AiNecto yet. Run \`npx -y ainecto@latest\` in a terminal on this PC first and approve the connection${then ? `, then ${then}` : ""}.`;
|
|
16986
|
+
}
|
|
16691
16987
|
function listed(labels) {
|
|
16692
16988
|
if (labels.length <= 2) return labels.join(" and ");
|
|
16693
16989
|
return `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
|
|
16694
16990
|
}
|
|
16695
16991
|
|
|
16696
|
-
// src/adapters/cli/
|
|
16697
|
-
|
|
16698
|
-
|
|
16699
|
-
const
|
|
16700
|
-
|
|
16701
|
-
|
|
16702
|
-
|
|
16703
|
-
|
|
16704
|
-
|
|
16705
|
-
|
|
16706
|
-
|
|
16707
|
-
|
|
16708
|
-
|
|
16709
|
-
|
|
16710
|
-
|
|
16711
|
-
if (
|
|
16712
|
-
|
|
16713
|
-
return 0;
|
|
16714
|
-
}
|
|
16715
|
-
const code = await deps.setup();
|
|
16716
|
-
if (code !== 0) {
|
|
16717
|
-
return code;
|
|
16718
|
-
}
|
|
16719
|
-
status = await deps.machine();
|
|
16720
|
-
later = preflightNotes(doctorChecks(status));
|
|
16992
|
+
// src/adapters/cli/pairCommand.ts
|
|
16993
|
+
var USAGE = "Usage: ainecto pair [--list | --remove <keyId|name>]";
|
|
16994
|
+
function openDevTty() {
|
|
16995
|
+
const terminal = controllingTerminal();
|
|
16996
|
+
let inFd;
|
|
16997
|
+
try {
|
|
16998
|
+
inFd = openSync3(terminal.input, terminal.inputFlags);
|
|
16999
|
+
const outFd = openSync3(terminal.output, terminal.outputFlags);
|
|
17000
|
+
const stdin = new ReadStream(inFd);
|
|
17001
|
+
const stderr = new WriteStream(outFd);
|
|
17002
|
+
return { stdin, stderr, close: () => {
|
|
17003
|
+
stdin.destroy();
|
|
17004
|
+
stderr.destroy();
|
|
17005
|
+
} };
|
|
17006
|
+
} catch (error) {
|
|
17007
|
+
if (inFd !== void 0) closeSync3(inFd);
|
|
17008
|
+
throw new CliCommandError("PAIR_NO_TTY", `\`ainecto pair\` needs this PC's terminal (${terminal.input}): ${error instanceof Error ? error.message : String(error)}`);
|
|
16721
17009
|
}
|
|
16722
|
-
|
|
16723
|
-
|
|
16724
|
-
|
|
17010
|
+
}
|
|
17011
|
+
async function executePair(deps, argv) {
|
|
17012
|
+
const [first, ...rest] = argv;
|
|
17013
|
+
if (first === "--list" && rest.length === 0) {
|
|
17014
|
+
return await listBrowsers(deps);
|
|
16725
17015
|
}
|
|
16726
|
-
|
|
16727
|
-
|
|
16728
|
-
if (!settings.accounts[key]) {
|
|
16729
|
-
if (!deps.interactive) {
|
|
16730
|
-
throw new CliCommandError("PC_NOT_APPROVED", "This PC is not connected yet \u2014 run `ainecto` in a terminal once to approve.");
|
|
16731
|
-
}
|
|
16732
|
-
note("");
|
|
16733
|
-
note(`This connects this PC to AiNecto as ${status.account?.displayName ?? "your account"} (${deps.endpoint}).`);
|
|
16734
|
-
note(" \xB7 Your AiNecto agent will run work on this PC (Claude Code / Codex).");
|
|
16735
|
-
note(" \xB7 From AiNecto on the web, you can open terminals on this PC and run commands in them.");
|
|
16736
|
-
note(" \xB7 It keeps itself up to date \u2014 new AiNecto releases built and signed on AiNecto's GitHub are installed when this PC is idle.");
|
|
16737
|
-
if (!yes(await promptLine(deps.io, "Connect this PC? [y/N]: "), false)) {
|
|
16738
|
-
note("Not connected. Nothing was started.");
|
|
16739
|
-
return 0;
|
|
16740
|
-
}
|
|
16741
|
-
const remote = yes(await promptLine(deps.io, "Also allow terminals from the web? [y/N]: "), false);
|
|
16742
|
-
settings = withConsent(settings, key, remote, /* @__PURE__ */ new Date());
|
|
16743
|
-
await savePcSettings(deps.settingsPath, settings);
|
|
17016
|
+
if (first === "--remove" && rest.length === 1 && rest[0] !== void 0 && rest[0] !== "") {
|
|
17017
|
+
return await removeBrowser(deps, rest[0]);
|
|
16744
17018
|
}
|
|
16745
|
-
|
|
16746
|
-
|
|
16747
|
-
|
|
16748
|
-
|
|
16749
|
-
|
|
16750
|
-
|
|
16751
|
-
|
|
16752
|
-
|
|
17019
|
+
if (first !== void 0) {
|
|
17020
|
+
throw new CliCommandError("USAGE", USAGE);
|
|
17021
|
+
}
|
|
17022
|
+
return await pair(deps);
|
|
17023
|
+
}
|
|
17024
|
+
async function pair(deps) {
|
|
17025
|
+
const interactive = deps.interactive && !deps.json;
|
|
17026
|
+
if (interactive && deps.insideTermSession) {
|
|
17027
|
+
throw new CliCommandError(
|
|
17028
|
+
"PAIR_IN_TERM_SESSION",
|
|
17029
|
+
"`ainecto pair` does not run inside an AiNecto terminal session (its screen can be shown on the web). Run it in a regular terminal on this PC."
|
|
17030
|
+
);
|
|
17031
|
+
}
|
|
17032
|
+
let approved = await approvedAccount(deps, { strict: !interactive });
|
|
17033
|
+
if (!approved && interactive) {
|
|
17034
|
+
const code = await deps.connectPc();
|
|
17035
|
+
if (code !== 0) return code;
|
|
17036
|
+
approved = await approvedAccount(deps, { strict: false });
|
|
17037
|
+
if (approved) deps.io.stderr.write("\nNext: register this browser with this PC.\n");
|
|
17038
|
+
}
|
|
17039
|
+
if (!approved) {
|
|
17040
|
+
throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName, "run `npx -y ainecto@latest pair` to register this browser"));
|
|
17041
|
+
}
|
|
17042
|
+
if (!interactive) {
|
|
17043
|
+
throw new CliCommandError(
|
|
17044
|
+
"PAIR_INTERACTIVE_ONLY",
|
|
17045
|
+
"`ainecto pair` shows a code and asks you to type the code the browser shows \u2014 run it yourself in a terminal (not with --json or a pipe)."
|
|
17046
|
+
);
|
|
17047
|
+
}
|
|
17048
|
+
const { key, userId, settings } = approved;
|
|
17049
|
+
const pcKey = (await loadPcKeys(deps.keysPath)).accounts[key]?.pcKey ?? await generateSigningJwk();
|
|
17050
|
+
const transport = await deps.transport(settings.pcId);
|
|
17051
|
+
const tty = deps.openTty();
|
|
17052
|
+
let outcome;
|
|
17053
|
+
try {
|
|
17054
|
+
outcome = await relayErrors(() => runPairing({
|
|
17055
|
+
userId: transcriptUserId(userId),
|
|
17056
|
+
pcId: settings.pcId,
|
|
17057
|
+
pcKey,
|
|
17058
|
+
transport,
|
|
17059
|
+
check: { kind: "codes", prompt: { show: (line) => {
|
|
17060
|
+
tty.stderr.write(`${line}
|
|
17061
|
+
`);
|
|
17062
|
+
}, ask: (question, signal) => promptLine(tty, question, signal) } },
|
|
17063
|
+
pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key, pcKey, browser: browser2, now: deps.now() }),
|
|
17064
|
+
waitMs: deps.waitMs
|
|
17065
|
+
}));
|
|
17066
|
+
} finally {
|
|
17067
|
+
tty.close();
|
|
17068
|
+
}
|
|
17069
|
+
if (outcome.kind === "timeout") {
|
|
17070
|
+
throw new CliCommandError("PAIR_TIMEOUT", "Browser registration did not finish in time. Nothing was saved \u2014 run `ainecto pair` again.");
|
|
17071
|
+
}
|
|
17072
|
+
if (outcome.kind === "cancelled") {
|
|
17073
|
+
throw new CliCommandError("PAIR_CANCELLED", "Browser registration cancelled. Nothing was saved \u2014 run `ainecto pair` again.");
|
|
17074
|
+
}
|
|
17075
|
+
if (outcome.kind === "code-mismatch") {
|
|
17076
|
+
throw new CliCommandError(
|
|
17077
|
+
"PAIR_CODE_MISMATCH",
|
|
17078
|
+
"That code does not match. Nothing was saved \u2014 start again with `ainecto pair` (if you typed it right, someone may be in the middle)."
|
|
17079
|
+
);
|
|
17080
|
+
}
|
|
17081
|
+
const { browser, doneError } = outcome;
|
|
17082
|
+
if (doneError !== void 0) {
|
|
17083
|
+
throw new CliCommandError("PAIR_DONE_FAILED", `Saved "${browser.name}" on this PC, but the browser did not get the confirmation (${doneError}), so it will not trust this PC yet. Remove it with \`ainecto pair --remove ${browser.keyId}\` and run \`ainecto pair\` again.`);
|
|
17084
|
+
}
|
|
17085
|
+
await deps.notifyPaired({ keyId: browser.keyId, name: browser.name });
|
|
17086
|
+
const lines = [`Registered the browser "${browser.name}" with this PC. Remove it later with \`ainecto pair --remove ${browser.keyId}\`.`];
|
|
17087
|
+
if (settings.accounts[key]?.remoteTerminal !== true) {
|
|
17088
|
+
lines.push("Terminals from the web are blocked on this PC \u2014 `ainecto remote on` allows them.");
|
|
17089
|
+
}
|
|
17090
|
+
deps.io.stdout.write(`${lines.join("\n")}
|
|
17091
|
+
`);
|
|
17092
|
+
return 0;
|
|
17093
|
+
}
|
|
17094
|
+
async function pinBrowser(input) {
|
|
17095
|
+
const { key, pcKey, browser } = input;
|
|
17096
|
+
await updatePcKeys(input.keysPath, (latest) => {
|
|
17097
|
+
const stored = latest.accounts[key]?.pcKey;
|
|
17098
|
+
if (stored && stored.d !== pcKey.d) {
|
|
17099
|
+
throw new CliCommandError("PAIR_CONFLICT", "This PC's key changed during browser registration (another `ainecto pair`?). Nothing was saved \u2014 run `ainecto pair` again.");
|
|
17100
|
+
}
|
|
17101
|
+
if (latest.accounts[key]?.pendingTurnOff?.removals.some((item) => item.keyId === browser.keyId)) {
|
|
17102
|
+
throw new CliCommandError("PAIR_REMOVE_PENDING", `This browser's earlier removal has not finished. Nothing was saved \u2014 run \`ainecto pair --remove ${browser.keyId}\` first, then \`ainecto pair\` again.`);
|
|
17103
|
+
}
|
|
17104
|
+
return withBrowser(latest, key, pcKey, { ...browser, pairedAt: input.now.toISOString() });
|
|
17105
|
+
});
|
|
17106
|
+
}
|
|
17107
|
+
async function listBrowsers(deps) {
|
|
17108
|
+
const browsers = (await loadPcKeys(deps.keysPath)).accounts[(await account(deps)).key]?.browsers ?? [];
|
|
17109
|
+
const data = { browsers: browsers.map((item) => ({ keyId: item.keyId, name: item.name, pairedAt: item.pairedAt })) };
|
|
17110
|
+
const human = browsers.length === 0 ? "No browsers are registered with this PC. Run `ainecto pair` to register one." : ["Browsers registered with this PC:", ...browsers.map((item) => ` ${item.keyId} ${item.name} (registered ${item.pairedAt})`)].join("\n");
|
|
17111
|
+
deps.io.stdout.write(deps.json ? renderSuccess(data, { json: true }) : `${human}
|
|
17112
|
+
`);
|
|
17113
|
+
return 0;
|
|
17114
|
+
}
|
|
17115
|
+
async function removeBrowser(deps, keyIdOrName) {
|
|
17116
|
+
const { key } = await account(deps);
|
|
17117
|
+
let removed;
|
|
17118
|
+
let target;
|
|
17119
|
+
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17120
|
+
const result = withoutBrowser(keys, key, keyIdOrName);
|
|
17121
|
+
removed = result.removed;
|
|
17122
|
+
if (!removed) {
|
|
17123
|
+
target = pendingRemovalOf(keys.accounts[key], keyIdOrName);
|
|
17124
|
+
return void 0;
|
|
17125
|
+
}
|
|
17126
|
+
target = { removalId: randomUUID7(), keyId: removed.keyId, name: removed.name };
|
|
17127
|
+
return withPendingTurnOff(result.keys, key, { at: deps.now(), groups: [], removal: target });
|
|
17128
|
+
});
|
|
17129
|
+
if (!target) {
|
|
17130
|
+
throw new CliCommandError("PAIR_NOT_FOUND", `No registered browser with key id or name "${keyIdOrName}" \u2014 \`ainecto pair --list\` shows them.`);
|
|
17131
|
+
}
|
|
17132
|
+
const { keyId: finished, removalId } = target;
|
|
17133
|
+
let groups;
|
|
17134
|
+
try {
|
|
17135
|
+
const found = await deps.findPcs();
|
|
17136
|
+
const saved = await updatePcKeys(deps.keysPath, (keys) => {
|
|
17137
|
+
const next = withPendingTurnOff(keys, key, { at: deps.now(), groups: found });
|
|
17138
|
+
return next === keys ? void 0 : next;
|
|
17139
|
+
});
|
|
17140
|
+
groups = saved.accounts[key]?.pendingTurnOff?.groups ?? found;
|
|
17141
|
+
await deps.turnOffPcs(groups);
|
|
17142
|
+
} catch (error) {
|
|
17143
|
+
throw new CliCommandError("PAIR_REMOVE_STOP_FAILED", `${removed ? `Removed "${removed.name}" (${removed.keyId}), but t` : "T"}urning off the PC connection was not confirmed (${error instanceof Error ? error.message : String(error)}). Run \`ainecto pair --remove ${finished}\` again to finish.`);
|
|
17144
|
+
}
|
|
17145
|
+
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17146
|
+
const next = withTurnOffConfirmed(keys, key, { groups, removalId });
|
|
17147
|
+
return next === keys ? void 0 : next;
|
|
17148
|
+
});
|
|
17149
|
+
const lines = [removed ? `Removed "${removed.name}" (${removed.keyId}). It can no longer open terminals on this PC.` : "Finished the earlier removal."];
|
|
17150
|
+
lines.push(groups.length > 0 ? "Turned off the PC connection. Run `ainecto` to turn it back on." : "The PC connection is not running.");
|
|
17151
|
+
deps.io.stdout.write(deps.json ? renderSuccess({ removed: removed ? { keyId: removed.keyId, name: removed.name } : null, turnedOff: groups }, { json: true }) : `${lines.join("\n")}
|
|
17152
|
+
`);
|
|
17153
|
+
return 0;
|
|
17154
|
+
}
|
|
17155
|
+
async function relayErrors(run) {
|
|
17156
|
+
try {
|
|
17157
|
+
return await run();
|
|
17158
|
+
} catch (error) {
|
|
17159
|
+
if (error instanceof PairRelayError) {
|
|
17160
|
+
throw new CliCommandError(error.code, `${error.message} Nothing was saved \u2014 run \`ainecto pair\` again.`);
|
|
17161
|
+
}
|
|
17162
|
+
if (error instanceof PcCallError) {
|
|
17163
|
+
throw new CliCommandError("PAIR_RELAY_FAILED", `Could not reach AiNecto for browser registration (${error.op}: ${error.status ?? "-"} ${error.code ?? ""} ` + `${error.message}`.replace(/\s+/g, " ").trim() + "). Nothing was saved \u2014 run `ainecto pair` again.");
|
|
17164
|
+
}
|
|
17165
|
+
throw error;
|
|
17166
|
+
}
|
|
17167
|
+
}
|
|
17168
|
+
async function approvedAccount(deps, options) {
|
|
17169
|
+
const userId = (await deps.account()).userId;
|
|
17170
|
+
if (!userId) {
|
|
17171
|
+
if (options.strict) throw accountUnknown();
|
|
17172
|
+
return void 0;
|
|
17173
|
+
}
|
|
17174
|
+
const key = accountKey(deps.endpoint, userId);
|
|
17175
|
+
const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
|
|
17176
|
+
return settings.accounts[key] ? { key, userId, settings } : void 0;
|
|
17177
|
+
}
|
|
17178
|
+
async function account(deps) {
|
|
17179
|
+
const userId = (await deps.account()).userId;
|
|
17180
|
+
if (!userId) throw accountUnknown();
|
|
17181
|
+
return { key: accountKey(deps.endpoint, userId), userId };
|
|
17182
|
+
}
|
|
17183
|
+
function accountUnknown() {
|
|
17184
|
+
return new CliCommandError("PC_ACCOUNT_UNKNOWN", "Could not read your AiNecto account \u2014 run `ainecto doctor` to see why.");
|
|
17185
|
+
}
|
|
17186
|
+
|
|
17187
|
+
// src/adapters/cli/pcCommand.ts
|
|
17188
|
+
async function executePcStart(deps) {
|
|
17189
|
+
assertTerm(deps);
|
|
17190
|
+
const note = (line) => {
|
|
17191
|
+
deps.io.stderr.write(`${line}
|
|
17192
|
+
`);
|
|
17193
|
+
};
|
|
17194
|
+
note("Checking sign-in and connections\u2026");
|
|
17195
|
+
let status = await deps.machine();
|
|
17196
|
+
let later = preflightNotes(doctorChecks(status));
|
|
17197
|
+
const signedIn = status.token.state === "env" || status.token.state === "signed-in";
|
|
17198
|
+
if (!signedIn) {
|
|
17199
|
+
if (!deps.interactive) {
|
|
17200
|
+
throw new CliCommandError("PC_NOT_SIGNED_IN", "Not signed in to AiNecto \u2014 run `ainecto setup` in a terminal first.");
|
|
17201
|
+
}
|
|
17202
|
+
if (!yes(await promptLine(deps.io, "Sign in and connect your coding agents now (ainecto setup)? [Y/n]: "), true)) {
|
|
17203
|
+
note("Run `ainecto setup` when you are ready, then `ainecto` again.");
|
|
17204
|
+
return 0;
|
|
17205
|
+
}
|
|
17206
|
+
const code = await deps.setup();
|
|
17207
|
+
if (code !== 0) {
|
|
17208
|
+
return code;
|
|
17209
|
+
}
|
|
17210
|
+
status = await deps.machine();
|
|
17211
|
+
later = preflightNotes(doctorChecks(status));
|
|
17212
|
+
}
|
|
17213
|
+
const userId = status.account?.userId;
|
|
17214
|
+
if (!userId) {
|
|
17215
|
+
throw new CliCommandError("PC_ACCOUNT_UNKNOWN", `Could not read your AiNecto account${status.account?.problem ? ` (${status.account.problem.message})` : ""}. Run \`ainecto doctor\` to see why.`);
|
|
17216
|
+
}
|
|
17217
|
+
const key = accountKey(deps.endpoint, userId);
|
|
17218
|
+
let settings = await loadPcSettings(deps.settingsPath, deps.hostName);
|
|
17219
|
+
if (!settings.accounts[key]) {
|
|
17220
|
+
if (!deps.interactive) {
|
|
17221
|
+
throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName));
|
|
17222
|
+
}
|
|
17223
|
+
note("");
|
|
17224
|
+
note(`This connects this PC to AiNecto as ${status.account?.displayName ?? "your account"} (${deps.endpoint}).`);
|
|
17225
|
+
note(" \xB7 Your AiNecto agent will run work on this PC (Claude Code / Codex).");
|
|
17226
|
+
note(" \xB7 From AiNecto on the web, you can open terminals on this PC and run commands in them.");
|
|
17227
|
+
note(" \xB7 It keeps itself up to date \u2014 new AiNecto releases built and signed on AiNecto's GitHub are installed when this PC is idle.");
|
|
17228
|
+
if (!yes(await promptLine(deps.io, "Connect this PC? [y/N]: "), false)) {
|
|
17229
|
+
note("Not connected. Nothing was started.");
|
|
17230
|
+
return 0;
|
|
17231
|
+
}
|
|
17232
|
+
const remote = yes(await promptLine(deps.io, "Also allow terminals from the web? [y/N]: "), false);
|
|
17233
|
+
settings = withConsent(settings, key, remote, /* @__PURE__ */ new Date());
|
|
17234
|
+
await savePcSettings(deps.settingsPath, settings);
|
|
17235
|
+
}
|
|
17236
|
+
const action = pcAction(runningPcs(await listed2(deps)), deps.cliVersion);
|
|
17237
|
+
if (action.kind === "already") {
|
|
17238
|
+
if (!remoteOffByWeb(await screenLines2(deps, action.pc.session))) {
|
|
17239
|
+
return await withRegistration(deps, key, userId, withNotes(deps, later, print2(
|
|
17240
|
+
deps,
|
|
17241
|
+
{ connected: true, already: true, ...pcView(deps, action.pc) },
|
|
17242
|
+
pcResultText({ kind: "already", folder: action.pc.cwd, version: pcVersionLabel(action.pc), log: deps.agentLog })
|
|
17243
|
+
)));
|
|
16753
17244
|
}
|
|
16754
17245
|
note("The remote terminal was turned off from the web \u2014 reconnecting this PC to turn it back on\u2026");
|
|
16755
17246
|
await stopPc(deps, action.pc);
|
|
16756
|
-
return withNotes(deps, later, await launchPc(deps));
|
|
17247
|
+
return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
|
|
16757
17248
|
}
|
|
16758
17249
|
await prepare(deps);
|
|
16759
17250
|
if (action.kind === "replace") {
|
|
@@ -16762,8 +17253,80 @@ async function executePcStart(deps) {
|
|
|
16762
17253
|
await stopPc(deps, pc);
|
|
16763
17254
|
}
|
|
16764
17255
|
}
|
|
16765
|
-
return withNotes(deps, later, await launchPc(deps));
|
|
17256
|
+
return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
|
|
17257
|
+
}
|
|
17258
|
+
async function withRegistration(deps, key, userId, code) {
|
|
17259
|
+
if (code === 0) await registerBrowserIfNone(deps, { key, userId });
|
|
17260
|
+
return code;
|
|
17261
|
+
}
|
|
17262
|
+
async function registerBrowserIfNone(deps, account2) {
|
|
17263
|
+
const register = deps.register;
|
|
17264
|
+
if (!register || !deps.interactive || deps.json || register.insideTermSession) return;
|
|
17265
|
+
const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
|
|
17266
|
+
if (settings.accounts[account2.key]?.remoteTerminal !== true) return;
|
|
17267
|
+
const stored = (await loadPcKeys(deps.keysPath)).accounts[account2.key];
|
|
17268
|
+
if ((stored?.browsers.length ?? 0) > 0) return;
|
|
17269
|
+
const note = (line) => {
|
|
17270
|
+
deps.io.stderr.write(`${line}
|
|
17271
|
+
`);
|
|
17272
|
+
};
|
|
17273
|
+
const noBrowser = "This PC can't open a browser here. To register this browser, run `npx -y ainecto@latest pair` in this PC's terminal.";
|
|
17274
|
+
if (register.overSsh) {
|
|
17275
|
+
note(noBrowser);
|
|
17276
|
+
return;
|
|
17277
|
+
}
|
|
17278
|
+
const userId = transcriptUserId(account2.userId);
|
|
17279
|
+
const secret = randomBytes3(NONCE_SEED_BYTES);
|
|
17280
|
+
const interrupt = register.interrupt();
|
|
17281
|
+
let outcome;
|
|
17282
|
+
try {
|
|
17283
|
+
const tag = await registerTag((await registerKeys(secret)).account, userId);
|
|
17284
|
+
const url = `${new URL(deps.endpoint).origin}${REGISTER_PATH}#${registerFragment({ pcId: settings.pcId, tag, secret })}`;
|
|
17285
|
+
try {
|
|
17286
|
+
await register.openBrowser(url);
|
|
17287
|
+
} catch {
|
|
17288
|
+
note(noBrowser);
|
|
17289
|
+
return;
|
|
17290
|
+
}
|
|
17291
|
+
note("");
|
|
17292
|
+
note(`Finish in the browser that just opened (up to ${Math.round(register.waitMs / 6e4)} min \xB7 Ctrl+C to skip)`);
|
|
17293
|
+
const pcKey = stored?.pcKey ?? await generateSigningJwk();
|
|
17294
|
+
outcome = await runPairing({
|
|
17295
|
+
userId,
|
|
17296
|
+
pcId: settings.pcId,
|
|
17297
|
+
pcKey,
|
|
17298
|
+
transport: await register.transport(settings.pcId),
|
|
17299
|
+
check: { kind: "secret", secret },
|
|
17300
|
+
pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now: register.now() }),
|
|
17301
|
+
waitMs: register.waitMs,
|
|
17302
|
+
cancel: interrupt.signal
|
|
17303
|
+
});
|
|
17304
|
+
} catch (error) {
|
|
17305
|
+
note(`Browser registration did not finish (${error instanceof Error ? error.message : String(error)}). ${REGISTER_AGAIN}`);
|
|
17306
|
+
return;
|
|
17307
|
+
} finally {
|
|
17308
|
+
interrupt.dispose();
|
|
17309
|
+
secret.fill(0);
|
|
17310
|
+
}
|
|
17311
|
+
if (outcome.kind !== "paired") {
|
|
17312
|
+
const why = outcome.kind === "timeout" ? "timed out" : outcome.kind === "cancelled" ? "skipped" : "the browser could not be verified";
|
|
17313
|
+
note(`Browser registration did not finish (${why}). Nothing was saved. ${REGISTER_AGAIN}`);
|
|
17314
|
+
return;
|
|
17315
|
+
}
|
|
17316
|
+
const { browser, doneError } = outcome;
|
|
17317
|
+
if (doneError !== void 0) {
|
|
17318
|
+
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17319
|
+
const result = withoutBrowser(keys, account2.key, browser.keyId);
|
|
17320
|
+
return result.removed ? result.keys : void 0;
|
|
17321
|
+
});
|
|
17322
|
+
note(`The browser "${browser.name}" did not get the confirmation (${doneError}), so nothing was kept. ${REGISTER_AGAIN}`);
|
|
17323
|
+
return;
|
|
17324
|
+
}
|
|
17325
|
+
await register.notifyPaired({ keyId: browser.keyId, name: browser.name });
|
|
17326
|
+
deps.io.stdout.write(`Registered "${browser.name}" with this PC. Remove it later with \`ainecto pair --remove ${browser.keyId}\`.
|
|
17327
|
+
`);
|
|
16766
17328
|
}
|
|
17329
|
+
var REGISTER_AGAIN = "Try again: `npx -y ainecto@latest` \xB7 or register this browser with `npx -y ainecto@latest pair`.";
|
|
16767
17330
|
function withNotes(deps, notes, code) {
|
|
16768
17331
|
for (const line of notes) deps.io.stderr.write(`${line}
|
|
16769
17332
|
`);
|
|
@@ -16843,535 +17406,196 @@ async function lastLogLineSince(path, since) {
|
|
|
16843
17406
|
try {
|
|
16844
17407
|
const ts = JSON.parse(last).ts;
|
|
16845
17408
|
return typeof ts === "string" && ts >= since ? last : void 0;
|
|
16846
|
-
} catch {
|
|
16847
|
-
return void 0;
|
|
16848
|
-
}
|
|
16849
|
-
}
|
|
16850
|
-
async function executePcStop(deps, argv) {
|
|
16851
|
-
const unknown = argv.filter((arg) => arg !== "--forget");
|
|
16852
|
-
if (unknown.length > 0) {
|
|
16853
|
-
throw new CliCommandError("USAGE", `Unknown argument for stop: ${unknown[0]}. Usage: ainecto stop [--forget]`);
|
|
16854
|
-
}
|
|
16855
|
-
const running = deps.termProblem === void 0 ? runningPcs(await listed2(deps)) : [];
|
|
16856
|
-
const lines = [];
|
|
16857
|
-
for (const pc of running) {
|
|
16858
|
-
lines.push(await stopPc(deps, pc));
|
|
16859
|
-
}
|
|
16860
|
-
if (running.length === 0) {
|
|
16861
|
-
lines.push("This PC is not connected.");
|
|
16862
|
-
}
|
|
16863
|
-
const forget = argv.includes("--forget");
|
|
16864
|
-
if (forget) {
|
|
16865
|
-
await savePcSettings(deps.settingsPath, withoutEndpoint(await loadPcSettings(deps.settingsPath, deps.hostName), deps.endpoint));
|
|
16866
|
-
lines.push(`Removed your approval for ${deps.endpoint} on this PC; \`ainecto\` asks again next time.`);
|
|
16867
|
-
let removedKeys = false;
|
|
16868
|
-
await updatePcKeys(deps.keysPath, (keys) => {
|
|
16869
|
-
const kept = withoutEndpointKeys(keys, deps.endpoint);
|
|
16870
|
-
removedKeys = Object.keys(kept.accounts).length !== Object.keys(keys.accounts).length;
|
|
16871
|
-
return removedKeys ? kept : void 0;
|
|
16872
|
-
});
|
|
16873
|
-
if (removedKeys) {
|
|
16874
|
-
lines.push("Also removed this PC's terminal key and paired browsers for that server \u2014 pair again with `ainecto pair`.");
|
|
16875
|
-
}
|
|
16876
|
-
}
|
|
16877
|
-
return print2(deps, { stopped: running.map((pc) => pc.session), forgot: forget }, lines.join("\n"));
|
|
16878
|
-
}
|
|
16879
|
-
async function executeRemoteSetting(deps, argv) {
|
|
16880
|
-
const [value, ...rest] = argv;
|
|
16881
|
-
if (value !== "on" && value !== "off" || rest.length > 0) {
|
|
16882
|
-
throw new CliCommandError("USAGE", "Usage: ainecto remote on|off");
|
|
16883
|
-
}
|
|
16884
|
-
const userId = (await deps.account()).userId;
|
|
16885
|
-
if (!userId) {
|
|
16886
|
-
throw new CliCommandError("PC_ACCOUNT_UNKNOWN", "Could not read your AiNecto account \u2014 run `ainecto doctor` to see why.");
|
|
16887
|
-
}
|
|
16888
|
-
const next = withRemoteTerminal(await loadPcSettings(deps.settingsPath, deps.hostName), accountKey(deps.endpoint, userId), value === "on");
|
|
16889
|
-
if (!next) {
|
|
16890
|
-
throw new CliCommandError("PC_NOT_APPROVED", "This PC is not connected yet \u2014 run `ainecto` in a terminal once to approve.");
|
|
16891
|
-
}
|
|
16892
|
-
await savePcSettings(deps.settingsPath, next);
|
|
16893
|
-
const said = value === "on" ? "Terminals from AiNecto on the web are allowed on this PC." : "Terminals from AiNecto on the web are blocked on this PC.";
|
|
16894
|
-
const running = deps.termProblem === void 0 ? runningPcs(await listed2(deps)) : [];
|
|
16895
|
-
if (running.length === 0) {
|
|
16896
|
-
return print2(deps, { remoteTerminal: value === "on" }, said);
|
|
16897
|
-
}
|
|
16898
|
-
if (!deps.json) deps.io.stdout.write(`${said}
|
|
16899
|
-
`);
|
|
16900
|
-
deps.io.stderr.write("Reconnecting this PC so it takes effect\u2026\n");
|
|
16901
|
-
for (const pc of running) {
|
|
16902
|
-
await stopPc(deps, pc);
|
|
16903
|
-
}
|
|
16904
|
-
return await launchPc(deps);
|
|
16905
|
-
}
|
|
16906
|
-
async function runningPcGroups(deps) {
|
|
16907
|
-
assertQueryable(deps);
|
|
16908
|
-
const groups = [];
|
|
16909
|
-
for (const session of (await listedToTurnOff(deps)).filter((item) => runningPcs([item]).length > 0)) {
|
|
16910
|
-
const pgid = await processGroupOf(session.pid);
|
|
16911
|
-
if (pgid === void 0) {
|
|
16912
|
-
throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not read the process group of the PC connection (session ${session.name}, pid ${session.pid}), so its end cannot be confirmed.${processGroupUnavailableHint()}`);
|
|
16913
|
-
}
|
|
16914
|
-
groups.push({ session: session.name, pid: session.pid, pgid });
|
|
16915
|
-
}
|
|
16916
|
-
return groups;
|
|
16917
|
-
}
|
|
16918
|
-
async function turnOffPcs(deps, groups) {
|
|
16919
|
-
assertQueryable(deps);
|
|
16920
|
-
for (const group of groups) {
|
|
16921
|
-
const session = (await listedToTurnOff(deps)).find((item) => item.name === group.session && item.pid === group.pid);
|
|
16922
|
-
const [pc] = session ? runningPcs([session]) : [];
|
|
16923
|
-
if (pc) await stopPc(deps, pc);
|
|
16924
|
-
await confirmEnded(deps, group);
|
|
16925
|
-
}
|
|
16926
|
-
}
|
|
16927
|
-
function assertQueryable(deps) {
|
|
16928
|
-
if (deps.termProblem !== void 0) {
|
|
16929
|
-
throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not check the PC connection (ainecto term: ${deps.termProblem}).`);
|
|
16930
|
-
}
|
|
16931
|
-
}
|
|
16932
|
-
var STOP_CONFIRM_POLL_MS = 100;
|
|
16933
|
-
async function confirmEnded(deps, group) {
|
|
16934
|
-
const deadline = Date.now() + deps.stopDeadlineMs;
|
|
16935
|
-
for (; ; ) {
|
|
16936
|
-
const stillListed = (await listedToTurnOff(deps)).some((session) => session.name === group.session && session.pid === group.pid);
|
|
16937
|
-
const alive = processGroupAlive(group.pgid);
|
|
16938
|
-
if (!stillListed && !alive) return;
|
|
16939
|
-
if (Date.now() >= deadline) {
|
|
16940
|
-
const what = stillListed ? "the session is still running" : `a process in its group ${group.pgid} is still alive`;
|
|
16941
|
-
throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not confirm that the PC connection (session ${group.session}, pid ${group.pid}) ended within ${deps.stopDeadlineMs / 1e3} s (${what}). See ${deps.agentLog}.`);
|
|
16942
|
-
}
|
|
16943
|
-
await new Promise((resolve4) => setTimeout(resolve4, STOP_CONFIRM_POLL_MS));
|
|
16944
|
-
}
|
|
16945
|
-
}
|
|
16946
|
-
async function stopPc(deps, pc) {
|
|
16947
|
-
const client = await openTermClient(deps.paths, { start: false });
|
|
16948
|
-
if (!client) {
|
|
16949
|
-
return `Session ${pc.session} is already gone.`;
|
|
16950
|
-
}
|
|
16951
|
-
let timer;
|
|
16952
|
-
try {
|
|
16953
|
-
let ready;
|
|
16954
|
-
try {
|
|
16955
|
-
ready = pcOutcome(readLines(await client.request({ op: "read", name: pc.session, scrollback: true })))?.kind === "connected";
|
|
16956
|
-
} catch (error) {
|
|
16957
|
-
if (error instanceof TermError && error.code === "TERM_NO_SESSION") {
|
|
16958
|
-
return `Session ${pc.session} is already gone.`;
|
|
16959
|
-
}
|
|
16960
|
-
throw error;
|
|
16961
|
-
}
|
|
16962
|
-
if (!ready) {
|
|
16963
|
-
await client.request({ op: "kill", name: pc.session });
|
|
16964
|
-
return `Session ${pc.session} was still starting \u2014 ended it.`;
|
|
16965
|
-
}
|
|
16966
|
-
const ended = new Promise((resolve4) => {
|
|
16967
|
-
client.onEvent((event) => {
|
|
16968
|
-
if (event.event === "exit") {
|
|
16969
|
-
resolve4("ended");
|
|
16970
|
-
}
|
|
16971
|
-
});
|
|
16972
|
-
client.onClose(() => resolve4("ended"));
|
|
16973
|
-
});
|
|
16974
|
-
try {
|
|
16975
|
-
await client.request({ op: "watch", name: pc.session });
|
|
16976
|
-
await client.request({ op: "key", name: pc.session, key: "ctrl-c" });
|
|
16977
|
-
} catch (error) {
|
|
16978
|
-
if (error instanceof TermError && error.code === "TERM_NO_SESSION") {
|
|
16979
|
-
return `Session ${pc.session} is already gone.`;
|
|
16980
|
-
}
|
|
16981
|
-
throw error;
|
|
16982
|
-
}
|
|
16983
|
-
const outcome = await Promise.race([ended, new Promise((resolve4) => {
|
|
16984
|
-
timer = setTimeout(() => resolve4("late"), deps.stopDeadlineMs);
|
|
16985
|
-
})]);
|
|
16986
|
-
if (outcome === "ended") {
|
|
16987
|
-
return `Disconnected this PC (session ${pc.session}).`;
|
|
16988
|
-
}
|
|
16989
|
-
await termRequest(deps.paths, { op: "kill", name: pc.session }, { start: false });
|
|
16990
|
-
return `Session ${pc.session} did not stop within ${deps.stopDeadlineMs / 1e3} s after Ctrl+C \u2014 ended it. See ${deps.agentLog}.`;
|
|
16991
|
-
} finally {
|
|
16992
|
-
clearTimeout(timer);
|
|
16993
|
-
client.close();
|
|
16994
|
-
}
|
|
16995
|
-
}
|
|
16996
|
-
async function prepare(deps) {
|
|
16997
|
-
const [command, ...args] = deps.managedCommand(["--version"]);
|
|
16998
|
-
if (!command) {
|
|
16999
|
-
throw new Error("The PC connection command is empty.");
|
|
17000
|
-
}
|
|
17001
|
-
const result = await deps.runner(command, args);
|
|
17002
|
-
if (result.missing || result.exitCode !== 0) {
|
|
17003
|
-
throw new CliCommandError("PC_PREPARE_FAILED", `\`${[command, ...args].join(" ")}\` failed${result.missing ? ` (${command} is not on PATH)` : ""}: ${lastLine(result.stderr) ?? lastLine(result.stdout) ?? `exit ${result.exitCode}`}`);
|
|
17004
|
-
}
|
|
17005
|
-
}
|
|
17006
|
-
async function listed2(deps, connect2 = { start: false }) {
|
|
17007
|
-
const result = await termRequest(deps.paths, { op: "ls" }, connect2);
|
|
17008
|
-
return listedSessions(result.daemon ? result.data : void 0);
|
|
17009
|
-
}
|
|
17010
|
-
async function listedToTurnOff(deps) {
|
|
17011
|
-
return await listed2(deps, { start: false, resetFails: true });
|
|
17012
|
-
}
|
|
17013
|
-
function assertTerm(deps) {
|
|
17014
|
-
if (deps.termProblem !== void 0) {
|
|
17015
|
-
throw new CliCommandError("PC_UNSUPPORTED", `Connecting this PC needs ainecto term: ${deps.termProblem}`);
|
|
17016
|
-
}
|
|
17017
|
-
}
|
|
17018
|
-
function pcView(deps, pc) {
|
|
17019
|
-
return { session: pc.session, folder: pc.cwd, version: pcVersionLabel(pc), log: deps.agentLog };
|
|
17020
|
-
}
|
|
17021
|
-
function yes(answer, byDefault) {
|
|
17022
|
-
const value = answer.trim().toLowerCase();
|
|
17023
|
-
return value === "" ? byDefault : value === "y" || value === "yes";
|
|
17024
|
-
}
|
|
17025
|
-
function print2(deps, data, human) {
|
|
17026
|
-
deps.io.stdout.write(deps.json ? renderSuccess(data, { json: true }) : `${human}
|
|
17027
|
-
`);
|
|
17028
|
-
return 0;
|
|
17029
|
-
}
|
|
17030
|
-
|
|
17031
|
-
// src/adapters/cli/pairCommand.ts
|
|
17032
|
-
import { randomUUID as randomUUID7 } from "crypto";
|
|
17033
|
-
import { closeSync as closeSync3, openSync as openSync3 } from "fs";
|
|
17034
|
-
import { ReadStream, WriteStream } from "tty";
|
|
17035
|
-
|
|
17036
|
-
// src/core/pc/pcPairing.ts
|
|
17037
|
-
var PAIR_WAIT_MS = 5 * 6e4;
|
|
17038
|
-
async function runPairing(input) {
|
|
17039
|
-
const deadline = new AbortController();
|
|
17040
|
-
const timer = setTimeout(() => deadline.abort(), input.waitMs);
|
|
17041
|
-
const { signal } = deadline;
|
|
17042
|
-
const relayed = async (step) => {
|
|
17043
|
-
try {
|
|
17044
|
-
return await step();
|
|
17045
|
-
} catch (error) {
|
|
17046
|
-
if (signal.aborted) return "timeout";
|
|
17047
|
-
throw error;
|
|
17048
|
-
}
|
|
17049
|
-
};
|
|
17050
|
-
let outcome;
|
|
17051
|
-
try {
|
|
17052
|
-
outcome = await pairOnce();
|
|
17053
|
-
return outcome;
|
|
17054
|
-
} finally {
|
|
17055
|
-
clearTimeout(timer);
|
|
17056
|
-
if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
|
|
17057
|
-
}
|
|
17058
|
-
async function pairOnce() {
|
|
17059
|
-
const pcPublicRaw = publicRawFromJwk(input.pcKey);
|
|
17060
|
-
const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
|
|
17061
|
-
const commit = await pairCommitment(pcPublicRaw, nP);
|
|
17062
|
-
input.prompt.show(`Waiting up to ${Math.round(input.waitMs / 6e4)} min for a browser \u2014 in AiNecto on the web, open Terminal, pick this PC and choose \xABPair with this PC\xBB.`);
|
|
17063
|
-
const offer = await relayed(() => input.transport.offer(commit, signal));
|
|
17064
|
-
if (offer === "timeout") return { kind: "timeout" };
|
|
17065
|
-
const publicJwk = publicJwkFromRaw(offer.publicRaw);
|
|
17066
|
-
await assertSigningPublicKey(publicJwk);
|
|
17067
|
-
if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
|
|
17068
|
-
throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 pairing aborted.");
|
|
17069
|
-
}
|
|
17070
|
-
const name = browserNameOf(offer.name);
|
|
17071
|
-
if (await relayed(() => input.transport.reveal(pcPublicRaw, nP, signal)) === "timeout") return { kind: "timeout" };
|
|
17072
|
-
const transcript = await pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
|
|
17073
|
-
const codes = await pairCodes(transcript);
|
|
17074
|
-
input.prompt.show(`A browser asked to pair: ${name}`);
|
|
17075
|
-
input.prompt.show(`Type this code in the browser: ${codes.a}`);
|
|
17076
|
-
const answer = await input.prompt.ask("Then type the code the browser shows (one try): ", signal);
|
|
17077
|
-
if (signal.aborted) return { kind: "timeout" };
|
|
17078
|
-
const typed = pairCodeInput(answer);
|
|
17079
|
-
if (typed.kind === "empty") return { kind: "cancelled" };
|
|
17080
|
-
if (typed.kind !== "code" || typed.code !== codes.b) return { kind: "code-mismatch" };
|
|
17081
|
-
const browser = { keyId: offer.keyId, publicJwk, name };
|
|
17082
|
-
await input.pin(browser);
|
|
17083
|
-
const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
|
|
17084
|
-
let doneError;
|
|
17085
|
-
try {
|
|
17086
|
-
await input.transport.done(signature, signal);
|
|
17087
|
-
} catch (error) {
|
|
17088
|
-
doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
|
|
17089
|
-
}
|
|
17090
|
-
return { kind: "paired", browser, doneError };
|
|
17091
|
-
}
|
|
17092
|
-
}
|
|
17093
|
-
|
|
17094
|
-
// src/core/pc/pcPairRelay.ts
|
|
17095
|
-
var PairRelayError = class extends Error {
|
|
17096
|
-
constructor(code, message2) {
|
|
17097
|
-
super(message2);
|
|
17098
|
-
this.code = code;
|
|
17099
|
-
}
|
|
17100
|
-
code;
|
|
17101
|
-
};
|
|
17102
|
-
function createPairRelay(input) {
|
|
17103
|
-
const http = createPcHttp({
|
|
17104
|
-
endpoint: input.endpoint,
|
|
17105
|
-
path: "term/pc",
|
|
17106
|
-
tokenProvider: input.tokenProvider,
|
|
17107
|
-
timeoutMs: CALL_TIMEOUT_MS,
|
|
17108
|
-
sessionHeader: "X-Remote-Token",
|
|
17109
|
-
fetchImpl: input.fetchImpl,
|
|
17110
|
-
logging: {
|
|
17111
|
-
log: input.log,
|
|
17112
|
-
request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
|
|
17113
|
-
response: ({ callId, op, ms }, outcome) => ({
|
|
17114
|
-
event: "remote_call_response",
|
|
17115
|
-
callId,
|
|
17116
|
-
op,
|
|
17117
|
-
...outcome.ok ? {
|
|
17118
|
-
ok: true,
|
|
17119
|
-
status: outcome.status,
|
|
17120
|
-
...Array.isArray(outcome.body.msgs) ? { commands: outcome.body.msgs.length } : {},
|
|
17121
|
-
...outcome.body.closed === true ? { state: "CLOSED" } : {}
|
|
17122
|
-
} : outcome,
|
|
17123
|
-
ms
|
|
17124
|
-
})
|
|
17125
|
-
}
|
|
17126
|
-
});
|
|
17127
|
-
let attemptId;
|
|
17128
|
-
let finished = false;
|
|
17129
|
-
const send = async (msg, signal) => {
|
|
17130
|
-
if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The pairing was not opened.");
|
|
17131
|
-
await http.call("pair/send", { attemptId, msg }, signal ? { signal } : void 0);
|
|
17132
|
-
};
|
|
17133
|
-
return {
|
|
17134
|
-
async offer(commit, signal) {
|
|
17135
|
-
const opened = await http.call("pair/open", { pcId: input.pcId }, { signal });
|
|
17136
|
-
if (typeof opened.attemptId !== "string" || opened.attemptId === "") {
|
|
17137
|
-
throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "AiNecto answered pair/open without an attemptId.");
|
|
17138
|
-
}
|
|
17139
|
-
attemptId = opened.attemptId;
|
|
17140
|
-
await send({ type: "commit", commit: b64u2(commit) }, signal);
|
|
17141
|
-
for (; ; ) {
|
|
17142
|
-
const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
|
|
17143
|
-
if (answer.closed === true) {
|
|
17144
|
-
finished = true;
|
|
17145
|
-
throw new PairRelayError("PAIR_CLOSED", "The pairing ended on AiNecto (the browser cancelled it, or it expired).");
|
|
17146
|
-
}
|
|
17147
|
-
const offer = offerOf(Array.isArray(answer.msgs) ? answer.msgs : []);
|
|
17148
|
-
if (offer === "abort") {
|
|
17149
|
-
finished = true;
|
|
17150
|
-
throw new PairRelayError("PAIR_CLOSED", "The browser cancelled the pairing.");
|
|
17151
|
-
}
|
|
17152
|
-
if (offer) return offer;
|
|
17153
|
-
}
|
|
17154
|
-
},
|
|
17155
|
-
async reveal(pcPublicRaw, nP, signal) {
|
|
17156
|
-
await send({ type: "reveal", publicKey: b64u2(pcPublicRaw), nP: b64u2(nP) }, signal);
|
|
17157
|
-
},
|
|
17158
|
-
async done(signature, signal) {
|
|
17159
|
-
await send({ type: "done", signature: b64u2(signature) }, signal);
|
|
17160
|
-
finished = true;
|
|
17161
|
-
},
|
|
17162
|
-
async abort(reason) {
|
|
17163
|
-
if (!attemptId || finished) return;
|
|
17164
|
-
finished = true;
|
|
17165
|
-
try {
|
|
17166
|
-
await send({ type: "abort", reason });
|
|
17167
|
-
} catch {
|
|
17168
|
-
}
|
|
17169
|
-
}
|
|
17170
|
-
};
|
|
17171
|
-
}
|
|
17172
|
-
function offerOf(msgs) {
|
|
17173
|
-
if (msgs.length === 0) return void 0;
|
|
17174
|
-
const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
|
|
17175
|
-
if (items.some((item2) => item2.type === "abort")) return "abort";
|
|
17176
|
-
if (items.length > 1) {
|
|
17177
|
-
throw new PairRelayError("PAIR_DUPLICATE", "More than one pairing request arrived \u2014 this try was ended. Run `ainecto pair` again.");
|
|
17178
|
-
}
|
|
17179
|
-
const [item] = items;
|
|
17180
|
-
const publicRaw = fromB64u2(item?.publicKey, PUBLIC_KEY_BYTES);
|
|
17181
|
-
const nB = fromB64u2(item?.nB, NONCE_SEED_BYTES);
|
|
17182
|
-
if (item?.type !== "offer" || !publicRaw || !nB || typeof item.keyId !== "string" || typeof item.name !== "string") {
|
|
17183
|
-
throw new PairRelayError("PAIR_BAD_MESSAGE", "AiNecto relayed a pairing message this CLI does not understand \u2014 this try was ended.");
|
|
17184
|
-
}
|
|
17185
|
-
return { keyId: item.keyId, publicRaw, nB, name: item.name };
|
|
17186
|
-
}
|
|
17187
|
-
function b64u2(bytes) {
|
|
17188
|
-
return Buffer.from(bytes).toString("base64url");
|
|
17189
|
-
}
|
|
17190
|
-
function fromB64u2(value, length) {
|
|
17191
|
-
if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) return void 0;
|
|
17192
|
-
const bytes = new Uint8Array(Buffer.from(value, "base64url"));
|
|
17193
|
-
return bytes.length === length ? bytes : void 0;
|
|
17194
|
-
}
|
|
17195
|
-
|
|
17196
|
-
// src/adapters/cli/pairCommand.ts
|
|
17197
|
-
var USAGE = "Usage: ainecto pair [--list | --remove <keyId|name>]";
|
|
17198
|
-
function openDevTty() {
|
|
17199
|
-
let inFd;
|
|
17200
|
-
try {
|
|
17201
|
-
inFd = openSync3("/dev/tty", "r");
|
|
17202
|
-
const outFd = openSync3("/dev/tty", "w");
|
|
17203
|
-
const stdin = new ReadStream(inFd);
|
|
17204
|
-
const stderr = new WriteStream(outFd);
|
|
17205
|
-
return { stdin, stderr, close: () => {
|
|
17206
|
-
stdin.destroy();
|
|
17207
|
-
stderr.destroy();
|
|
17208
|
-
} };
|
|
17209
|
-
} catch (error) {
|
|
17210
|
-
if (inFd !== void 0) closeSync3(inFd);
|
|
17211
|
-
throw new CliCommandError("PAIR_NO_TTY", `\`ainecto pair\` needs this PC's terminal (/dev/tty): ${error instanceof Error ? error.message : String(error)}`);
|
|
17212
|
-
}
|
|
17213
|
-
}
|
|
17214
|
-
async function executePair(deps, argv) {
|
|
17215
|
-
const [first, ...rest] = argv;
|
|
17216
|
-
if (first === "--list" && rest.length === 0) {
|
|
17217
|
-
return await listBrowsers(deps);
|
|
17218
|
-
}
|
|
17219
|
-
if (first === "--remove" && rest.length === 1 && rest[0] !== void 0 && rest[0] !== "") {
|
|
17220
|
-
return await removeBrowser(deps, rest[0]);
|
|
17221
|
-
}
|
|
17222
|
-
if (first !== void 0) {
|
|
17223
|
-
throw new CliCommandError("USAGE", USAGE);
|
|
17224
|
-
}
|
|
17225
|
-
return await pair(deps);
|
|
17226
|
-
}
|
|
17227
|
-
async function pair(deps) {
|
|
17228
|
-
if (deps.json || !deps.interactive) {
|
|
17229
|
-
throw new CliCommandError(
|
|
17230
|
-
"PAIR_INTERACTIVE_ONLY",
|
|
17231
|
-
"`ainecto pair` shows a code and asks you to type the code the browser shows \u2014 run it yourself in a terminal (not with --json or a pipe)."
|
|
17232
|
-
);
|
|
17233
|
-
}
|
|
17234
|
-
if (deps.insideTermSession) {
|
|
17235
|
-
throw new CliCommandError(
|
|
17236
|
-
"PAIR_IN_TERM_SESSION",
|
|
17237
|
-
"`ainecto pair` does not run inside an AiNecto terminal session (its screen can be shown on the web). Run it in a regular terminal on this PC."
|
|
17238
|
-
);
|
|
17239
|
-
}
|
|
17240
|
-
const { key, userId } = await account(deps);
|
|
17241
|
-
const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
|
|
17242
|
-
if (!settings.accounts[key]) {
|
|
17243
|
-
throw new CliCommandError("PC_NOT_APPROVED", "This PC is not connected yet \u2014 run `ainecto` in a terminal once to approve, then `ainecto pair`.");
|
|
17244
|
-
}
|
|
17245
|
-
const pcKey = (await loadPcKeys(deps.keysPath)).accounts[key]?.pcKey ?? await generateSigningJwk();
|
|
17246
|
-
const transport = await deps.transport(settings.pcId);
|
|
17247
|
-
const tty = deps.openTty();
|
|
17248
|
-
let outcome;
|
|
17249
|
-
try {
|
|
17250
|
-
outcome = await relayErrors(() => runPairing({
|
|
17251
|
-
userId: transcriptUserId(userId),
|
|
17252
|
-
pcId: settings.pcId,
|
|
17253
|
-
pcKey,
|
|
17254
|
-
transport,
|
|
17255
|
-
prompt: { show: (line) => {
|
|
17256
|
-
tty.stderr.write(`${line}
|
|
17257
|
-
`);
|
|
17258
|
-
}, ask: (question, signal) => promptLine(tty, question, signal) },
|
|
17259
|
-
pin: (browser2) => pin(deps, key, pcKey, browser2),
|
|
17260
|
-
waitMs: deps.waitMs
|
|
17261
|
-
}));
|
|
17262
|
-
} finally {
|
|
17263
|
-
tty.close();
|
|
17409
|
+
} catch {
|
|
17410
|
+
return void 0;
|
|
17264
17411
|
}
|
|
17265
|
-
|
|
17266
|
-
|
|
17412
|
+
}
|
|
17413
|
+
async function executePcStop(deps, argv) {
|
|
17414
|
+
const unknown = argv.filter((arg) => arg !== "--forget");
|
|
17415
|
+
if (unknown.length > 0) {
|
|
17416
|
+
throw new CliCommandError("USAGE", `Unknown argument for stop: ${unknown[0]}. Usage: ainecto stop [--forget]`);
|
|
17267
17417
|
}
|
|
17268
|
-
|
|
17269
|
-
|
|
17418
|
+
const running = deps.termProblem === void 0 ? runningPcs(await listed2(deps)) : [];
|
|
17419
|
+
const lines = [];
|
|
17420
|
+
for (const pc of running) {
|
|
17421
|
+
lines.push(await stopPc(deps, pc));
|
|
17270
17422
|
}
|
|
17271
|
-
if (
|
|
17272
|
-
|
|
17273
|
-
"PAIR_CODE_MISMATCH",
|
|
17274
|
-
"That code does not match. Nothing was saved \u2014 start again with `ainecto pair` (if you typed it right, someone may be in the middle)."
|
|
17275
|
-
);
|
|
17423
|
+
if (running.length === 0) {
|
|
17424
|
+
lines.push("This PC is not connected.");
|
|
17276
17425
|
}
|
|
17277
|
-
const
|
|
17278
|
-
if (
|
|
17279
|
-
|
|
17426
|
+
const forget = argv.includes("--forget");
|
|
17427
|
+
if (forget) {
|
|
17428
|
+
await savePcSettings(deps.settingsPath, withoutEndpoint(await loadPcSettings(deps.settingsPath, deps.hostName), deps.endpoint));
|
|
17429
|
+
lines.push(`Removed your approval for ${deps.endpoint} on this PC; \`ainecto\` asks again next time.`);
|
|
17430
|
+
let removedKeys = false;
|
|
17431
|
+
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17432
|
+
const kept = withoutEndpointKeys(keys, deps.endpoint);
|
|
17433
|
+
removedKeys = Object.keys(kept.accounts).length !== Object.keys(keys.accounts).length;
|
|
17434
|
+
return removedKeys ? kept : void 0;
|
|
17435
|
+
});
|
|
17436
|
+
if (removedKeys) {
|
|
17437
|
+
lines.push("Also removed this PC's terminal key and registered browsers for that server \u2014 register them again with `ainecto pair`.");
|
|
17438
|
+
}
|
|
17280
17439
|
}
|
|
17281
|
-
|
|
17282
|
-
|
|
17283
|
-
|
|
17284
|
-
|
|
17440
|
+
return print2(deps, { stopped: running.map((pc) => pc.session), forgot: forget }, lines.join("\n"));
|
|
17441
|
+
}
|
|
17442
|
+
async function executeRemoteSetting(deps, argv) {
|
|
17443
|
+
const [value, ...rest] = argv;
|
|
17444
|
+
if (value !== "on" && value !== "off" || rest.length > 0) {
|
|
17445
|
+
throw new CliCommandError("USAGE", "Usage: ainecto remote on|off");
|
|
17285
17446
|
}
|
|
17286
|
-
deps.
|
|
17447
|
+
const userId = (await deps.account()).userId;
|
|
17448
|
+
if (!userId) {
|
|
17449
|
+
throw new CliCommandError("PC_ACCOUNT_UNKNOWN", "Could not read your AiNecto account \u2014 run `ainecto doctor` to see why.");
|
|
17450
|
+
}
|
|
17451
|
+
const next = withRemoteTerminal(await loadPcSettings(deps.settingsPath, deps.hostName), accountKey(deps.endpoint, userId), value === "on");
|
|
17452
|
+
if (!next) {
|
|
17453
|
+
throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName));
|
|
17454
|
+
}
|
|
17455
|
+
await savePcSettings(deps.settingsPath, next);
|
|
17456
|
+
const said = value === "on" ? "Terminals from AiNecto on the web are allowed on this PC." : "Terminals from AiNecto on the web are blocked on this PC.";
|
|
17457
|
+
const running = deps.termProblem === void 0 ? runningPcs(await listed2(deps)) : [];
|
|
17458
|
+
const key = accountKey(deps.endpoint, userId);
|
|
17459
|
+
if (running.length === 0) {
|
|
17460
|
+
return await withRegistration(deps, key, userId, print2(deps, { remoteTerminal: value === "on" }, said));
|
|
17461
|
+
}
|
|
17462
|
+
if (!deps.json) deps.io.stdout.write(`${said}
|
|
17287
17463
|
`);
|
|
17288
|
-
|
|
17464
|
+
deps.io.stderr.write("Reconnecting this PC so it takes effect\u2026\n");
|
|
17465
|
+
for (const pc of running) {
|
|
17466
|
+
await stopPc(deps, pc);
|
|
17467
|
+
}
|
|
17468
|
+
return await withRegistration(deps, key, userId, await launchPc(deps));
|
|
17289
17469
|
}
|
|
17290
|
-
async function
|
|
17291
|
-
|
|
17292
|
-
|
|
17293
|
-
|
|
17294
|
-
|
|
17295
|
-
|
|
17296
|
-
|
|
17297
|
-
throw new CliCommandError("PAIR_REMOVE_PENDING", `This browser's earlier removal has not finished. Nothing was saved \u2014 run \`ainecto pair --remove ${browser.keyId}\` first, then \`ainecto pair\` again.`);
|
|
17470
|
+
async function runningPcGroups(deps) {
|
|
17471
|
+
assertQueryable(deps);
|
|
17472
|
+
const groups = [];
|
|
17473
|
+
for (const session of (await listedToTurnOff(deps)).filter((item) => runningPcs([item]).length > 0)) {
|
|
17474
|
+
const pgid = await processGroupOf(session.pid);
|
|
17475
|
+
if (pgid === void 0) {
|
|
17476
|
+
throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not read the process group of the PC connection (session ${session.name}, pid ${session.pid}), so its end cannot be confirmed.${processGroupUnavailableHint()}`);
|
|
17298
17477
|
}
|
|
17299
|
-
|
|
17300
|
-
}
|
|
17478
|
+
groups.push({ session: session.name, pid: session.pid, pgid });
|
|
17479
|
+
}
|
|
17480
|
+
return groups;
|
|
17301
17481
|
}
|
|
17302
|
-
async function
|
|
17303
|
-
|
|
17304
|
-
const
|
|
17305
|
-
|
|
17306
|
-
|
|
17307
|
-
|
|
17308
|
-
|
|
17482
|
+
async function turnOffPcs(deps, groups) {
|
|
17483
|
+
assertQueryable(deps);
|
|
17484
|
+
for (const group of groups) {
|
|
17485
|
+
const session = (await listedToTurnOff(deps)).find((item) => item.name === group.session && item.pid === group.pid);
|
|
17486
|
+
const [pc] = session ? runningPcs([session]) : [];
|
|
17487
|
+
if (pc) await stopPc(deps, pc);
|
|
17488
|
+
await confirmEnded(deps, group);
|
|
17489
|
+
}
|
|
17309
17490
|
}
|
|
17310
|
-
|
|
17311
|
-
|
|
17312
|
-
|
|
17313
|
-
let target;
|
|
17314
|
-
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17315
|
-
const result = withoutBrowser(keys, key, keyIdOrName);
|
|
17316
|
-
removed = result.removed;
|
|
17317
|
-
if (!removed) {
|
|
17318
|
-
target = pendingRemovalOf(keys.accounts[key], keyIdOrName);
|
|
17319
|
-
return void 0;
|
|
17320
|
-
}
|
|
17321
|
-
target = { removalId: randomUUID7(), keyId: removed.keyId, name: removed.name };
|
|
17322
|
-
return withPendingTurnOff(result.keys, key, { at: deps.now(), groups: [], removal: target });
|
|
17323
|
-
});
|
|
17324
|
-
if (!target) {
|
|
17325
|
-
throw new CliCommandError("PAIR_NOT_FOUND", `No paired browser with key id or name "${keyIdOrName}" \u2014 \`ainecto pair --list\` shows them.`);
|
|
17491
|
+
function assertQueryable(deps) {
|
|
17492
|
+
if (deps.termProblem !== void 0) {
|
|
17493
|
+
throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not check the PC connection (ainecto term: ${deps.termProblem}).`);
|
|
17326
17494
|
}
|
|
17327
|
-
|
|
17328
|
-
|
|
17329
|
-
|
|
17330
|
-
|
|
17331
|
-
|
|
17332
|
-
|
|
17333
|
-
|
|
17334
|
-
|
|
17335
|
-
|
|
17336
|
-
|
|
17337
|
-
|
|
17338
|
-
|
|
17495
|
+
}
|
|
17496
|
+
var STOP_CONFIRM_POLL_MS = 100;
|
|
17497
|
+
async function confirmEnded(deps, group) {
|
|
17498
|
+
const deadline = Date.now() + deps.stopDeadlineMs;
|
|
17499
|
+
for (; ; ) {
|
|
17500
|
+
const stillListed = (await listedToTurnOff(deps)).some((session) => session.name === group.session && session.pid === group.pid);
|
|
17501
|
+
const alive = processGroupAlive(group.pgid);
|
|
17502
|
+
if (!stillListed && !alive) return;
|
|
17503
|
+
if (Date.now() >= deadline) {
|
|
17504
|
+
const what = stillListed ? "the session is still running" : `a process in its group ${group.pgid} is still alive`;
|
|
17505
|
+
throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not confirm that the PC connection (session ${group.session}, pid ${group.pid}) ended within ${deps.stopDeadlineMs / 1e3} s (${what}). See ${deps.agentLog}.`);
|
|
17506
|
+
}
|
|
17507
|
+
await new Promise((resolve4) => setTimeout(resolve4, STOP_CONFIRM_POLL_MS));
|
|
17339
17508
|
}
|
|
17340
|
-
await updatePcKeys(deps.keysPath, (keys) => {
|
|
17341
|
-
const next = withTurnOffConfirmed(keys, key, { groups, removalId });
|
|
17342
|
-
return next === keys ? void 0 : next;
|
|
17343
|
-
});
|
|
17344
|
-
const lines = [removed ? `Removed "${removed.name}" (${removed.keyId}). It can no longer open terminals on this PC.` : "Finished the earlier removal."];
|
|
17345
|
-
lines.push(groups.length > 0 ? "Turned off the PC connection. Run `ainecto` to turn it back on." : "The PC connection is not running.");
|
|
17346
|
-
deps.io.stdout.write(deps.json ? renderSuccess({ removed: removed ? { keyId: removed.keyId, name: removed.name } : null, turnedOff: groups }, { json: true }) : `${lines.join("\n")}
|
|
17347
|
-
`);
|
|
17348
|
-
return 0;
|
|
17349
17509
|
}
|
|
17350
|
-
async function
|
|
17510
|
+
async function stopPc(deps, pc) {
|
|
17511
|
+
const client = await openTermClient(deps.paths, { start: false });
|
|
17512
|
+
if (!client) {
|
|
17513
|
+
return `Session ${pc.session} is already gone.`;
|
|
17514
|
+
}
|
|
17515
|
+
let timer;
|
|
17351
17516
|
try {
|
|
17352
|
-
|
|
17353
|
-
|
|
17354
|
-
|
|
17355
|
-
|
|
17517
|
+
let ready;
|
|
17518
|
+
try {
|
|
17519
|
+
ready = pcOutcome(readLines(await client.request({ op: "read", name: pc.session, scrollback: true })))?.kind === "connected";
|
|
17520
|
+
} catch (error) {
|
|
17521
|
+
if (error instanceof TermError && error.code === "TERM_NO_SESSION") {
|
|
17522
|
+
return `Session ${pc.session} is already gone.`;
|
|
17523
|
+
}
|
|
17524
|
+
throw error;
|
|
17356
17525
|
}
|
|
17357
|
-
if (
|
|
17358
|
-
|
|
17526
|
+
if (!ready) {
|
|
17527
|
+
await client.request({ op: "kill", name: pc.session });
|
|
17528
|
+
return `Session ${pc.session} was still starting \u2014 ended it.`;
|
|
17359
17529
|
}
|
|
17360
|
-
|
|
17530
|
+
const ended = new Promise((resolve4) => {
|
|
17531
|
+
client.onEvent((event) => {
|
|
17532
|
+
if (event.event === "exit") {
|
|
17533
|
+
resolve4("ended");
|
|
17534
|
+
}
|
|
17535
|
+
});
|
|
17536
|
+
client.onClose(() => resolve4("ended"));
|
|
17537
|
+
});
|
|
17538
|
+
try {
|
|
17539
|
+
await client.request({ op: "watch", name: pc.session });
|
|
17540
|
+
await client.request({ op: "key", name: pc.session, key: "ctrl-c" });
|
|
17541
|
+
} catch (error) {
|
|
17542
|
+
if (error instanceof TermError && error.code === "TERM_NO_SESSION") {
|
|
17543
|
+
return `Session ${pc.session} is already gone.`;
|
|
17544
|
+
}
|
|
17545
|
+
throw error;
|
|
17546
|
+
}
|
|
17547
|
+
const outcome = await Promise.race([ended, new Promise((resolve4) => {
|
|
17548
|
+
timer = setTimeout(() => resolve4("late"), deps.stopDeadlineMs);
|
|
17549
|
+
})]);
|
|
17550
|
+
if (outcome === "ended") {
|
|
17551
|
+
return `Disconnected this PC (session ${pc.session}).`;
|
|
17552
|
+
}
|
|
17553
|
+
await termRequest(deps.paths, { op: "kill", name: pc.session }, { start: false });
|
|
17554
|
+
return `Session ${pc.session} did not stop within ${deps.stopDeadlineMs / 1e3} s after Ctrl+C \u2014 ended it. See ${deps.agentLog}.`;
|
|
17555
|
+
} finally {
|
|
17556
|
+
clearTimeout(timer);
|
|
17557
|
+
client.close();
|
|
17361
17558
|
}
|
|
17362
17559
|
}
|
|
17363
|
-
async function
|
|
17364
|
-
const
|
|
17365
|
-
if (!
|
|
17366
|
-
throw new
|
|
17560
|
+
async function prepare(deps) {
|
|
17561
|
+
const [command, ...args] = deps.managedCommand(["--version"]);
|
|
17562
|
+
if (!command) {
|
|
17563
|
+
throw new Error("The PC connection command is empty.");
|
|
17367
17564
|
}
|
|
17368
|
-
|
|
17565
|
+
const result = await deps.runner(command, args);
|
|
17566
|
+
if (result.missing || result.exitCode !== 0) {
|
|
17567
|
+
throw new CliCommandError("PC_PREPARE_FAILED", `\`${[command, ...args].join(" ")}\` failed${result.missing ? ` (${command} is not on PATH)` : ""}: ${lastLine(result.stderr) ?? lastLine(result.stdout) ?? `exit ${result.exitCode}`}`);
|
|
17568
|
+
}
|
|
17569
|
+
}
|
|
17570
|
+
async function listed2(deps, connect2 = { start: false }) {
|
|
17571
|
+
const result = await termRequest(deps.paths, { op: "ls" }, connect2);
|
|
17572
|
+
return listedSessions(result.daemon ? result.data : void 0);
|
|
17573
|
+
}
|
|
17574
|
+
async function listedToTurnOff(deps) {
|
|
17575
|
+
return await listed2(deps, { start: false, resetFails: true });
|
|
17576
|
+
}
|
|
17577
|
+
function assertTerm(deps) {
|
|
17578
|
+
if (deps.termProblem !== void 0) {
|
|
17579
|
+
throw new CliCommandError("PC_UNSUPPORTED", `Connecting this PC needs ainecto term: ${deps.termProblem}`);
|
|
17580
|
+
}
|
|
17581
|
+
}
|
|
17582
|
+
function pcView(deps, pc) {
|
|
17583
|
+
return { session: pc.session, folder: pc.cwd, version: pcVersionLabel(pc), log: deps.agentLog };
|
|
17584
|
+
}
|
|
17585
|
+
function yes(answer, byDefault) {
|
|
17586
|
+
const value = answer.trim().toLowerCase();
|
|
17587
|
+
return value === "" ? byDefault : value === "y" || value === "yes";
|
|
17588
|
+
}
|
|
17589
|
+
function print2(deps, data, human) {
|
|
17590
|
+
deps.io.stdout.write(deps.json ? renderSuccess(data, { json: true }) : `${human}
|
|
17591
|
+
`);
|
|
17592
|
+
return 0;
|
|
17369
17593
|
}
|
|
17370
17594
|
|
|
17371
17595
|
// src/core/pc/pcNotify.ts
|
|
17372
17596
|
var NOTIFY_BATCH_MS = 6e4;
|
|
17373
17597
|
var WHAT = {
|
|
17374
|
-
paired: "was
|
|
17598
|
+
paired: "was registered with this PC",
|
|
17375
17599
|
session: "opened a terminal connection to this PC",
|
|
17376
17600
|
shell: "started a new shell on this PC",
|
|
17377
17601
|
command: "started a command in a new terminal on this PC"
|
|
@@ -17718,19 +17942,6 @@ async function pcStatus(status, endpoint) {
|
|
|
17718
17942
|
// src/adapters/cli/agentCommand.ts
|
|
17719
17943
|
import { hostname as hostname3 } from "os";
|
|
17720
17944
|
|
|
17721
|
-
// src/core/async/stopSignals.ts
|
|
17722
|
-
var STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
17723
|
-
function onStopSignals(handler) {
|
|
17724
|
-
for (const signal of STOP_SIGNALS) {
|
|
17725
|
-
process.on(signal, handler);
|
|
17726
|
-
}
|
|
17727
|
-
return () => {
|
|
17728
|
-
for (const signal of STOP_SIGNALS) {
|
|
17729
|
-
process.off(signal, handler);
|
|
17730
|
-
}
|
|
17731
|
-
};
|
|
17732
|
-
}
|
|
17733
|
-
|
|
17734
17945
|
// src/core/agent/child.ts
|
|
17735
17946
|
import { createInterface as createInterface3 } from "readline";
|
|
17736
17947
|
var spawnAgent = (command, args, options) => spawnPiped([command, ...args], options);
|
|
@@ -18837,9 +19048,9 @@ async function runPcRemote(setup, signal, onAnswer) {
|
|
|
18837
19048
|
var AGENT_HELP_LINES = [
|
|
18838
19049
|
" ainecto in a terminal, with no arguments: check sign-in, ask once, then connect this PC in the background (same as ainecto start)",
|
|
18839
19050
|
" ainecto start [--env prod|dev] connect this PC in the background \u2014 keeps running after you close the window (log: ~/.ainecto/agent/agent.log)",
|
|
18840
|
-
" ainecto stop [--forget] disconnect this PC now (--forget also removes your approval and
|
|
19051
|
+
" ainecto stop [--forget] disconnect this PC now (--forget also removes your approval and registered browsers on this PC)",
|
|
18841
19052
|
" ainecto remote on|off allow or block terminals from AiNecto on the web on this PC",
|
|
18842
|
-
" ainecto pair [--list | --remove <keyId|name>]
|
|
19053
|
+
" ainecto pair [--list | --remove <keyId|name>] register a web browser with this PC by typing codes shown on both (once per browser)"
|
|
18843
19054
|
];
|
|
18844
19055
|
function isPcRunCommand(domain, action) {
|
|
18845
19056
|
return domain === "pc" && action === "run";
|
|
@@ -19059,6 +19270,17 @@ async function runAinectoCli(argv, io) {
|
|
|
19059
19270
|
envVars: process.env
|
|
19060
19271
|
};
|
|
19061
19272
|
};
|
|
19273
|
+
const insideTermSession = process.env[SESSION_ENV] !== void 0;
|
|
19274
|
+
const pairTransport = async (pcId) => {
|
|
19275
|
+
const paths = termPaths();
|
|
19276
|
+
await ensurePrivateDir(paths.dir);
|
|
19277
|
+
return createPairRelay({ endpoint: resolved.endpoint, tokenProvider: connect2().auth, log: openRemoteLog(paths), pcId, holdMs: PAIR_WAIT_MS });
|
|
19278
|
+
};
|
|
19279
|
+
const notifyPaired = async (browser) => {
|
|
19280
|
+
const paths = termPaths();
|
|
19281
|
+
await ensurePrivateDir(paths.dir);
|
|
19282
|
+
await createPcNotifier({ log: openRemoteLog(paths) }).notify({ kind: "paired", keyId: browser.keyId, browserName: browser.name });
|
|
19283
|
+
};
|
|
19062
19284
|
const pcDeps = () => ({
|
|
19063
19285
|
io,
|
|
19064
19286
|
json: parsed.json,
|
|
@@ -19080,7 +19302,21 @@ async function runAinectoCli(argv, io) {
|
|
|
19080
19302
|
readyDeadlineMs: pcReadyDeadlineMs(),
|
|
19081
19303
|
machine: () => collectStatus(collectInput()),
|
|
19082
19304
|
account: () => readAccount(connect2().client),
|
|
19083
|
-
setup: () => runSetup([])
|
|
19305
|
+
setup: () => runSetup([]),
|
|
19306
|
+
register: {
|
|
19307
|
+
insideTermSession,
|
|
19308
|
+
overSsh: process.env.SSH_CONNECTION !== void 0 || process.env.SSH_TTY !== void 0,
|
|
19309
|
+
openBrowser: (url) => launchBrowser(url),
|
|
19310
|
+
transport: pairTransport,
|
|
19311
|
+
notifyPaired,
|
|
19312
|
+
waitMs: PAIR_WAIT_MS,
|
|
19313
|
+
interrupt: () => {
|
|
19314
|
+
const controller = new AbortController();
|
|
19315
|
+
const off = onStopSignals(() => controller.abort());
|
|
19316
|
+
return { signal: controller.signal, dispose: off };
|
|
19317
|
+
},
|
|
19318
|
+
now: () => /* @__PURE__ */ new Date()
|
|
19319
|
+
}
|
|
19084
19320
|
});
|
|
19085
19321
|
if (domain === void 0 || domain === "start") {
|
|
19086
19322
|
if (rest.length > 0 || domain === "start" && action !== void 0) {
|
|
@@ -19099,26 +19335,19 @@ async function runAinectoCli(argv, io) {
|
|
|
19099
19335
|
io,
|
|
19100
19336
|
json: parsed.json,
|
|
19101
19337
|
interactive,
|
|
19102
|
-
insideTermSession
|
|
19338
|
+
insideTermSession,
|
|
19103
19339
|
openTty: openDevTty,
|
|
19104
19340
|
settingsPath: pcSettingsPath(),
|
|
19105
19341
|
keysPath: pcKeysPath(),
|
|
19106
19342
|
hostName: hostname4(),
|
|
19107
19343
|
endpoint: resolved.endpoint,
|
|
19108
19344
|
account: () => readAccount(connect2().client),
|
|
19109
|
-
|
|
19110
|
-
|
|
19111
|
-
const paths = termPaths();
|
|
19112
|
-
await ensurePrivateDir(paths.dir);
|
|
19113
|
-
return createPairRelay({ endpoint: resolved.endpoint, tokenProvider: connect2().auth, log: openRemoteLog(paths), pcId, holdMs: PAIR_WAIT_MS });
|
|
19114
|
-
},
|
|
19115
|
-
notifyPaired: async (browser) => {
|
|
19116
|
-
const paths = termPaths();
|
|
19117
|
-
await ensurePrivateDir(paths.dir);
|
|
19118
|
-
await createPcNotifier({ log: openRemoteLog(paths) }).notify({ kind: "paired", keyId: browser.keyId, browserName: browser.name });
|
|
19119
|
-
},
|
|
19345
|
+
transport: pairTransport,
|
|
19346
|
+
notifyPaired,
|
|
19120
19347
|
findPcs: () => runningPcGroups(pcDeps()),
|
|
19121
19348
|
turnOffPcs: (groups) => turnOffPcs(pcDeps(), groups),
|
|
19349
|
+
// 연결 승인 전 대화형 — `ainecto`(인자 없음)와 같은 흐름 그대로(KAN-1348). 자동 등록은 빼고 이어서 코드로 등록한다.
|
|
19350
|
+
connectPc: () => executePcStart({ ...pcDeps(), register: void 0 }),
|
|
19122
19351
|
waitMs: PAIR_WAIT_MS,
|
|
19123
19352
|
now: () => /* @__PURE__ */ new Date()
|
|
19124
19353
|
}, parsed.positionals.slice(1));
|