@ainecto/mcp 0.15.2 → 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.
@@ -5699,8 +5699,8 @@ function legacyRoleInput(flag, envVars = process.env) {
5699
5699
 
5700
5700
  // src/core/version.ts
5701
5701
  var UNBUNDLED_VERSION = "dev";
5702
- var CLI_VERSION = true ? "0.15.2" : UNBUNDLED_VERSION;
5703
- var CLI_BUILD = true ? "cdf776d" : void 0;
5702
+ var CLI_VERSION = true ? "0.15.3" : UNBUNDLED_VERSION;
5703
+ var CLI_BUILD = true ? "b93ea31" : void 0;
5704
5704
  function cliVersionLabel(version, build, release2) {
5705
5705
  return release2 || build === void 0 ? version : `${version}-dev+${build}`;
5706
5706
  }
@@ -10165,9 +10165,6 @@ function endedFromOutside(exitCode2, signal, platform = process.platform) {
10165
10165
  if (signal !== 0) return true;
10166
10166
  return platform === "win32" && exitCode2 !== 0;
10167
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
- }
10171
10168
  function notifyTool(platform = process.platform) {
10172
10169
  if (platform === "darwin") {
10173
10170
  return {
@@ -14842,19 +14839,16 @@ var subtle = webcrypto.subtle;
14842
14839
  var VERSION = "ainecto-e2e-v1";
14843
14840
  var PAIR_LABEL = "ainecto-pair-v1";
14844
14841
  var PAIR_DONE_LABEL = "ainecto-pair-v1/done";
14845
- var PAIR_CODE_INFO = { a: "ainecto-pair-code-A", b: "ainecto-pair-code-B" };
14846
14842
  var REGISTER_INFO = { browser: "ainecto-register-v1 browser", pc: "ainecto-register-v1 pc", account: "ainecto-register-v1 account" };
14847
14843
  var REGISTER_OFFER_LABEL = "ainecto-register-v1/offer";
14848
14844
  var REGISTER_REVEAL_LABEL = "ainecto-register-v1/reveal";
14849
14845
  var REGISTER_TAG_BYTES = 8;
14850
14846
  var KEY_INFO = { browserToPc: "ainecto-e2e-v1 b2p", pcToBrowser: "ainecto-e2e-v1 p2b", connId: "ainecto-e2e-v1 conn-id" };
14851
- var PAIR_CODE_LIMIT = 4294e6;
14852
14847
  var MAX_MESSAGES_PER_KEY = 2 ** 32;
14853
14848
  var PUBLIC_KEY_BYTES = 65;
14854
14849
  var NONCE_SEED_BYTES = 32;
14855
14850
  var SIGNATURE_BYTES = 64;
14856
14851
  var CONN_ID_BYTES = 16;
14857
- var PAIR_CODE_DIGITS = 6;
14858
14852
  var E2eError = class extends Error {
14859
14853
  constructor(code, message2) {
14860
14854
  super(message2);
@@ -14948,8 +14942,8 @@ function publicJwkFromRaw(raw) {
14948
14942
  return { kty: "EC", crv: "P-256", x: base64url(raw.subarray(1, 33)), y: base64url(raw.subarray(33, 65)) };
14949
14943
  }
14950
14944
  async function generateSigningJwk() {
14951
- const pair2 = await subtle.generateKey(ECDSA, true, ["sign", "verify"]);
14952
- 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));
14953
14947
  if (!jwk) {
14954
14948
  throw new Error("WebCrypto returned an unexpected P-256 JWK.");
14955
14949
  }
@@ -14978,8 +14972,8 @@ async function verifyBytes(publicKey, signature, data) {
14978
14972
  }
14979
14973
  }
14980
14974
  async function generateEphemeral() {
14981
- const pair2 = await subtle.generateKey(ECDH, false, ["deriveBits"]);
14982
- 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)) };
14983
14977
  }
14984
14978
  var USER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
14985
14979
  function transcriptUserId(raw) {
@@ -14996,11 +14990,6 @@ async function browserKeyIdOf(browserPublicRaw) {
14996
14990
  expectLength("browserPub", browserPublicRaw, PUBLIC_KEY_BYTES);
14997
14991
  return Buffer.from((await sha256(browserPublicRaw)).subarray(0, 16)).toString("hex");
14998
14992
  }
14999
- function pairCodeInput(raw) {
15000
- const trimmed = raw.trim();
15001
- if (trimmed === "") return { kind: "empty" };
15002
- return new RegExp(`^[0-9]{${PAIR_CODE_DIGITS}}$`).test(trimmed) ? { kind: "code", code: trimmed } : { kind: "invalid" };
15003
- }
15004
14993
  async function pairCommitment(pcPublicRaw, nP) {
15005
14994
  expectLength("pcPub", pcPublicRaw, PUBLIC_KEY_BYTES);
15006
14995
  expectLength("nP", nP, NONCE_SEED_BYTES);
@@ -15014,30 +15003,6 @@ async function pairTranscript(input) {
15014
15003
  expectLength("nB", input.nB, NONCE_SEED_BYTES);
15015
15004
  return await sha256(enc(PAIR_LABEL, input.userId, input.pcId, input.pcPublicRaw, input.browserPublicRaw, input.nP, input.nB));
15016
15005
  }
15017
- function pairCodeFromBlock(block) {
15018
- expectLength("code block", block, 32);
15019
- const view = new DataView(block.buffer, block.byteOffset, block.byteLength);
15020
- for (let offset = 0; offset < 32; offset += 4) {
15021
- const value = view.getUint32(offset, false);
15022
- if (value < PAIR_CODE_LIMIT) {
15023
- return String(value % 10 ** PAIR_CODE_DIGITS).padStart(PAIR_CODE_DIGITS, "0");
15024
- }
15025
- }
15026
- return void 0;
15027
- }
15028
- async function pairCodes(transcript) {
15029
- expectLength("transcript", transcript, 32);
15030
- const prk = await subtle.importKey("raw", transcript, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
15031
- const code = async (info) => {
15032
- const block = new Uint8Array(await subtle.sign("HMAC", prk, concatBytes(utf8(info), Uint8Array.of(1))));
15033
- const value = pairCodeFromBlock(block);
15034
- if (value === void 0) {
15035
- throw new E2eError("E2E_PAIR_CODE_UNAVAILABLE", "No usable registration code in this attempt \u2014 run `ainecto pair` again.");
15036
- }
15037
- return value;
15038
- };
15039
- return { a: await code(PAIR_CODE_INFO.a), b: await code(PAIR_CODE_INFO.b) };
15040
- }
15041
15006
  function pairDoneInput(transcript) {
15042
15007
  expectLength("transcript", transcript, 32);
15043
15008
  return enc(PAIR_DONE_LABEL, transcript);
@@ -15240,7 +15205,7 @@ async function loadPcKeys(path) {
15240
15205
  try {
15241
15206
  return normalizePcKeys(JSON.parse(raw));
15242
15207
  } catch (error) {
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\`.`);
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\`.`);
15244
15209
  }
15245
15210
  }
15246
15211
  var PC_KEYS_LOCK = { waitMs: 5e3, pollMs: 50 };
@@ -16778,10 +16743,6 @@ async function runPairing(input) {
16778
16743
  const pcPublicRaw = publicRawFromJwk(input.pcKey);
16779
16744
  const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
16780
16745
  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
16746
  const offer = await relayed(() => input.transport.offer(commit, signal));
16786
16747
  if (offer === "timeout") return { kind: "timeout" };
16787
16748
  const publicJwk = publicJwkFromRaw(offer.publicRaw);
@@ -16791,42 +16752,28 @@ async function runPairing(input) {
16791
16752
  }
16792
16753
  const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
16793
16754
  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" };
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" };
16813
16767
  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
16768
  await input.pin(browser);
16823
- return await finish(browser, t);
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));
16824
16771
  }
16825
16772
  async function finish(browser, transcript, before) {
16826
16773
  const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
16827
16774
  let doneError;
16828
16775
  try {
16829
- await before?.();
16776
+ await before();
16830
16777
  await input.transport.done(signature, signal);
16831
16778
  } catch (error) {
16832
16779
  doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
@@ -16840,174 +16787,8 @@ import { readFile as readFile13 } from "fs/promises";
16840
16787
 
16841
16788
  // src/adapters/cli/pairCommand.ts
16842
16789
  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
-
16953
- // src/adapters/cli/pcStartText.ts
16954
- var DOCTOR_ONLY = /* @__PURE__ */ new Set(["AiNecto job title"]);
16955
- var NOT_CONNECTED = "not connected to AiNecto";
16956
- var STOP = "To stop it, run `ainecto stop`.";
16957
- function preflightNotes(checks) {
16958
- const agentLabels = new Set(Object.values(AGENT_CLIENT_LABELS));
16959
- const missing = [];
16960
- const lines = [];
16961
- for (const check of checks) {
16962
- if (check.level === "ok" || DOCTOR_ONLY.has(check.item)) continue;
16963
- if (agentLabels.has(check.item) && check.level === "warn" && check.detail === NOT_CONNECTED) {
16964
- missing.push(check.item);
16965
- continue;
16966
- }
16967
- lines.push(`${check.level === "fail" ? "\u2717" : "!"} ${check.item}: ${check.detail}${check.fix ? ` \u2014 fix: ${check.fix}` : ""}`);
16968
- }
16969
- if (missing.length > 0) {
16970
- lines.unshift(`! To use AiNecto from ${listed(missing)} on this computer, run \`ainecto setup\` \u2014 ${missing.length === 1 ? "its" : "their"} settings here have no AiNecto entry yet (a connector you added in your claude.ai or ChatGPT account is not checked here).`);
16971
- }
16972
- return lines;
16973
- }
16974
- function pcResultText(result) {
16975
- if (result.kind === "connecting") {
16976
- return `Still connecting this PC to AiNecto \u2014 run \`ainecto status\` to see when it is up. Log: ${result.log}`;
16977
- }
16978
- if (result.kind === "already") {
16979
- return `This PC is already connected to AiNecto (folder ${result.folder}, version ${result.version}). ${STOP} Log: ${result.log}`;
16980
- }
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).";
16982
- return `This PC is now connected to AiNecto. ${use} It keeps running after you close this window. ${STOP} Log: ${result.log}`;
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
- }
16987
- function listed(labels) {
16988
- if (labels.length <= 2) return labels.join(" and ");
16989
- return `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
16990
- }
16991
-
16992
- // src/adapters/cli/pairCommand.ts
16993
16790
  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)}`);
17009
- }
17010
- }
16791
+ var PAIR_RETIRED = "Browser registration is automatic now \u2014 just run `npx -y ainecto@latest` in this PC's terminal.";
17011
16792
  async function executePair(deps, argv) {
17012
16793
  const [first, ...rest] = argv;
17013
16794
  if (first === "--list" && rest.length === 0) {
@@ -17019,75 +16800,7 @@ async function executePair(deps, argv) {
17019
16800
  if (first !== void 0) {
17020
16801
  throw new CliCommandError("USAGE", USAGE);
17021
16802
  }
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")}
16803
+ deps.io.stdout.write(`${PAIR_RETIRED}
17091
16804
  `);
17092
16805
  return 0;
17093
16806
  }
@@ -17096,10 +16809,10 @@ async function pinBrowser(input) {
17096
16809
  await updatePcKeys(input.keysPath, (latest) => {
17097
16810
  const stored = latest.accounts[key]?.pcKey;
17098
16811
  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.");
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.");
17100
16813
  }
17101
16814
  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.`);
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.`);
17103
16816
  }
17104
16817
  return withBrowser(latest, key, pcKey, { ...browser, pairedAt: input.now.toISOString() });
17105
16818
  });
