@ainecto/mcp 0.15.0 → 0.15.3

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.
@@ -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.0" : UNBUNDLED_VERSION;
5690
- var CLI_BUILD = true ? "809aaf7" : void 0;
5702
+ var CLI_VERSION = true ? "0.15.3" : UNBUNDLED_VERSION;
5703
+ var CLI_BUILD = true ? "b93ea31" : 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
- child.once("error", (error) => reject(unavailable(error.message)));
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,10 @@ 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
+ }
10148
10168
  function notifyTool(platform = process.platform) {
10149
10169
  if (platform === "darwin") {
10150
10170
  return {
@@ -10165,10 +10185,29 @@ function notifyTool(platform = process.platform) {
10165
10185
  if (platform === "linux") {
10166
10186
  return { name: "notify-send", file: "notify-send", args: (title, body) => ["--", title, body] };
10167
10187
  }
10188
+ if (platform === "win32") {
10189
+ return { name: "powershell", file: "powershell.exe", args: (title, body) => ["-NoProfile", "-NonInteractive", "-EncodedCommand", windowsToastScript(title, body)] };
10190
+ }
10168
10191
  return void 0;
10169
10192
  }
10193
+ function windowsToastScript(title, body) {
10194
+ const b64 = (text2) => Buffer.from(text2, "utf8").toString("base64");
10195
+ const script = [
10196
+ "$ErrorActionPreference = 'Stop'",
10197
+ `$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title)}'))`,
10198
+ `$b = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(body)}'))`,
10199
+ "[void][Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]",
10200
+ "$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)",
10201
+ "$n = $x.GetElementsByTagName('text')",
10202
+ "[void]$n.Item(0).AppendChild($x.CreateTextNode($t))",
10203
+ "[void]$n.Item(1).AppendChild($x.CreateTextNode($b))",
10204
+ "$app = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'",
10205
+ "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show([Windows.UI.Notifications.ToastNotification]::new($x))"
10206
+ ].join("\n");
10207
+ return Buffer.from(script, "utf16le").toString("base64");
10208
+ }
10170
10209
  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 pairs or opens a terminal here." : void 0;
10210
+ 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
10211
  }
10173
10212
 
10174
10213
  // src/core/setup/accountSummary.ts
@@ -12819,12 +12858,13 @@ var TermDaemon = class {
12819
12858
  }
12820
12859
  }
12821
12860
  /**
12822
- * 세션이 스스로 끝났다. ★매니페스트에서 지우는 것은 «신호 없이» 끝났을 때만이다 — 신호로 끝난 세션(재부팅·로그아웃 때
12823
- * 시스템이 보낸 SIGTERM·SIGHUP 포함)은 `restore` 가 다시 띄울 수 있게 남긴다. kill 로 지운 세션은 이미 표에 없다.
12861
+ * 세션이 스스로 끝났다. ★매니페스트에서 지우는 것은 «바깥 사정 없이» 끝났을 때만이다 — 신호로 끝난 세션(재부팅·로그아웃 때
12862
+ * 시스템이 보낸 SIGTERM·SIGHUP 포함 · Windows 는 콘솔 닫힘 끝 코드 — launch.endedFromOutside)은 `restore` 가 다시 띄울 수 있게
12863
+ * 남긴다. kill 로 지운 세션은 이미 표에 없다.
12824
12864
  */
12825
12865
  sessionEnded(session, exitCode2, signal) {
12826
12866
  const current = this.sessions.get(session.name) === session;
12827
- const kept = current && signal !== 0;
12867
+ const kept = current && endedFromOutside(exitCode2, signal);
12828
12868
  if (current) {
12829
12869
  this.sessions.delete(session.name);
12830
12870
  if (!kept) {
@@ -14794,20 +14834,21 @@ async function release(lockPath, token) {
14794
14834
  }
14795
14835
 
14796
14836
  // src/core/term/e2e.ts
14797
- import { webcrypto } from "crypto";
14837
+ import { timingSafeEqual as timingSafeEqual2, webcrypto } from "crypto";
14798
14838
  var subtle = webcrypto.subtle;
14799
14839
  var VERSION = "ainecto-e2e-v1";
14800
14840
  var PAIR_LABEL = "ainecto-pair-v1";
14801
14841
  var PAIR_DONE_LABEL = "ainecto-pair-v1/done";
14802
- var PAIR_CODE_INFO = { a: "ainecto-pair-code-A", b: "ainecto-pair-code-B" };
14842
+ var REGISTER_INFO = { browser: "ainecto-register-v1 browser", pc: "ainecto-register-v1 pc", account: "ainecto-register-v1 account" };
14843
+ var REGISTER_OFFER_LABEL = "ainecto-register-v1/offer";
14844
+ var REGISTER_REVEAL_LABEL = "ainecto-register-v1/reveal";
14845
+ var REGISTER_TAG_BYTES = 8;
14803
14846
  var KEY_INFO = { browserToPc: "ainecto-e2e-v1 b2p", pcToBrowser: "ainecto-e2e-v1 p2b", connId: "ainecto-e2e-v1 conn-id" };
14804
- var PAIR_CODE_LIMIT = 4294e6;
14805
14847
  var MAX_MESSAGES_PER_KEY = 2 ** 32;
14806
14848
  var PUBLIC_KEY_BYTES = 65;
14807
14849
  var NONCE_SEED_BYTES = 32;
14808
14850
  var SIGNATURE_BYTES = 64;
14809
14851
  var CONN_ID_BYTES = 16;
14810
- var PAIR_CODE_DIGITS = 6;
14811
14852
  var E2eError = class extends Error {
14812
14853
  constructor(code, message2) {
14813
14854
  super(message2);
@@ -14901,8 +14942,8 @@ function publicJwkFromRaw(raw) {
14901
14942
  return { kty: "EC", crv: "P-256", x: base64url(raw.subarray(1, 33)), y: base64url(raw.subarray(33, 65)) };
14902
14943
  }
14903
14944
  async function generateSigningJwk() {
14904
- const pair2 = await subtle.generateKey(ECDSA, true, ["sign", "verify"]);
14905
- const jwk = asPrivateJwk(await subtle.exportKey("jwk", pair2.privateKey));
14945
+ const pair = await subtle.generateKey(ECDSA, true, ["sign", "verify"]);
14946
+ const jwk = asPrivateJwk(await subtle.exportKey("jwk", pair.privateKey));
14906
14947
  if (!jwk) {
14907
14948
  throw new Error("WebCrypto returned an unexpected P-256 JWK.");
14908
14949
  }
@@ -14931,8 +14972,8 @@ async function verifyBytes(publicKey, signature, data) {
14931
14972
  }
14932
14973
  }
14933
14974
  async function generateEphemeral() {
14934
- const pair2 = await subtle.generateKey(ECDH, false, ["deriveBits"]);
14935
- return { privateKey: pair2.privateKey, publicRaw: new Uint8Array(await subtle.exportKey("raw", pair2.publicKey)) };
14975
+ const pair = await subtle.generateKey(ECDH, false, ["deriveBits"]);
14976
+ return { privateKey: pair.privateKey, publicRaw: new Uint8Array(await subtle.exportKey("raw", pair.publicKey)) };
14936
14977
  }
14937
14978
  var USER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
14938
14979
  function transcriptUserId(raw) {
@@ -14949,11 +14990,6 @@ async function browserKeyIdOf(browserPublicRaw) {
14949
14990
  expectLength("browserPub", browserPublicRaw, PUBLIC_KEY_BYTES);
14950
14991
  return Buffer.from((await sha256(browserPublicRaw)).subarray(0, 16)).toString("hex");
14951
14992
  }
14952
- function pairCodeInput(raw) {
14953
- const trimmed = raw.trim();
14954
- if (trimmed === "") return { kind: "empty" };
14955
- return new RegExp(`^[0-9]{${PAIR_CODE_DIGITS}}$`).test(trimmed) ? { kind: "code", code: trimmed } : { kind: "invalid" };
14956
- }
14957
14993
  async function pairCommitment(pcPublicRaw, nP) {
14958
14994
  expectLength("pcPub", pcPublicRaw, PUBLIC_KEY_BYTES);
14959
14995
  expectLength("nP", nP, NONCE_SEED_BYTES);
@@ -14967,34 +15003,52 @@ async function pairTranscript(input) {
14967
15003
  expectLength("nB", input.nB, NONCE_SEED_BYTES);
14968
15004
  return await sha256(enc(PAIR_LABEL, input.userId, input.pcId, input.pcPublicRaw, input.browserPublicRaw, input.nP, input.nB));
14969
15005
  }
14970
- function pairCodeFromBlock(block) {
14971
- expectLength("code block", block, 32);
14972
- const view = new DataView(block.buffer, block.byteOffset, block.byteLength);
14973
- for (let offset = 0; offset < 32; offset += 4) {
14974
- const value = view.getUint32(offset, false);
14975
- if (value < PAIR_CODE_LIMIT) {
14976
- return String(value % 10 ** PAIR_CODE_DIGITS).padStart(PAIR_CODE_DIGITS, "0");
14977
- }
14978
- }
14979
- return void 0;
14980
- }
14981
- async function pairCodes(transcript) {
14982
- expectLength("transcript", transcript, 32);
14983
- const prk = await subtle.importKey("raw", transcript, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
14984
- const code = async (info) => {
14985
- const block = new Uint8Array(await subtle.sign("HMAC", prk, concatBytes(utf8(info), Uint8Array.of(1))));
14986
- const value = pairCodeFromBlock(block);
14987
- if (value === void 0) {
14988
- throw new E2eError("E2E_PAIR_CODE_UNAVAILABLE", "No usable pairing code in this attempt \u2014 run `ainecto pair` again.");
14989
- }
14990
- return value;
14991
- };
14992
- return { a: await code(PAIR_CODE_INFO.a), b: await code(PAIR_CODE_INFO.b) };
14993
- }
14994
15006
  function pairDoneInput(transcript) {
14995
15007
  expectLength("transcript", transcript, 32);
14996
15008
  return enc(PAIR_DONE_LABEL, transcript);
14997
15009
  }
15010
+ async function registerKeys(secret) {
15011
+ expectLength("register secret", secret, NONCE_SEED_BYTES);
15012
+ const ikm = await subtle.importKey("raw", secret, "HKDF", false, ["deriveBits"]);
15013
+ const derive = async (info) => new Uint8Array(await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: utf8(info) }, ikm, 256));
15014
+ return { browser: await derive(REGISTER_INFO.browser), pc: await derive(REGISTER_INFO.pc), account: await derive(REGISTER_INFO.account) };
15015
+ }
15016
+ async function hmac(key, data) {
15017
+ expectLength("mac key", key, 32);
15018
+ const imported = await subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
15019
+ return new Uint8Array(await subtle.sign("HMAC", imported, data));
15020
+ }
15021
+ async function registerOfferMac(browserKey, input) {
15022
+ expectLength("commit", input.commit, 32);
15023
+ expectLength("browserPub", input.browserPublicRaw, PUBLIC_KEY_BYTES);
15024
+ expectLength("nB", input.nB, NONCE_SEED_BYTES);
15025
+ return await hmac(browserKey, enc(
15026
+ REGISTER_OFFER_LABEL,
15027
+ input.userId,
15028
+ input.pcId,
15029
+ input.attemptId,
15030
+ input.commit,
15031
+ input.browserPublicRaw,
15032
+ input.keyId,
15033
+ input.nB,
15034
+ input.name
15035
+ ));
15036
+ }
15037
+ async function registerRevealMac(pcKey, input) {
15038
+ expectLength("transcript", input.transcript, 32);
15039
+ return await hmac(pcKey, enc(REGISTER_REVEAL_LABEL, input.transcript, input.attemptId));
15040
+ }
15041
+ async function registerTag(accountKey2, userId) {
15042
+ return base64url((await hmac(accountKey2, utf8(userId))).subarray(0, REGISTER_TAG_BYTES));
15043
+ }
15044
+ var REGISTER_PATH = "/api/v1/public/term-register";
15045
+ function registerFragment(input) {
15046
+ expectLength("register secret", input.secret, NONCE_SEED_BYTES);
15047
+ return `1.${input.pcId}.${input.tag}.${base64url(input.secret)}`;
15048
+ }
15049
+ function macEquals(a, b) {
15050
+ return a.length === b.length && timingSafeEqual2(a, b);
15051
+ }
14998
15052
  function assertHello(hello) {
14999
15053
  expectUserId(hello.userId);
15000
15054
  expectLength("eB", hello.eB, PUBLIC_KEY_BYTES);
@@ -15151,7 +15205,7 @@ async function loadPcKeys(path) {
15151
15205
  try {
15152
15206
  return normalizePcKeys(JSON.parse(raw));
15153
15207
  } catch (error) {
15154
- throw new Error(`${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}). Delete it to pair again.`);
15208
+ throw new Error(`${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}). Delete it and register your browsers again by running \`npx -y ainecto@latest\`.`);
15155
15209
  }
15156
15210
  }
15157
15211
  var PC_KEYS_LOCK = { waitMs: 5e3, pollMs: 50 };
@@ -16654,9 +16708,172 @@ function pcOutcome(lines) {
16654
16708
  return failed === void 0 ? void 0 : { kind: "failed", line: failed };
16655
16709
  }
16656
16710
 
16711
+ // src/core/pc/pcPairing.ts
16712
+ var PAIR_WAIT_MS = 5 * 6e4;
16713
+ async function runPairing(input) {
16714
+ const deadline = new AbortController();
16715
+ const timer = setTimeout(() => deadline.abort(), input.waitMs);
16716
+ let cancelled = false;
16717
+ const onCancel = () => {
16718
+ cancelled = true;
16719
+ deadline.abort();
16720
+ };
16721
+ input.cancel?.addEventListener("abort", onCancel, { once: true });
16722
+ if (input.cancel?.aborted) onCancel();
16723
+ const { signal } = deadline;
16724
+ const relayed = async (step) => {
16725
+ try {
16726
+ return await step();
16727
+ } catch (error) {
16728
+ if (signal.aborted) return "timeout";
16729
+ throw error;
16730
+ }
16731
+ };
16732
+ let outcome;
16733
+ try {
16734
+ outcome = await pairOnce();
16735
+ if (cancelled && outcome.kind === "timeout") outcome = { kind: "cancelled" };
16736
+ return outcome;
16737
+ } finally {
16738
+ clearTimeout(timer);
16739
+ input.cancel?.removeEventListener("abort", onCancel);
16740
+ if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
16741
+ }
16742
+ async function pairOnce() {
16743
+ const pcPublicRaw = publicRawFromJwk(input.pcKey);
16744
+ const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
16745
+ const commit = await pairCommitment(pcPublicRaw, nP);
16746
+ const offer = await relayed(() => input.transport.offer(commit, signal));
16747
+ if (offer === "timeout") return { kind: "timeout" };
16748
+ const publicJwk = publicJwkFromRaw(offer.publicRaw);
16749
+ await assertSigningPublicKey(publicJwk);
16750
+ if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
16751
+ throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 browser registration aborted.");
16752
+ }
16753
+ const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
16754
+ const transcript = () => pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
16755
+ const keys = await registerKeys(input.secret);
16756
+ const expected = await registerOfferMac(keys.browser, {
16757
+ userId: input.userId,
16758
+ pcId: input.pcId,
16759
+ attemptId: offer.attemptId,
16760
+ commit,
16761
+ browserPublicRaw: offer.publicRaw,
16762
+ keyId: offer.keyId,
16763
+ nB: offer.nB,
16764
+ name: offer.name
16765
+ });
16766
+ if (!offer.macB || !macEquals(offer.macB, expected)) return { kind: "code-mismatch" };
16767
+ const t = await transcript();
16768
+ await input.pin(browser);
16769
+ const macP = await registerRevealMac(keys.pc, { transcript: t, attemptId: offer.attemptId });
16770
+ return await finish(browser, t, () => input.transport.reveal(pcPublicRaw, nP, signal, macP));
16771
+ }
16772
+ async function finish(browser, transcript, before) {
16773
+ const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
16774
+ let doneError;
16775
+ try {
16776
+ await before();
16777
+ await input.transport.done(signature, signal);
16778
+ } catch (error) {
16779
+ doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
16780
+ }
16781
+ return { kind: "paired", browser, doneError };
16782
+ }
16783
+ }
16784
+
16657
16785
  // src/adapters/cli/pcCommand.ts
16658
16786
  import { readFile as readFile13 } from "fs/promises";
16659
16787
 
16788
+ // src/adapters/cli/pairCommand.ts
16789
+ import { randomUUID as randomUUID7 } from "crypto";
16790
+ var USAGE = "Usage: ainecto pair [--list | --remove <keyId|name>]";
16791
+ var PAIR_RETIRED = "Browser registration is automatic now \u2014 just run `npx -y ainecto@latest` in this PC's terminal.";
16792
+ async function executePair(deps, argv) {
16793
+ const [first, ...rest] = argv;
16794
+ if (first === "--list" && rest.length === 0) {
16795
+ return await listBrowsers(deps);
16796
+ }
16797
+ if (first === "--remove" && rest.length === 1 && rest[0] !== void 0 && rest[0] !== "") {
16798
+ return await removeBrowser(deps, rest[0]);
16799
+ }
16800
+ if (first !== void 0) {
16801
+ throw new CliCommandError("USAGE", USAGE);
16802
+ }
16803
+ deps.io.stdout.write(`${PAIR_RETIRED}
16804
+ `);
16805
+ return 0;
16806
+ }
16807
+ async function pinBrowser(input) {
16808
+ const { key, pcKey, browser } = input;
16809
+ await updatePcKeys(input.keysPath, (latest) => {
16810
+ const stored = latest.accounts[key]?.pcKey;
16811
+ if (stored && stored.d !== pcKey.d) {
16812
+ throw new CliCommandError("PAIR_CONFLICT", "This PC's key changed during browser registration (another registration?). Nothing was saved \u2014 run `npx -y ainecto@latest` again.");
16813
+ }
16814
+ if (latest.accounts[key]?.pendingTurnOff?.removals.some((item) => item.keyId === browser.keyId)) {
16815
+ 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 \`npx -y ainecto@latest\` again.`);
16816
+ }
16817
+ return withBrowser(latest, key, pcKey, { ...browser, pairedAt: input.now.toISOString() });
16818
+ });
16819
+ }
16820
+ async function listBrowsers(deps) {
16821
+ const browsers = (await loadPcKeys(deps.keysPath)).accounts[(await account(deps)).key]?.browsers ?? [];
16822
+ const data = { browsers: browsers.map((item) => ({ keyId: item.keyId, name: item.name, pairedAt: item.pairedAt })) };
16823
+ const human = browsers.length === 0 ? "No browsers are registered with this PC. Run `npx -y ainecto@latest` to register one." : ["Browsers registered with this PC:", ...browsers.map((item) => ` ${item.keyId} ${item.name} (registered ${item.pairedAt})`)].join("\n");
16824
+ deps.io.stdout.write(deps.json ? renderSuccess(data, { json: true }) : `${human}
16825
+ `);
16826
+ return 0;
16827
+ }
16828
+ async function removeBrowser(deps, keyIdOrName) {
16829
+ const { key } = await account(deps);
16830
+ let removed;
16831
+ let target;
16832
+ await updatePcKeys(deps.keysPath, (keys) => {
16833
+ const result = withoutBrowser(keys, key, keyIdOrName);
16834
+ removed = result.removed;
16835
+ if (!removed) {
16836
+ target = pendingRemovalOf(keys.accounts[key], keyIdOrName);
16837
+ return void 0;
16838
+ }
16839
+ target = { removalId: randomUUID7(), keyId: removed.keyId, name: removed.name };
16840
+ return withPendingTurnOff(result.keys, key, { at: deps.now(), groups: [], removal: target });
16841
+ });
16842
+ if (!target) {
16843
+ throw new CliCommandError("PAIR_NOT_FOUND", `No registered browser with key id or name "${keyIdOrName}" \u2014 \`ainecto pair --list\` shows them.`);
16844
+ }
16845
+ const { keyId: finished, removalId } = target;
16846
+ let groups;
16847
+ try {
16848
+ const found = await deps.findPcs();
16849
+ const saved = await updatePcKeys(deps.keysPath, (keys) => {
16850
+ const next = withPendingTurnOff(keys, key, { at: deps.now(), groups: found });
16851
+ return next === keys ? void 0 : next;
16852
+ });
16853
+ groups = saved.accounts[key]?.pendingTurnOff?.groups ?? found;
16854
+ await deps.turnOffPcs(groups);
16855
+ } catch (error) {
16856
+ 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.`);
16857
+ }
16858
+ await updatePcKeys(deps.keysPath, (keys) => {
16859
+ const next = withTurnOffConfirmed(keys, key, { groups, removalId });
16860
+ return next === keys ? void 0 : next;
16861
+ });
16862
+ const lines = [removed ? `Removed "${removed.name}" (${removed.keyId}). It can no longer open terminals on this PC.` : "Finished the earlier removal."];
16863
+ lines.push(groups.length > 0 ? "Turned off the PC connection. Run `ainecto` to turn it back on." : "The PC connection is not running.");
16864
+ deps.io.stdout.write(deps.json ? renderSuccess({ removed: removed ? { keyId: removed.keyId, name: removed.name } : null, turnedOff: groups }, { json: true }) : `${lines.join("\n")}
16865
+ `);
16866
+ return 0;
16867
+ }
16868
+ async function account(deps) {
16869
+ const userId = (await deps.account()).userId;
16870
+ if (!userId) throw accountUnknown();
16871
+ return { key: accountKey(deps.endpoint, userId), userId };
16872
+ }
16873
+ function accountUnknown() {
16874
+ return new CliCommandError("PC_ACCOUNT_UNKNOWN", "Could not read your AiNecto account \u2014 run `ainecto doctor` to see why.");
16875
+ }
16876
+
16660
16877
  // src/adapters/cli/pcStartText.ts
16661
16878
  var DOCTOR_ONLY = /* @__PURE__ */ new Set(["AiNecto job title"]);
16662
16879
  var NOT_CONNECTED = "not connected to AiNecto";
@@ -16688,6 +16905,9 @@ function pcResultText(result) {
16688
16905
  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
16906
  return `This PC is now connected to AiNecto. ${use} It keeps running after you close this window. ${STOP} Log: ${result.log}`;
16690
16907
  }
16908
+ function pcNotApprovedText(hostName, then) {
16909
+ 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}` : ""}.`;
16910
+ }
16691
16911
  function listed(labels) {
16692
16912
  if (labels.length <= 2) return labels.join(" and ");
16693
16913
  return `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
@@ -16727,7 +16947,7 @@ async function executePcStart(deps) {
16727
16947
  let settings = await loadPcSettings(deps.settingsPath, deps.hostName);
16728
16948
  if (!settings.accounts[key]) {
16729
16949
  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.");
16950
+ throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName));
16731
16951
  }
16732
16952
  note("");
16733
16953
  note(`This connects this PC to AiNecto as ${status.account?.displayName ?? "your account"} (${deps.endpoint}).`);
@@ -16745,15 +16965,15 @@ async function executePcStart(deps) {
16745
16965
  const action = pcAction(runningPcs(await listed2(deps)), deps.cliVersion);
16746
16966
  if (action.kind === "already") {
16747
16967
  if (!remoteOffByWeb(await screenLines2(deps, action.pc.session))) {
16748
- return withNotes(deps, later, print2(
16968
+ return await withRegistration(deps, key, userId, withNotes(deps, later, print2(
16749
16969
  deps,
16750
16970
  { connected: true, already: true, ...pcView(deps, action.pc) },
16751
16971
  pcResultText({ kind: "already", folder: action.pc.cwd, version: pcVersionLabel(action.pc), log: deps.agentLog })
16752
- ));
16972
+ )));
16753
16973
  }
16754
16974
  note("The remote terminal was turned off from the web \u2014 reconnecting this PC to turn it back on\u2026");
16755
16975
  await stopPc(deps, action.pc);
16756
- return withNotes(deps, later, await launchPc(deps));
16976
+ return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
16757
16977
  }
16758
16978
  await prepare(deps);
16759
16979
  if (action.kind === "replace") {
@@ -16762,8 +16982,84 @@ async function executePcStart(deps) {
16762
16982
  await stopPc(deps, pc);
16763
16983
  }
16764
16984
  }
16765
- return withNotes(deps, later, await launchPc(deps));
16985
+ return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
16986
+ }
16987
+ async function withRegistration(deps, key, userId, code) {
16988
+ if (code === 0) await registerBrowserOnStart(deps, { key, userId });
16989
+ return code;
16990
+ }
16991
+ async function registerBrowserOnStart(deps, account2) {
16992
+ const register = deps.register;
16993
+ if (!register || !deps.interactive || deps.json || register.insideTermSession) return;
16994
+ const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
16995
+ if (settings.accounts[account2.key]?.remoteTerminal !== true) return;
16996
+ const stored = (await loadPcKeys(deps.keysPath)).accounts[account2.key];
16997
+ const registered = stored?.browsers.length ?? 0;
16998
+ const note = (line) => {
16999
+ deps.io.stderr.write(`${line}
17000
+ `);
17001
+ };
17002
+ const noBrowser = "This PC can't open a browser here (for example over ssh). Run `npx -y ainecto@latest` in a terminal on this PC's own screen to register your browser.";
17003
+ if (register.overSsh) {
17004
+ if (registered === 0) note(noBrowser);
17005
+ return;
17006
+ }
17007
+ if (registered > 0) {
17008
+ const question = `This PC already has ${registered} registered browser${registered === 1 ? "" : "s"}. Register the browser that opens now too? [y/N]: `;
17009
+ if (!yes(await promptLine(deps.io, question), false)) return;
17010
+ }
17011
+ const userId = transcriptUserId(account2.userId);
17012
+ const secret = randomBytes3(NONCE_SEED_BYTES);
17013
+ const interrupt = register.interrupt();
17014
+ let outcome;
17015
+ try {
17016
+ const tag = await registerTag((await registerKeys(secret)).account, userId);
17017
+ const url = `${new URL(deps.endpoint).origin}${REGISTER_PATH}#${registerFragment({ pcId: settings.pcId, tag, secret })}`;
17018
+ try {
17019
+ await register.openBrowser(url);
17020
+ } catch {
17021
+ note(noBrowser);
17022
+ return;
17023
+ }
17024
+ note("");
17025
+ note(`Finish in the browser that just opened (up to ${Math.round(register.waitMs / 6e4)} min \xB7 Ctrl+C to skip)`);
17026
+ const pcKey = stored?.pcKey ?? await generateSigningJwk();
17027
+ outcome = await runPairing({
17028
+ userId,
17029
+ pcId: settings.pcId,
17030
+ pcKey,
17031
+ transport: await register.transport(settings.pcId),
17032
+ secret,
17033
+ pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now: register.now() }),
17034
+ waitMs: register.waitMs,
17035
+ cancel: interrupt.signal
17036
+ });
17037
+ } catch (error) {
17038
+ note(`Browser registration did not finish (${error instanceof Error ? error.message : String(error)}). ${REGISTER_AGAIN}`);
17039
+ return;
17040
+ } finally {
17041
+ interrupt.dispose();
17042
+ secret.fill(0);
17043
+ }
17044
+ if (outcome.kind !== "paired") {
17045
+ const why = outcome.kind === "timeout" ? "timed out" : outcome.kind === "cancelled" ? "skipped" : "the browser could not be verified";
17046
+ note(`Browser registration did not finish (${why}). Nothing was saved. ${REGISTER_AGAIN}`);
17047
+ return;
17048
+ }
17049
+ const { browser, doneError } = outcome;
17050
+ if (doneError !== void 0) {
17051
+ await updatePcKeys(deps.keysPath, (keys) => {
17052
+ const result = withoutBrowser(keys, account2.key, browser.keyId);
17053
+ return result.removed ? result.keys : void 0;
17054
+ });
17055
+ note(`The browser "${browser.name}" did not get the confirmation (${doneError}), so nothing was kept. ${REGISTER_AGAIN}`);
17056
+ return;
17057
+ }
17058
+ await register.notifyPaired({ keyId: browser.keyId, name: browser.name });
17059
+ deps.io.stdout.write(`Registered "${browser.name}" with this PC.
17060
+ `);
16766
17061
  }
17062
+ var REGISTER_AGAIN = "Try again: `npx -y ainecto@latest`.";
16767
17063
  function withNotes(deps, notes, code) {
16768
17064
  for (const line of notes) deps.io.stderr.write(`${line}
16769
17065
  `);
@@ -16871,7 +17167,7 @@ async function executePcStop(deps, argv) {
16871
17167
  return removedKeys ? kept : void 0;
16872
17168
  });
16873
17169
  if (removedKeys) {
16874
- lines.push("Also removed this PC's terminal key and paired browsers for that server \u2014 pair again with `ainecto pair`.");
17170
+ lines.push("Also removed this PC's terminal key and registered browsers for that server \u2014 register them again by running `npx -y ainecto@latest`.");
16875
17171
  }
16876
17172
  }
16877
17173
  return print2(deps, { stopped: running.map((pc) => pc.session), forgot: forget }, lines.join("\n"));
@@ -16887,13 +17183,14 @@ async function executeRemoteSetting(deps, argv) {
16887
17183
  }
16888
17184
  const next = withRemoteTerminal(await loadPcSettings(deps.settingsPath, deps.hostName), accountKey(deps.endpoint, userId), value === "on");
16889
17185
  if (!next) {
16890
- throw new CliCommandError("PC_NOT_APPROVED", "This PC is not connected yet \u2014 run `ainecto` in a terminal once to approve.");
17186
+ throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName));
16891
17187
  }
16892
17188
  await savePcSettings(deps.settingsPath, next);
16893
17189
  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
17190
  const running = deps.termProblem === void 0 ? runningPcs(await listed2(deps)) : [];
17191
+ const key = accountKey(deps.endpoint, userId);
16895
17192
  if (running.length === 0) {
16896
- return print2(deps, { remoteTerminal: value === "on" }, said);
17193
+ return await withRegistration(deps, key, userId, print2(deps, { remoteTerminal: value === "on" }, said));
16897
17194
  }
16898
17195
  if (!deps.json) deps.io.stdout.write(`${said}
16899
17196
  `);
@@ -16901,7 +17198,7 @@ async function executeRemoteSetting(deps, argv) {
16901
17198
  for (const pc of running) {
16902
17199
  await stopPc(deps, pc);
16903
17200
  }
16904
- return await launchPc(deps);
17201
+ return await withRegistration(deps, key, userId, await launchPc(deps));
16905
17202
  }
16906
17203
  async function runningPcGroups(deps) {
16907
17204
  assertQueryable(deps);
@@ -17028,69 +17325,6 @@ function print2(deps, data, human) {
17028
17325
  return 0;
17029
17326
  }
17030
17327
 
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
17328
  // src/core/pc/pcPairRelay.ts
17095
17329
  var PairRelayError = class extends Error {
17096
17330
  constructor(code, message2) {
@@ -17127,7 +17361,7 @@ function createPairRelay(input) {
17127
17361
  let attemptId;
17128
17362
  let finished = false;
17129
17363
  const send = async (msg, signal) => {
17130
- if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The pairing was not opened.");
17364
+ if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The browser registration was not opened.");
17131
17365
  await http.call("pair/send", { attemptId, msg }, signal ? { signal } : void 0);
17132
17366
  };
17133
17367
  return {
@@ -17142,18 +17376,18 @@ function createPairRelay(input) {
17142
17376
  const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
17143
17377
  if (answer.closed === true) {
17144
17378
  finished = true;
17145
- throw new PairRelayError("PAIR_CLOSED", "The pairing ended on AiNecto (the browser cancelled it, or it expired).");
17379
+ throw new PairRelayError("PAIR_CLOSED", "The browser registration ended on AiNecto (the browser cancelled it, or it expired).");
17146
17380
  }
17147
17381
  const offer = offerOf(Array.isArray(answer.msgs) ? answer.msgs : []);
17148
17382
  if (offer === "abort") {
17149
17383
  finished = true;
17150
- throw new PairRelayError("PAIR_CLOSED", "The browser cancelled the pairing.");
17384
+ throw new PairRelayError("PAIR_CLOSED", "The browser cancelled the registration.");
17151
17385
  }
17152
- if (offer) return offer;
17386
+ if (offer) return { ...offer, attemptId };
17153
17387
  }
17154
17388
  },
17155
- async reveal(pcPublicRaw, nP, signal) {
17156
- await send({ type: "reveal", publicKey: b64u2(pcPublicRaw), nP: b64u2(nP) }, signal);
17389
+ async reveal(pcPublicRaw, nP, signal, macP) {
17390
+ await send({ type: "reveal", publicKey: b64u2(pcPublicRaw), nP: b64u2(nP), ...macP ? { macP: b64u2(macP) } : {} }, signal);
17157
17391
  },
17158
17392
  async done(signature, signal) {
17159
17393
  await send({ type: "done", signature: b64u2(signature) }, signal);
@@ -17174,15 +17408,20 @@ function offerOf(msgs) {
17174
17408
  const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
17175
17409
  if (items.some((item2) => item2.type === "abort")) return "abort";
17176
17410
  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.");
17411
+ throw new PairRelayError("PAIR_DUPLICATE", "More than one browser registration request arrived \u2014 this try was ended. Run `npx -y ainecto@latest` again.");
17178
17412
  }
17179
17413
  const [item] = items;
17180
17414
  const publicRaw = fromB64u2(item?.publicKey, PUBLIC_KEY_BYTES);
17181
17415
  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.");
17416
+ const macB = item?.macB === void 0 ? void 0 : fromB64u2(
17417
+ item.macB,
17418
+ 32
17419
+ /* HMAC-SHA256 */
17420
+ );
17421
+ if (item?.type !== "offer" || !publicRaw || !nB || typeof item.keyId !== "string" || typeof item.name !== "string" || item.macB !== void 0 && !macB) {
17422
+ throw new PairRelayError("PAIR_BAD_MESSAGE", "AiNecto relayed a browser registration message this CLI does not understand \u2014 this try was ended.");
17184
17423
  }
17185
- return { keyId: item.keyId, publicRaw, nB, name: item.name };
17424
+ return { keyId: item.keyId, publicRaw, nB, name: item.name, ...macB ? { macB } : {} };
17186
17425
  }
17187
17426
  function b64u2(bytes) {
17188
17427
  return Buffer.from(bytes).toString("base64url");
@@ -17193,185 +17432,10 @@ function fromB64u2(value, length) {
17193
17432
  return bytes.length === length ? bytes : void 0;
17194
17433
  }
17195
17434
 
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();
17264
- }
17265
- if (outcome.kind === "timeout") {
17266
- throw new CliCommandError("PAIR_TIMEOUT", "No pairing finished in time. Nothing was saved \u2014 run `ainecto pair` again.");
17267
- }
17268
- if (outcome.kind === "cancelled") {
17269
- throw new CliCommandError("PAIR_CANCELLED", "Pairing cancelled. Nothing was saved \u2014 run `ainecto pair` again.");
17270
- }
17271
- if (outcome.kind === "code-mismatch") {
17272
- throw new CliCommandError(
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
- );
17276
- }
17277
- const { browser, doneError } = outcome;
17278
- if (doneError !== void 0) {
17279
- 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.`);
17280
- }
17281
- await deps.notifyPaired({ keyId: browser.keyId, name: browser.name });
17282
- const lines = [`Paired "${browser.name}" with this PC. Remove it later with \`ainecto pair --remove ${browser.keyId}\`.`];
17283
- if (settings.accounts[key]?.remoteTerminal !== true) {
17284
- lines.push("Terminals from the web are blocked on this PC \u2014 `ainecto remote on` allows them.");
17285
- }
17286
- deps.io.stdout.write(`${lines.join("\n")}
17287
- `);
17288
- return 0;
17289
- }
17290
- async function pin(deps, key, pcKey, browser) {
17291
- await updatePcKeys(deps.keysPath, (latest) => {
17292
- const stored = latest.accounts[key]?.pcKey;
17293
- if (stored && stored.d !== pcKey.d) {
17294
- throw new CliCommandError("PAIR_CONFLICT", "This PC's key changed while pairing (another `ainecto pair`?). Nothing was saved \u2014 run `ainecto pair` again.");
17295
- }
17296
- if (latest.accounts[key]?.pendingTurnOff?.removals.some((item) => item.keyId === browser.keyId)) {
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.`);
17298
- }
17299
- return withBrowser(latest, key, pcKey, { ...browser, pairedAt: deps.now().toISOString() });
17300
- });
17301
- }
17302
- async function listBrowsers(deps) {
17303
- const browsers = (await loadPcKeys(deps.keysPath)).accounts[(await account(deps)).key]?.browsers ?? [];
17304
- const data = { browsers: browsers.map((item) => ({ keyId: item.keyId, name: item.name, pairedAt: item.pairedAt })) };
17305
- const human = browsers.length === 0 ? "No browsers are paired with this PC. Run `ainecto pair` to pair one." : ["Browsers paired with this PC:", ...browsers.map((item) => ` ${item.keyId} ${item.name} (paired ${item.pairedAt})`)].join("\n");
17306
- deps.io.stdout.write(deps.json ? renderSuccess(data, { json: true }) : `${human}
17307
- `);
17308
- return 0;
17309
- }
17310
- async function removeBrowser(deps, keyIdOrName) {
17311
- const { key } = await account(deps);
17312
- let removed;
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.`);
17326
- }
17327
- const { keyId: finished, removalId } = target;
17328
- let groups;
17329
- try {
17330
- const found = await deps.findPcs();
17331
- const saved = await updatePcKeys(deps.keysPath, (keys) => {
17332
- const next = withPendingTurnOff(keys, key, { at: deps.now(), groups: found });
17333
- return next === keys ? void 0 : next;
17334
- });
17335
- groups = saved.accounts[key]?.pendingTurnOff?.groups ?? found;
17336
- await deps.turnOffPcs(groups);
17337
- } catch (error) {
17338
- 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.`);
17339
- }
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
- }
17350
- async function relayErrors(run) {
17351
- try {
17352
- return await run();
17353
- } catch (error) {
17354
- if (error instanceof PairRelayError) {
17355
- throw new CliCommandError(error.code, `${error.message} Nothing was saved \u2014 run \`ainecto pair\` again.`);
17356
- }
17357
- if (error instanceof PcCallError) {
17358
- throw new CliCommandError("PAIR_RELAY_FAILED", `Could not reach AiNecto to pair (${error.op}: ${error.status ?? "-"} ${error.code ?? ""} ` + `${error.message}`.replace(/\s+/g, " ").trim() + "). Nothing was saved \u2014 run `ainecto pair` again.");
17359
- }
17360
- throw error;
17361
- }
17362
- }
17363
- async function account(deps) {
17364
- const userId = (await deps.account()).userId;
17365
- if (!userId) {
17366
- throw new CliCommandError("PC_ACCOUNT_UNKNOWN", "Could not read your AiNecto account \u2014 run `ainecto doctor` to see why.");
17367
- }
17368
- return { key: accountKey(deps.endpoint, userId), userId };
17369
- }
17370
-
17371
17435
  // src/core/pc/pcNotify.ts
17372
17436
  var NOTIFY_BATCH_MS = 6e4;
17373
17437
  var WHAT = {
17374
- paired: "was paired with this PC",
17438
+ paired: "was registered with this PC",
17375
17439
  session: "opened a terminal connection to this PC",
17376
17440
  shell: "started a new shell on this PC",
17377
17441
  command: "started a command in a new terminal on this PC"
@@ -17718,19 +17782,6 @@ async function pcStatus(status, endpoint) {
17718
17782
  // src/adapters/cli/agentCommand.ts
17719
17783
  import { hostname as hostname3 } from "os";
17720
17784
 
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
17785
  // src/core/agent/child.ts
17735
17786
  import { createInterface as createInterface3 } from "readline";
17736
17787
  var spawnAgent = (command, args, options) => spawnPiped([command, ...args], options);
@@ -18837,9 +18888,8 @@ async function runPcRemote(setup, signal, onAnswer) {
18837
18888
  var AGENT_HELP_LINES = [
18838
18889
  " ainecto in a terminal, with no arguments: check sign-in, ask once, then connect this PC in the background (same as ainecto start)",
18839
18890
  " 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 paired browsers on this PC)",
18841
- " ainecto remote on|off allow or block terminals from AiNecto on the web on this PC",
18842
- " ainecto pair [--list | --remove <keyId|name>] pair a web browser with this PC by typing codes shown on both (once per browser)"
18891
+ " ainecto stop [--forget] disconnect this PC now (--forget also removes your approval and registered browsers on this PC)",
18892
+ " ainecto remote on|off allow or block terminals from AiNecto on the web on this PC"
18843
18893
  ];
18844
18894
  function isPcRunCommand(domain, action) {
18845
18895
  return domain === "pc" && action === "run";
@@ -19059,6 +19109,17 @@ async function runAinectoCli(argv, io) {
19059
19109
  envVars: process.env
19060
19110
  };
19061
19111
  };
19112
+ const insideTermSession = process.env[SESSION_ENV] !== void 0;
19113
+ const pairTransport = async (pcId) => {
19114
+ const paths = termPaths();
19115
+ await ensurePrivateDir(paths.dir);
19116
+ return createPairRelay({ endpoint: resolved.endpoint, tokenProvider: connect2().auth, log: openRemoteLog(paths), pcId, holdMs: PAIR_WAIT_MS });
19117
+ };
19118
+ const notifyPaired = async (browser) => {
19119
+ const paths = termPaths();
19120
+ await ensurePrivateDir(paths.dir);
19121
+ await createPcNotifier({ log: openRemoteLog(paths) }).notify({ kind: "paired", keyId: browser.keyId, browserName: browser.name });
19122
+ };
19062
19123
  const pcDeps = () => ({
19063
19124
  io,
19064
19125
  json: parsed.json,
@@ -19080,7 +19141,21 @@ async function runAinectoCli(argv, io) {
19080
19141
  readyDeadlineMs: pcReadyDeadlineMs(),
19081
19142
  machine: () => collectStatus(collectInput()),
19082
19143
  account: () => readAccount(connect2().client),
19083
- setup: () => runSetup([])
19144
+ setup: () => runSetup([]),
19145
+ register: {
19146
+ insideTermSession,
19147
+ overSsh: process.env.SSH_CONNECTION !== void 0 || process.env.SSH_TTY !== void 0,
19148
+ openBrowser: (url) => launchBrowser(url),
19149
+ transport: pairTransport,
19150
+ notifyPaired,
19151
+ waitMs: PAIR_WAIT_MS,
19152
+ interrupt: () => {
19153
+ const controller = new AbortController();
19154
+ const off = onStopSignals(() => controller.abort());
19155
+ return { signal: controller.signal, dispose: off };
19156
+ },
19157
+ now: () => /* @__PURE__ */ new Date()
19158
+ }
19084
19159
  });
19085
19160
  if (domain === void 0 || domain === "start") {
19086
19161
  if (rest.length > 0 || domain === "start" && action !== void 0) {
@@ -19098,28 +19173,13 @@ async function runAinectoCli(argv, io) {
19098
19173
  return await executePair({
19099
19174
  io,
19100
19175
  json: parsed.json,
19101
- interactive,
19102
- insideTermSession: process.env[SESSION_ENV] !== void 0,
19103
- openTty: openDevTty,
19104
19176
  settingsPath: pcSettingsPath(),
19105
19177
  keysPath: pcKeysPath(),
19106
19178
  hostName: hostname4(),
19107
19179
  endpoint: resolved.endpoint,
19108
19180
  account: () => readAccount(connect2().client),
19109
- // 중계 호출 줄(요청 1 + 응답 1)은 원격 다리와 같은 remote.log 에(op = pair/…).
19110
- transport: async (pcId) => {
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
- },
19120
19181
  findPcs: () => runningPcGroups(pcDeps()),
19121
19182
  turnOffPcs: (groups) => turnOffPcs(pcDeps(), groups),
19122
- waitMs: PAIR_WAIT_MS,
19123
19183
  now: () => /* @__PURE__ */ new Date()
19124
19184
  }, parsed.positionals.slice(1));
19125
19185
  }