@@ -17107,7 +16820,7 @@ async function pinBrowser(input) {
17107
16820
  async function listBrowsers(deps) {
17108
16821
  const browsers = (await loadPcKeys(deps.keysPath)).accounts[(await account(deps)).key]?.browsers ?? [];
17109
16822
  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");
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");
17111
16824
  deps.io.stdout.write(deps.json ? renderSuccess(data, { json: true }) : `${human}
17112
16825
  `);
17113
16826
  return 0;
@@ -17152,29 +16865,6 @@ async function removeBrowser(deps, keyIdOrName) {
17152
16865
  `);
17153
16866
  return 0;
17154
16867
  }
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
16868
  async function account(deps) {
17179
16869
  const userId = (await deps.account()).userId;
17180
16870
  if (!userId) throw accountUnknown();
@@ -17184,6 +16874,45 @@ function accountUnknown() {
17184
16874
  return new CliCommandError("PC_ACCOUNT_UNKNOWN", "Could not read your AiNecto account \u2014 run `ainecto doctor` to see why.");
17185
16875
  }
17186
16876
 
16877
+ // src/adapters/cli/pcStartText.ts
16878
+ var DOCTOR_ONLY = /* @__PURE__ */ new Set(["AiNecto job title"]);
16879
+ var NOT_CONNECTED = "not connected to AiNecto";
16880
+ var STOP = "To stop it, run `ainecto stop`.";
16881
+ function preflightNotes(checks) {
16882
+ const agentLabels = new Set(Object.values(AGENT_CLIENT_LABELS));
16883
+ const missing = [];
16884
+ const lines = [];
16885
+ for (const check of checks) {
16886
+ if (check.level === "ok" || DOCTOR_ONLY.has(check.item)) continue;
16887
+ if (agentLabels.has(check.item) && check.level === "warn" && check.detail === NOT_CONNECTED) {
16888
+ missing.push(check.item);
16889
+ continue;
16890
+ }
16891
+ lines.push(`${check.level === "fail" ? "\u2717" : "!"} ${check.item}: ${check.detail}${check.fix ? ` \u2014 fix: ${check.fix}` : ""}`);
16892
+ }
16893
+ if (missing.length > 0) {
16894
+ lines.unshift(`! To use AiNecto from ${listed(missing)} on this computer, run \`ainecto setup\` \u2014 ${missing.length === 1 ? "its" : "their"} settings here have no AiNecto entry yet (a connector you added in your claude.ai or ChatGPT account is not checked here).`);
16895
+ }
16896
+ return lines;
16897
+ }
16898
+ function pcResultText(result) {
16899
+ if (result.kind === "connecting") {
16900
+ return `Still connecting this PC to AiNecto \u2014 run \`ainecto status\` to see when it is up. Log: ${result.log}`;
16901
+ }
16902
+ if (result.kind === "already") {
16903
+ return `This PC is already connected to AiNecto (folder ${result.folder}, version ${result.version}). ${STOP} Log: ${result.log}`;
16904
+ }
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).";
16906
+ return `This PC is now connected to AiNecto. ${use} It keeps running after you close this window. ${STOP} Log: ${result.log}`;
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
+ }
16911
+ function listed(labels) {
16912
+ if (labels.length <= 2) return labels.join(" and ");
16913
+ return `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
16914
+ }
16915
+
17187
16916
  // src/adapters/cli/pcCommand.ts
17188
16917
  async function executePcStart(deps) {
17189
16918
  assertTerm(deps);
@@ -17256,25 +16985,29 @@ async function executePcStart(deps) {
17256
16985
  return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
17257
16986
  }
17258
16987
  async function withRegistration(deps, key, userId, code) {
17259
- if (code === 0) await registerBrowserIfNone(deps, { key, userId });
16988
+ if (code === 0) await registerBrowserOnStart(deps, { key, userId });
17260
16989
  return code;
17261
16990
  }
17262
- async function registerBrowserIfNone(deps, account2) {
16991
+ async function registerBrowserOnStart(deps, account2) {
17263
16992
  const register = deps.register;
17264
16993
  if (!register || !deps.interactive || deps.json || register.insideTermSession) return;
17265
16994
  const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
17266
16995
  if (settings.accounts[account2.key]?.remoteTerminal !== true) return;
17267
16996
  const stored = (await loadPcKeys(deps.keysPath)).accounts[account2.key];
17268
- if ((stored?.browsers.length ?? 0) > 0) return;
16997
+ const registered = stored?.browsers.length ?? 0;
17269
16998
  const note = (line) => {
17270
16999
  deps.io.stderr.write(`${line}
17271
17000
  `);
17272
17001
  };
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.";
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.";
17274
17003
  if (register.overSsh) {
17275
- note(noBrowser);
17004
+ if (registered === 0) note(noBrowser);
17276
17005
  return;
17277
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
+ }
17278
17011
  const userId = transcriptUserId(account2.userId);
17279
17012
  const secret = randomBytes3(NONCE_SEED_BYTES);
17280
17013
  const interrupt = register.interrupt();
@@ -17296,7 +17029,7 @@ async function registerBrowserIfNone(deps, account2) {
17296
17029
  pcId: settings.pcId,
17297
17030
  pcKey,
17298
17031
  transport: await register.transport(settings.pcId),
17299
- check: { kind: "secret", secret },
17032
+ secret,
17300
17033
  pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now: register.now() }),
17301
17034
  waitMs: register.waitMs,
17302
17035
  cancel: interrupt.signal
@@ -17323,10 +17056,10 @@ async function registerBrowserIfNone(deps, account2) {
17323
17056
  return;
17324
17057
  }
17325
17058
  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}\`.
17059
+ deps.io.stdout.write(`Registered "${browser.name}" with this PC.
17327
17060
  `);
17328
17061
  }
17329
- var REGISTER_AGAIN = "Try again: `npx -y ainecto@latest` \xB7 or register this browser with `npx -y ainecto@latest pair`.";
17062
+ var REGISTER_AGAIN = "Try again: `npx -y ainecto@latest`.";
17330
17063
  function withNotes(deps, notes, code) {
17331
17064
  for (const line of notes) deps.io.stderr.write(`${line}
17332
17065
  `);
@@ -17434,7 +17167,7 @@ async function executePcStop(deps, argv) {
17434
17167
  return removedKeys ? kept : void 0;
17435
17168
  });
17436
17169
  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`.");
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`.");
17438
17171
  }
17439
17172
  }
17440
17173
  return print2(deps, { stopped: running.map((pc) => pc.session), forgot: forget }, lines.join("\n"));
@@ -17592,6 +17325,113 @@ function print2(deps, data, human) {
17592
17325
  return 0;
17593
17326
  }
17594
17327
 
17328
+ // src/core/pc/pcPairRelay.ts
17329
+ var PairRelayError = class extends Error {
17330
+ constructor(code, message2) {
17331
+ super(message2);
17332
+ this.code = code;
17333
+ }
17334
+ code;
17335
+ };
17336
+ function createPairRelay(input) {
17337
+ const http = createPcHttp({
17338
+ endpoint: input.endpoint,
17339
+ path: "term/pc",
17340
+ tokenProvider: input.tokenProvider,
17341
+ timeoutMs: CALL_TIMEOUT_MS,
17342
+ sessionHeader: "X-Remote-Token",
17343
+ fetchImpl: input.fetchImpl,
17344
+ logging: {
17345
+ log: input.log,
17346
+ request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
17347
+ response: ({ callId, op, ms }, outcome) => ({
17348
+ event: "remote_call_response",
17349
+ callId,
17350
+ op,
17351
+ ...outcome.ok ? {
17352
+ ok: true,
17353
+ status: outcome.status,
17354
+ ...Array.isArray(outcome.body.msgs) ? { commands: outcome.body.msgs.length } : {},
17355
+ ...outcome.body.closed === true ? { state: "CLOSED" } : {}
17356
+ } : outcome,
17357
+ ms
17358
+ })
17359
+ }
17360
+ });
17361
+ let attemptId;
17362
+ let finished = false;
17363
+ const send = async (msg, signal) => {
17364
+ if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The browser registration was not opened.");
17365
+ await http.call("pair/send", { attemptId, msg }, signal ? { signal } : void 0);
17366
+ };
17367
+ return {
17368
+ async offer(commit, signal) {
17369
+ const opened = await http.call("pair/open", { pcId: input.pcId }, { signal });
17370
+ if (typeof opened.attemptId !== "string" || opened.attemptId === "") {
17371
+ throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "AiNecto answered pair/open without an attemptId.");
17372
+ }
17373
+ attemptId = opened.attemptId;
17374
+ await send({ type: "commit", commit: b64u2(commit) }, signal);
17375
+ for (; ; ) {
17376
+ const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
17377
+ if (answer.closed === true) {
17378
+ finished = true;
17379
+ throw new PairRelayError("PAIR_CLOSED", "The browser registration ended on AiNecto (the browser cancelled it, or it expired).");
17380
+ }
17381
+ const offer = offerOf(Array.isArray(answer.msgs) ? answer.msgs : []);
17382
+ if (offer === "abort") {
17383
+ finished = true;
17384
+ throw new PairRelayError("PAIR_CLOSED", "The browser cancelled the registration.");
17385
+ }
17386
+ if (offer) return { ...offer, attemptId };
17387
+ }
17388
+ },
17389
+ async reveal(pcPublicRaw, nP, signal, macP) {
17390
+ await send({ type: "reveal", publicKey: b64u2(pcPublicRaw), nP: b64u2(nP), ...macP ? { macP: b64u2(macP) } : {} }, signal);
17391
+ },
17392
+ async done(signature, signal) {
17393
+ await send({ type: "done", signature: b64u2(signature) }, signal);
17394
+ finished = true;
17395
+ },
17396
+ async abort(reason) {
17397
+ if (!attemptId || finished) return;
17398
+ finished = true;
17399
+ try {
17400
+ await send({ type: "abort", reason });
17401
+ } catch {
17402
+ }
17403
+ }
17404
+ };
17405
+ }
17406
+ function offerOf(msgs) {
17407
+ if (msgs.length === 0) return void 0;
17408
+ const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
17409
+ if (items.some((item2) => item2.type === "abort")) return "abort";
17410
+ if (items.length > 1) {
17411
+ throw new PairRelayError("PAIR_DUPLICATE", "More than one browser registration request arrived \u2014 this try was ended. Run `npx -y ainecto@latest` again.");
17412
+ }
17413
+ const [item] = items;
17414
+ const publicRaw = fromB64u2(item?.publicKey, PUBLIC_KEY_BYTES);
17415
+ const nB = fromB64u2(item?.nB, NONCE_SEED_BYTES);
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.");
17423
+ }
17424
+ return { keyId: item.keyId, publicRaw, nB, name: item.name, ...macB ? { macB } : {} };
17425
+ }
17426
+ function b64u2(bytes) {
17427
+ return Buffer.from(bytes).toString("base64url");
17428
+ }
17429
+ function fromB64u2(value, length) {
17430
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) return void 0;
17431
+ const bytes = new Uint8Array(Buffer.from(value, "base64url"));
17432
+ return bytes.length === length ? bytes : void 0;
17433
+ }
17434
+
17595
17435
  // src/core/pc/pcNotify.ts
17596
17436
  var NOTIFY_BATCH_MS = 6e4;
17597
17437
  var WHAT = {
@@ -19049,8 +18889,7 @@ var AGENT_HELP_LINES = [
19049
18889
  " ainecto in a terminal, with no arguments: check sign-in, ask once, then connect this PC in the background (same as ainecto start)",
19050
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)",
19051
18891
  " ainecto stop [--forget] disconnect this PC now (--forget also removes your approval and registered browsers on this PC)",
19052
- " ainecto remote on|off allow or block terminals from AiNecto on the web on this PC",
19053
- " ainecto pair [--list | --remove <keyId|name>] register a web browser with this PC by typing codes shown on both (once per browser)"
18892
+ " ainecto remote on|off allow or block terminals from AiNecto on the web on this PC"
19054
18893
  ];
19055
18894
  function isPcRunCommand(domain, action) {
19056
18895
  return domain === "pc" && action === "run";
@@ -19334,21 +19173,13 @@ async function runAinectoCli(argv, io) {
19334
19173
  return await executePair({
19335
19174
  io,
19336
19175
  json: parsed.json,
19337
- interactive,
19338
- insideTermSession,
19339
- openTty: openDevTty,
19340
19176
  settingsPath: pcSettingsPath(),
19341
19177
  keysPath: pcKeysPath(),
19342
19178
  hostName: hostname4(),
19343
19179
  endpoint: resolved.endpoint,
19344
19180
  account: () => readAccount(connect2().client),
19345
- transport: pairTransport,
19346
- notifyPaired,
19347
19181
  findPcs: () => runningPcGroups(pcDeps()),
19348
19182
  turnOffPcs: (groups) => turnOffPcs(pcDeps(), groups),
19349
- // 연결 승인 전 대화형 — `ainecto`(인자 없음)와 같은 흐름 그대로(KAN-1348). 자동 등록은 빼고 이어서 코드로 등록한다.
19350
- connectPc: () => executePcStart({ ...pcDeps(), register: void 0 }),
19351
- waitMs: PAIR_WAIT_MS,
19352
19183
  now: () => /* @__PURE__ */ new Date()
19353
19184
  }, parsed.positionals.slice(1));
19354
19185
  }