@ainecto/mcp 0.14.0 → 0.15.0

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.
@@ -5686,10 +5686,10 @@ function legacyRoleInput(flag, envVars = process.env) {
5686
5686
 
5687
5687
  // src/core/version.ts
5688
5688
  var UNBUNDLED_VERSION = "dev";
5689
- var CLI_VERSION = true ? "0.14.0" : UNBUNDLED_VERSION;
5690
- var CLI_BUILD = true ? "b96aaec" : void 0;
5691
- function cliVersionLabel(version, build, release) {
5692
- return release || build === void 0 ? version : `${version}-dev+${build}`;
5689
+ var CLI_VERSION = true ? "0.15.0" : UNBUNDLED_VERSION;
5690
+ var CLI_BUILD = true ? "809aaf7" : void 0;
5691
+ function cliVersionLabel(version, build, release2) {
5692
+ return release2 || build === void 0 ? version : `${version}-dev+${build}`;
5693
5693
  }
5694
5694
  var CLI_RELEASE = true;
5695
5695
  var CLI_VERSION_LABEL = cliVersionLabel(CLI_VERSION, CLI_BUILD, CLI_RELEASE);
@@ -7367,14 +7367,14 @@ function managedBlockProblem(key, body) {
7367
7367
  return void 0;
7368
7368
  }
7369
7369
  function hasUnclosedFence(content) {
7370
- let open2;
7370
+ let open3;
7371
7371
  for (const line of content.split("\n")) {
7372
7372
  const fence = fenceOf(line);
7373
7373
  if (!fence) continue;
7374
- if (!open2) open2 = { char: fence.char, length: fence.length };
7375
- else if (fence.char === open2.char && fence.length >= open2.length && fence.info === "") open2 = void 0;
7374
+ if (!open3) open3 = { char: fence.char, length: fence.length };
7375
+ else if (fence.char === open3.char && fence.length >= open3.length && fence.info === "") open3 = void 0;
7376
7376
  }
7377
- return open2 !== void 0;
7377
+ return open3 !== void 0;
7378
7378
  }
7379
7379
  function canonicalManagedBlock(block) {
7380
7380
  return block.trim();
@@ -7434,24 +7434,24 @@ function hit(at, marker) {
7434
7434
  return at >= 0 ? { at, length: marker.length } : void 0;
7435
7435
  }
7436
7436
  function isInsideFencedBlock(content, index) {
7437
- let open2;
7437
+ let open3;
7438
7438
  let offset = 0;
7439
7439
  for (const line of content.split("\n")) {
7440
7440
  const nextOffset = offset + line.length + 1;
7441
7441
  if (index < nextOffset) {
7442
- return open2 !== void 0;
7442
+ return open3 !== void 0;
7443
7443
  }
7444
7444
  const fence = fenceOf(line);
7445
7445
  if (fence) {
7446
- if (!open2) {
7447
- open2 = { char: fence.char, length: fence.length };
7448
- } else if (fence.char === open2.char && fence.length >= open2.length && fence.info === "") {
7449
- open2 = void 0;
7446
+ if (!open3) {
7447
+ open3 = { char: fence.char, length: fence.length };
7448
+ } else if (fence.char === open3.char && fence.length >= open3.length && fence.info === "") {
7449
+ open3 = void 0;
7450
7450
  }
7451
7451
  }
7452
7452
  offset = nextOffset;
7453
7453
  }
7454
- return open2 !== void 0;
7454
+ return open3 !== void 0;
7455
7455
  }
7456
7456
  function fenceOf(line) {
7457
7457
  const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
@@ -8020,15 +8020,19 @@ async function confirmDestructiveCommand(options) {
8020
8020
  });
8021
8021
  }
8022
8022
  }
8023
- async function promptLine(io, message2) {
8023
+ async function promptLine(io, message2, signal) {
8024
+ if (signal?.aborted) return "";
8024
8025
  io.stderr.write(message2);
8025
8026
  const rl = createInterface2({ input: io.stdin, terminal: false });
8027
+ const close = () => rl.close();
8028
+ signal?.addEventListener("abort", close, { once: true });
8026
8029
  try {
8027
8030
  for await (const line of rl) {
8028
8031
  return line;
8029
8032
  }
8030
8033
  return "";
8031
8034
  } finally {
8035
+ signal?.removeEventListener("abort", close);
8032
8036
  rl.close();
8033
8037
  }
8034
8038
  }
@@ -8807,12 +8811,12 @@ function readRecord(content) {
8807
8811
  }
8808
8812
  };
8809
8813
  }
8810
- function serializeRecord(record3) {
8814
+ function serializeRecord(record4) {
8811
8815
  return `${JSON.stringify({
8812
8816
  kind: RECORD_KIND,
8813
8817
  version: RECORD_VERSION,
8814
- files: record3.files,
8815
- createdDirectories: record3.createdDirectories
8818
+ files: record4.files,
8819
+ createdDirectories: record4.createdDirectories
8816
8820
  }, null, 2)}
8817
8821
  `;
8818
8822
  }
@@ -9069,20 +9073,20 @@ function planInit(input) {
9069
9073
  const carriedRecord = previous.state === "valid" ? previous.record : emptyRecord();
9070
9074
  const writes = [];
9071
9075
  const notes = [];
9072
- const record3 = {
9076
+ const record4 = {
9073
9077
  version: carriedRecord.version,
9074
9078
  files: { ...carriedRecord.files },
9075
9079
  createdDirectories: [...carriedRecord.createdDirectories]
9076
9080
  };
9077
9081
  const priorOf = (path, current) => {
9078
- const prior = record3.files[path];
9082
+ const prior = record4.files[path];
9079
9083
  if (prior === void 0) {
9080
9084
  return void 0;
9081
9085
  }
9082
9086
  if (sameOwned(prior.written, current) || sameOwned(prior.original, current)) {
9083
9087
  return prior;
9084
9088
  }
9085
- delete record3.files[path];
9089
+ delete record4.files[path];
9086
9090
  notes.push(`${path}: it changed outside ainecto, so the older backup was dropped and this is the new baseline.`);
9087
9091
  return void 0;
9088
9092
  };
@@ -9091,7 +9095,7 @@ function planInit(input) {
9091
9095
  if (prior === void 0 && original.at !== "absent") {
9092
9096
  notes.push(`${path} already existed; its original was saved and --undo will restore it.`);
9093
9097
  }
9094
- record3.files[path] = {
9098
+ record4.files[path] = {
9095
9099
  scope: "whole",
9096
9100
  createdByUs: prior?.createdByUs ?? existing === void 0,
9097
9101
  original,
@@ -9134,7 +9138,7 @@ function planInit(input) {
9134
9138
  if (prior === void 0 && original.at !== "absent") {
9135
9139
  notes.push(`${target.path}: your existing "${SERVER_NAME}" entry was saved and will be restored by --undo`);
9136
9140
  }
9137
- record3.files[target.path] = {
9141
+ record4.files[target.path] = {
9138
9142
  scope: "entry",
9139
9143
  createdByUs: prior?.createdByUs ?? existing === void 0,
9140
9144
  original,
@@ -9179,7 +9183,7 @@ ${codexContent}`);
9179
9183
  continue;
9180
9184
  }
9181
9185
  const blockNow = existing === void 0 ? void 0 : existingMarkerBlock(existing);
9182
- const carried = record3.files[target.path];
9186
+ const carried = record4.files[target.path];
9183
9187
  let content;
9184
9188
  try {
9185
9189
  content = upsertMarkerBlock(existing, note);
@@ -9201,7 +9205,7 @@ ${codexContent}`);
9201
9205
  if (prior === void 0 && original.at !== "absent") {
9202
9206
  notes.push(`${target.path}: an existing ainecto block was saved and will be restored by --undo`);
9203
9207
  }
9204
- record3.files[target.path] = {
9208
+ record4.files[target.path] = {
9205
9209
  scope: "block",
9206
9210
  createdByUs: prior?.createdByUs ?? existing === void 0,
9207
9211
  original,
@@ -9227,7 +9231,7 @@ ${codexContent}`);
9227
9231
  if (existingConfig !== void 0 && theirConfig === void 0) {
9228
9232
  notes.push(`${HARNESS_CONFIG_PATH} is not a JSON object \u2014 left untouched.`);
9229
9233
  } else {
9230
- const priorConfig = record3.files[HARNESS_CONFIG_PATH];
9234
+ const priorConfig = record4.files[HARNESS_CONFIG_PATH];
9231
9235
  const originalFields = {};
9232
9236
  for (const field of OUR_CONFIG_FIELDS) {
9233
9237
  const presentNow = theirConfig !== void 0 && hasField(theirConfig, field);
@@ -9259,7 +9263,7 @@ ${codexContent}`);
9259
9263
  }
9260
9264
  }
9261
9265
  const mergedConfig = serialize({ ...retained, ...ourFields });
9262
- record3.files[HARNESS_CONFIG_PATH] = {
9266
+ record4.files[HARNESS_CONFIG_PATH] = {
9263
9267
  scope: "fields",
9264
9268
  createdByUs: priorConfig?.createdByUs ?? existingConfig === void 0,
9265
9269
  original: ABSENT,
@@ -9277,7 +9281,7 @@ ${codexContent}`);
9277
9281
  }
9278
9282
  }
9279
9283
  const existingRecord = input.files.get(HARNESS_RECORD_PATH);
9280
- const recordContent = serializeRecord(record3);
9284
+ const recordContent = serializeRecord(record4);
9281
9285
  if (recordContent !== existingRecord) {
9282
9286
  writes.push({
9283
9287
  path: HARNESS_RECORD_PATH,
@@ -9285,7 +9289,7 @@ ${codexContent}`);
9285
9289
  existed: existingRecord !== void 0
9286
9290
  });
9287
9291
  }
9288
- return { writes, deletes: [], notes, record: record3 };
9292
+ return { writes, deletes: [], notes, record: record4 };
9289
9293
  }
9290
9294
  function planUndo(input) {
9291
9295
  const state = input.record ?? readRecord(input.files.get(HARNESS_RECORD_PATH));
@@ -9307,9 +9311,9 @@ function planUndo(input) {
9307
9311
  tail();
9308
9312
  return { writes, deletes, notes };
9309
9313
  }
9310
- const record3 = state.record;
9311
- const remaining = { ...record3.files };
9312
- for (const [path, contract] of Object.entries(record3.files)) {
9314
+ const record4 = state.record;
9315
+ const remaining = { ...record4.files };
9316
+ for (const [path, contract] of Object.entries(record4.files)) {
9313
9317
  const outcome = undoOne(path, contract, input.files.get(path));
9314
9318
  if (outcome.kind !== "unresolved" && outcome.kind !== "keep" && outcome.note !== void 0) {
9315
9319
  notes.push(outcome.note);
@@ -9329,7 +9333,7 @@ function planUndo(input) {
9329
9333
  tail();
9330
9334
  if (input.files.get(HARNESS_RECORD_PATH) !== void 0) {
9331
9335
  if (Object.keys(remaining).length > 0) {
9332
- const reduced = { ...record3, files: remaining };
9336
+ const reduced = { ...record4, files: remaining };
9333
9337
  writes.push({ path: HARNESS_RECORD_PATH, content: serializeRecord(reduced), existed: true });
9334
9338
  notes.push(
9335
9339
  `${HARNESS_RECORD_PATH}: kept, with the finished items removed \u2014 it still holds the backups --undo needs. Run --undo again once the items above are resolved.`
@@ -9338,7 +9342,7 @@ function planUndo(input) {
9338
9342
  deletes.push(HARNESS_RECORD_PATH);
9339
9343
  }
9340
9344
  }
9341
- const removableDirectories = parentsOf(deletes).filter((directory) => record3.createdDirectories.includes(directory));
9345
+ const removableDirectories = parentsOf(deletes).filter((directory) => record4.createdDirectories.includes(directory));
9342
9346
  return { writes, deletes, notes, removableDirectories };
9343
9347
  }
9344
9348
  function unexplainedMarkers(existing, contract) {
@@ -9820,9 +9824,9 @@ Already applied before this failure: ${applied.join(", ") || "(nothing)"}`
9820
9824
  }
9821
9825
  }
9822
9826
  function orderedWrites(writes, recordFirst) {
9823
- const record3 = writes.filter((write) => write.path === HARNESS_RECORD_PATH);
9827
+ const record4 = writes.filter((write) => write.path === HARNESS_RECORD_PATH);
9824
9828
  const rest = writes.filter((write) => write.path !== HARNESS_RECORD_PATH);
9825
- return recordFirst ? [...record3, ...rest] : [...rest, ...record3];
9829
+ return recordFirst ? [...record4, ...rest] : [...rest, ...record4];
9826
9830
  }
9827
9831
  async function assertUnchangedSinceSnapshot(root, relativePath, snapshot) {
9828
9832
  if (!snapshot.has(relativePath)) {
@@ -9918,55 +9922,9 @@ function isRecord13(value) {
9918
9922
  return typeof value === "object" && value !== null && !Array.isArray(value);
9919
9923
  }
9920
9924
 
9921
- // src/core/setup/accountSummary.ts
9922
- async function readAccount(client) {
9923
- const summary2 = {};
9924
- try {
9925
- await client.initialize();
9926
- const self = unwrapMcpToolPayload(await client.toolsCall("identity_get_self", {}));
9927
- if (typeof self?.userId === "string") summary2.userId = self.userId;
9928
- if (typeof self?.displayName === "string") summary2.displayName = self.displayName;
9929
- if ("jobProfile" in (self ?? {})) {
9930
- const profile = self.jobProfile;
9931
- summary2.jobTitle = profile && typeof profile.title === "string" ? profile.title : null;
9932
- }
9933
- summary2.projectCount = extractProjects(unwrapMcpToolPayload(await client.toolsCall("list_projects", {}))).length;
9934
- } catch (error) {
9935
- summary2.problem = classify(error);
9936
- }
9937
- return summary2;
9938
- }
9939
- function classify(error) {
9940
- const message2 = error instanceof Error ? error.message : String(error);
9941
- if (error instanceof McpRpcError && error.code === "MCP_HTTP_ERROR") {
9942
- const status = error.details?.status;
9943
- if (status === 401) return { kind: "unauthorized", message: message2 };
9944
- if (status === 403) return { kind: "forbidden", message: message2 };
9945
- return { kind: "other", message: message2 };
9946
- }
9947
- if (error instanceof McpRpcError) {
9948
- return { kind: "other", message: message2 };
9949
- }
9950
- return { kind: "network", message: message2 };
9951
- }
9952
-
9953
- // src/core/setup/agentConnections.ts
9954
- import { chmod as chmod4, mkdir as mkdir5, readFile as readFile6, rename as rename5, stat as stat5, writeFile as writeFile4 } from "fs/promises";
9955
- import { dirname as dirname6, join as join4 } from "path";
9956
-
9957
- // src/core/agent/limits.ts
9958
- var AGENT_CALL_TIMEOUT_MS = 1e4;
9959
- var AGENT_RETRY_MIN_MS = 500;
9960
- var AGENT_RETRY_MAX_MS = 1e4;
9961
- var AGENT_TURN_TIMEOUT_MS = 15 * 6e4;
9962
- var AGENT_STOP_WAIT_MS = 5e3;
9963
- function nextRetryDelay(previousMs) {
9964
- if (previousMs === void 0) return AGENT_RETRY_MIN_MS;
9965
- return Math.min(previousMs * 2, AGENT_RETRY_MAX_MS);
9966
- }
9967
-
9968
9925
  // src/core/os/launch.ts
9969
9926
  import {
9927
+ execFile,
9970
9928
  spawn as spawn2
9971
9929
  } from "child_process";
9972
9930
  import { statSync } from "fs";
@@ -10156,6 +10114,109 @@ function stuckProcessHint(pid, platform = process.platform) {
10156
10114
  function loginShell(env) {
10157
10115
  return env.SHELL || userInfo().shell || "/bin/sh";
10158
10116
  }
10117
+ function processAlive(pid) {
10118
+ return signalZero(pid);
10119
+ }
10120
+ function processGroupAlive(pgid) {
10121
+ return signalZero(-pgid);
10122
+ }
10123
+ function signalZero(target) {
10124
+ try {
10125
+ process.kill(target, 0);
10126
+ return true;
10127
+ } catch (error) {
10128
+ return isNodeError(error, "EPERM");
10129
+ }
10130
+ }
10131
+ async function processGroupOf(pid, platform = process.platform) {
10132
+ if (platform !== "darwin" && platform !== "linux") return void 0;
10133
+ return await new Promise((resolve4) => {
10134
+ execFile("ps", ["-o", "pgid=", "-p", String(pid)], { timeout: 5e3 }, (error, stdout) => {
10135
+ const pgid = Number.parseInt(String(stdout).trim(), 10);
10136
+ resolve4(error || !Number.isSafeInteger(pgid) || pgid <= 0 ? void 0 : pgid);
10137
+ });
10138
+ });
10139
+ }
10140
+ function processGroupUnavailableHint(platform = process.platform) {
10141
+ return platform === "win32" ? " This check is not available on Windows yet \u2014 the removed browser cannot open new terminals, and a terminal it already had open ends when the PC connection restarts (`ainecto remote on`)." : "";
10142
+ }
10143
+ function runQuiet(file, args) {
10144
+ return new Promise((resolve4, reject) => {
10145
+ execFile(file, [...args], { windowsHide: true }, (error) => error ? reject(error) : resolve4());
10146
+ });
10147
+ }
10148
+ function notifyTool(platform = process.platform) {
10149
+ if (platform === "darwin") {
10150
+ return {
10151
+ name: "osascript",
10152
+ file: "osascript",
10153
+ args: (title, body) => [
10154
+ "-e",
10155
+ "on run argv",
10156
+ "-e",
10157
+ "display notification (item 2 of argv) with title (item 1 of argv)",
10158
+ "-e",
10159
+ "end run",
10160
+ title,
10161
+ body
10162
+ ]
10163
+ };
10164
+ }
10165
+ if (platform === "linux") {
10166
+ return { name: "notify-send", file: "notify-send", args: (title, body) => ["--", title, body] };
10167
+ }
10168
+ return void 0;
10169
+ }
10170
+ 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;
10172
+ }
10173
+
10174
+ // src/core/setup/accountSummary.ts
10175
+ async function readAccount(client) {
10176
+ const summary2 = {};
10177
+ try {
10178
+ await client.initialize();
10179
+ const self = unwrapMcpToolPayload(await client.toolsCall("identity_get_self", {}));
10180
+ if (typeof self?.userId === "string") summary2.userId = self.userId;
10181
+ if (typeof self?.displayName === "string") summary2.displayName = self.displayName;
10182
+ if ("jobProfile" in (self ?? {})) {
10183
+ const profile = self.jobProfile;
10184
+ summary2.jobTitle = profile && typeof profile.title === "string" ? profile.title : null;
10185
+ }
10186
+ summary2.projectCount = extractProjects(unwrapMcpToolPayload(await client.toolsCall("list_projects", {}))).length;
10187
+ } catch (error) {
10188
+ summary2.problem = classify(error);
10189
+ }
10190
+ return summary2;
10191
+ }
10192
+ function classify(error) {
10193
+ const message2 = error instanceof Error ? error.message : String(error);
10194
+ if (error instanceof McpRpcError && error.code === "MCP_HTTP_ERROR") {
10195
+ const status = error.details?.status;
10196
+ if (status === 401) return { kind: "unauthorized", message: message2 };
10197
+ if (status === 403) return { kind: "forbidden", message: message2 };
10198
+ return { kind: "other", message: message2 };
10199
+ }
10200
+ if (error instanceof McpRpcError) {
10201
+ return { kind: "other", message: message2 };
10202
+ }
10203
+ return { kind: "network", message: message2 };
10204
+ }
10205
+
10206
+ // src/core/setup/agentConnections.ts
10207
+ import { chmod as chmod4, mkdir as mkdir5, readFile as readFile6, rename as rename5, stat as stat5, writeFile as writeFile4 } from "fs/promises";
10208
+ import { dirname as dirname6, join as join4 } from "path";
10209
+
10210
+ // src/core/agent/limits.ts
10211
+ var AGENT_CALL_TIMEOUT_MS = 1e4;
10212
+ var AGENT_RETRY_MIN_MS = 500;
10213
+ var AGENT_RETRY_MAX_MS = 1e4;
10214
+ var AGENT_TURN_TIMEOUT_MS = 15 * 6e4;
10215
+ var AGENT_STOP_WAIT_MS = 5e3;
10216
+ function nextRetryDelay(previousMs) {
10217
+ if (previousMs === void 0) return AGENT_RETRY_MIN_MS;
10218
+ return Math.min(previousMs * 2, AGENT_RETRY_MAX_MS);
10219
+ }
10159
10220
 
10160
10221
  // src/core/setup/commandRunner.ts
10161
10222
  var COMMAND_TIMEOUT_MS = 9e4;
@@ -10524,7 +10585,7 @@ async function executeSetupCommand(options) {
10524
10585
  options.io.stderr.write("Signed in.\n");
10525
10586
  signedIn = true;
10526
10587
  }
10527
- const account = signedIn ? await readAccount(options.client) : void 0;
10588
+ const account2 = signedIn ? await readAccount(options.client) : void 0;
10528
10589
  const agents = [];
10529
10590
  const remote = [];
10530
10591
  for (const state of await inspectAgents(context)) {
@@ -10535,33 +10596,33 @@ async function executeSetupCommand(options) {
10535
10596
  remote.push(state.client);
10536
10597
  }
10537
10598
  }
10538
- const failed = agents.some((agent) => agent.status === "failed") || account?.problem !== void 0;
10599
+ const failed = agents.some((agent) => agent.status === "failed") || account2?.problem !== void 0;
10539
10600
  options.io.stdout.write(renderSuccess({
10540
10601
  action: args.dryRun ? "setup (dry-run)" : "setup",
10541
10602
  setup: failed ? "partial" : "complete",
10542
10603
  endpoint: options.endpoint,
10543
- account: accountView(account, signedIn, options.endpoint),
10604
+ account: accountView(account2, signedIn, options.endpoint),
10544
10605
  agents,
10545
10606
  commands,
10546
- next: nextSteps(account, agents, remote, options.endpoint)
10607
+ next: nextSteps(account2, agents, remote, options.endpoint)
10547
10608
  }, { json: options.json }));
10548
10609
  return failed ? 1 : 0;
10549
10610
  }
10550
- function accountView(account, signedIn, endpoint) {
10611
+ function accountView(account2, signedIn, endpoint) {
10551
10612
  if (!signedIn) {
10552
10613
  return { signedIn: false, note: "sign-in required \u2014 `ainecto setup` (without --dry-run) opens the browser once" };
10553
10614
  }
10554
10615
  const view = { signedIn: true };
10555
- if (account?.userId) view.userId = account.userId;
10556
- if (account?.displayName) view.name = account.displayName;
10557
- if (account?.jobTitle !== void 0) {
10558
- view.jobTitle = account.jobTitle ?? `not set \u2014 set it at ${profileSettingsUrl(endpoint)}`;
10616
+ if (account2?.userId) view.userId = account2.userId;
10617
+ if (account2?.displayName) view.name = account2.displayName;
10618
+ if (account2?.jobTitle !== void 0) {
10619
+ view.jobTitle = account2.jobTitle ?? `not set \u2014 set it at ${profileSettingsUrl(endpoint)}`;
10559
10620
  }
10560
- if (account?.projectCount !== void 0) view.projects = account.projectCount;
10561
- if (account?.problem) view.problem = `${account.problem.kind}: ${account.problem.message}`;
10621
+ if (account2?.projectCount !== void 0) view.projects = account2.projectCount;
10622
+ if (account2?.problem) view.problem = `${account2.problem.kind}: ${account2.problem.message}`;
10562
10623
  return view;
10563
10624
  }
10564
- function nextSteps(account, agents, remote, endpoint) {
10625
+ function nextSteps(account2, agents, remote, endpoint) {
10565
10626
  const next = [];
10566
10627
  if (agents.some((agent) => agent.status === "connected" || agent.status === "updated")) {
10567
10628
  next.push("Start a new agent session to load the AiNecto tools. Every session sees the same tools; your AiNecto permissions decide what they may change.");
@@ -10569,10 +10630,12 @@ function nextSteps(account, agents, remote, endpoint) {
10569
10630
  if (remote.length > 0) {
10570
10631
  next.push(`Each agent signs in to AiNecto by itself the first time it connects: ${remote.map((client) => REMOTE_SIGN_IN[client]).join("; ")}.`);
10571
10632
  }
10572
- if (account?.jobTitle === null) {
10633
+ if (account2?.jobTitle === null) {
10573
10634
  next.push(`Set your AiNecto role (your job) at ${profileSettingsUrl(endpoint)} \u2014 AI uses it to pitch explanations; it does not change permissions.`);
10574
10635
  }
10575
10636
  next.push("To add AiNecto's working rules to a repository, run `ainecto init` from its root.");
10637
+ const notifyHint = notificationHint();
10638
+ if (notifyHint) next.push(notifyHint);
10576
10639
  next.push("`ainecto doctor` shows anything still missing.");
10577
10640
  return next;
10578
10641
  }
@@ -10858,9 +10921,12 @@ async function executeDoctorCommand(options) {
10858
10921
  const checks = doctorChecks(status);
10859
10922
  const failed = checks.filter((check) => check.level === "fail").length;
10860
10923
  const warned = checks.filter((check) => check.level === "warn").length;
10924
+ const notifyHint = notificationHint();
10861
10925
  options.io.stdout.write(renderSuccess({
10862
10926
  summary: failed > 0 ? `${failed} problem(s) to fix` : warned > 0 ? `working \u2014 ${warned} suggestion(s)` : "all good",
10863
- checks
10927
+ checks,
10928
+ // macOS 첫 알림 허용 안내 한 줄(설계 terminal-e2e §4-6) — 판정(ok/warn/fail)에는 넣지 않는다.
10929
+ ...notifyHint ? { note: notifyHint } : {}
10864
10930
  }, { json: options.json }));
10865
10931
  return failed > 0 ? 1 : 0;
10866
10932
  }
@@ -11014,8 +11080,8 @@ var DaemonLog = class {
11014
11080
  enableRotation() {
11015
11081
  this.rotating = true;
11016
11082
  }
11017
- write(record3) {
11018
- const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record3 })}
11083
+ write(record4) {
11084
+ const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record4 })}
11019
11085
  `;
11020
11086
  try {
11021
11087
  if (this.rotating) {
@@ -11202,28 +11268,28 @@ function parseClientMessage(line) {
11202
11268
  } catch {
11203
11269
  throw new TermProtocolError("Not a JSON line.");
11204
11270
  }
11205
- const record3 = asRecord(value);
11206
- const op = stringField(record3, "op");
11271
+ const record4 = asRecord(value);
11272
+ const op = stringField(record4, "op");
11207
11273
  if (op === "in") {
11208
- return { op, d: stringField(record3, "d") };
11274
+ return { op, d: stringField(record4, "d") };
11209
11275
  }
11210
11276
  if (op === "resize") {
11211
- return { op, cols: sizeField(record3, "cols"), rows: sizeField(record3, "rows") };
11277
+ return { op, cols: sizeField(record4, "cols"), rows: sizeField(record4, "rows") };
11212
11278
  }
11213
- const id = stringField(record3, "id");
11279
+ const id = stringField(record4, "id");
11214
11280
  switch (op) {
11215
11281
  case "new":
11216
11282
  return {
11217
11283
  id,
11218
11284
  op,
11219
- name: stringField(record3, "name"),
11220
- cwd: stringField(record3, "cwd"),
11221
- command: record3.command === null ? null : stringArrayField(record3, "command"),
11222
- env: stringMapField(record3, "env"),
11223
- cols: optionalSize(record3, "cols"),
11224
- rows: optionalSize(record3, "rows"),
11225
- ...record3.project === void 0 ? {} : { project: projectField(record3, "project") },
11226
- ...record3.input === void 0 ? {} : { input: noInputField(record3, "input") }
11285
+ name: stringField(record4, "name"),
11286
+ cwd: stringField(record4, "cwd"),
11287
+ command: record4.command === null ? null : stringArrayField(record4, "command"),
11288
+ env: stringMapField(record4, "env"),
11289
+ cols: optionalSize(record4, "cols"),
11290
+ rows: optionalSize(record4, "rows"),
11291
+ ...record4.project === void 0 ? {} : { project: projectField(record4, "project") },
11292
+ ...record4.input === void 0 ? {} : { input: noInputField(record4, "input") }
11227
11293
  };
11228
11294
  case "ls":
11229
11295
  case "kill-server":
@@ -11231,39 +11297,41 @@ function parseClientMessage(line) {
11231
11297
  case "watch-sessions":
11232
11298
  return { id, op };
11233
11299
  case "label": {
11234
- const label = stringField(record3, "label");
11300
+ const label = stringField(record4, "label");
11235
11301
  if (label.length === 0) {
11236
11302
  throw new TermProtocolError(`"label" must not be empty.`);
11237
11303
  }
11238
- return { id, op, name: stringField(record3, "name"), label };
11304
+ return { id, op, name: stringField(record4, "name"), label, ...optionalInstance(record4) };
11239
11305
  }
11240
11306
  case "send":
11241
- return { id, op, name: stringField(record3, "name"), text: stringField(record3, "text"), paste: record3.paste === true };
11307
+ return { id, op, name: stringField(record4, "name"), text: stringField(record4, "text"), paste: record4.paste === true, ...optionalInstance(record4) };
11242
11308
  case "key":
11243
- return { id, op, name: stringField(record3, "name"), key: stringField(record3, "key") };
11309
+ return { id, op, name: stringField(record4, "name"), key: stringField(record4, "key"), ...optionalInstance(record4) };
11244
11310
  case "read":
11245
- return { id, op, name: stringField(record3, "name"), scrollback: record3.scrollback === true, lines: optionalSize(record3, "lines") };
11311
+ return { id, op, name: stringField(record4, "name"), scrollback: record4.scrollback === true, lines: optionalSize(record4, "lines") };
11246
11312
  case "kill":
11313
+ return { id, op, name: stringField(record4, "name"), ...optionalInstance(record4) };
11247
11314
  case "watch":
11248
- return { id, op, name: stringField(record3, "name") };
11315
+ return { id, op, name: stringField(record4, "name") };
11249
11316
  case "restore":
11250
- return { id, op, env: stringMapField(record3, "env") };
11317
+ return { id, op, env: stringMapField(record4, "env") };
11251
11318
  case "hello":
11252
- return { id, op, nonce: stringField(record3, "nonce") };
11319
+ return { id, op, nonce: stringField(record4, "nonce") };
11253
11320
  case "attach":
11321
+ return { id, op, name: stringField(record4, "name"), cols: sizeField(record4, "cols"), rows: sizeField(record4, "rows") };
11254
11322
  case "set-size":
11255
- return { id, op, name: stringField(record3, "name"), cols: sizeField(record3, "cols"), rows: sizeField(record3, "rows") };
11323
+ return { id, op, name: stringField(record4, "name"), cols: sizeField(record4, "cols"), rows: sizeField(record4, "rows"), ...optionalInstance(record4) };
11256
11324
  default:
11257
11325
  throw new TermProtocolError(`Unknown op "${op}".`);
11258
11326
  }
11259
11327
  }
11260
11328
  function parseDaemonMessage(line) {
11261
- const record3 = asRecord(JSON.parse(line));
11262
- if (typeof record3.event === "string") {
11263
- switch (record3.event) {
11329
+ const record4 = asRecord(JSON.parse(line));
11330
+ if (typeof record4.event === "string") {
11331
+ switch (record4.event) {
11264
11332
  case "screen":
11265
11333
  case "out":
11266
- return { event: record3.event, d: stringField(record3, "d") };
11334
+ return { event: record4.event, d: stringField(record4, "d") };
11267
11335
  case "changed":
11268
11336
  return { event: "changed" };
11269
11337
  case "sessions":
@@ -11271,19 +11339,19 @@ function parseDaemonMessage(line) {
11271
11339
  case "exit":
11272
11340
  return {
11273
11341
  event: "exit",
11274
- exitCode: typeof record3.exitCode === "number" ? record3.exitCode : 0,
11275
- signal: typeof record3.signal === "number" ? record3.signal : 0,
11276
- reset: stringField(record3, "reset")
11342
+ exitCode: typeof record4.exitCode === "number" ? record4.exitCode : 0,
11343
+ signal: typeof record4.signal === "number" ? record4.signal : 0,
11344
+ reset: stringField(record4, "reset")
11277
11345
  };
11278
11346
  default:
11279
- throw new TermProtocolError(`Unknown event "${record3.event}".`);
11347
+ throw new TermProtocolError(`Unknown event "${record4.event}".`);
11280
11348
  }
11281
11349
  }
11282
- const id = stringField(record3, "id");
11283
- if (record3.ok === true) {
11284
- return { id, ok: true, data: record3.data };
11350
+ const id = stringField(record4, "id");
11351
+ if (record4.ok === true) {
11352
+ return { id, ok: true, data: record4.data };
11285
11353
  }
11286
- const error = asRecord(record3.error);
11354
+ const error = asRecord(record4.error);
11287
11355
  return { id, ok: false, error: { code: stringField(error, "code"), message: stringField(error, "message") } };
11288
11356
  }
11289
11357
  function listedSessions(data) {
@@ -11314,6 +11382,9 @@ function readModes(data) {
11314
11382
  const bracketedPaste = "bracketedPaste" in modes ? modes.bracketedPaste : void 0;
11315
11383
  return typeof altScreen === "boolean" && typeof appCursor === "boolean" && typeof bracketedPaste === "boolean" ? { altScreen, appCursor, bracketedPaste } : void 0;
11316
11384
  }
11385
+ function sessionInstance(data) {
11386
+ return data && typeof data === "object" && "instance" in data && typeof data.instance === "string" && data.instance !== "" ? data.instance : void 0;
11387
+ }
11317
11388
  function readLines(data) {
11318
11389
  if (data && typeof data === "object" && "lines" in data && Array.isArray(data.lines)) {
11319
11390
  return data.lines.filter((line) => typeof line === "string");
@@ -11326,22 +11397,22 @@ function asRecord(value) {
11326
11397
  }
11327
11398
  return value;
11328
11399
  }
11329
- function stringField(record3, key) {
11330
- const value = record3[key];
11400
+ function stringField(record4, key) {
11401
+ const value = record4[key];
11331
11402
  if (typeof value !== "string") {
11332
11403
  throw new TermProtocolError(`"${key}" must be a string.`);
11333
11404
  }
11334
11405
  return value;
11335
11406
  }
11336
- function stringArrayField(record3, key) {
11337
- const value = record3[key];
11407
+ function stringArrayField(record4, key) {
11408
+ const value = record4[key];
11338
11409
  if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string")) {
11339
11410
  throw new TermProtocolError(`"${key}" must be a non-empty string array.`);
11340
11411
  }
11341
11412
  return value;
11342
11413
  }
11343
- function stringMapField(record3, key) {
11344
- const value = asRecord(record3[key]);
11414
+ function stringMapField(record4, key) {
11415
+ const value = asRecord(record4[key]);
11345
11416
  const output = {};
11346
11417
  for (const [name, item] of Object.entries(value)) {
11347
11418
  if (typeof item === "string") {
@@ -11350,28 +11421,36 @@ function stringMapField(record3, key) {
11350
11421
  }
11351
11422
  return output;
11352
11423
  }
11353
- function sizeField(record3, key) {
11354
- const value = record3[key];
11424
+ function sizeField(record4, key) {
11425
+ const value = record4[key];
11355
11426
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
11356
11427
  throw new TermProtocolError(`"${key}" must be a positive integer.`);
11357
11428
  }
11358
11429
  return value;
11359
11430
  }
11360
- function projectField(record3, key) {
11361
- const value = stringField(record3, key);
11431
+ function projectField(record4, key) {
11432
+ const value = stringField(record4, key);
11362
11433
  if (!isUuid(value)) {
11363
11434
  throw new TermProtocolError(`"${key}" must be a lowercase UUID.`);
11364
11435
  }
11365
11436
  return value;
11366
11437
  }
11367
- function noInputField(record3, key) {
11368
- if (record3[key] !== "none") {
11438
+ function noInputField(record4, key) {
11439
+ if (record4[key] !== "none") {
11369
11440
  throw new TermProtocolError(`"${key}" must be "none" when present.`);
11370
11441
  }
11371
11442
  return "none";
11372
11443
  }
11373
- function optionalSize(record3, key) {
11374
- return record3[key] === void 0 ? void 0 : sizeField(record3, key);
11444
+ function optionalInstance(record4) {
11445
+ if (record4.instance === void 0) return {};
11446
+ const instance = stringField(record4, "instance");
11447
+ if (instance === "") {
11448
+ throw new TermProtocolError(`"instance" must not be empty.`);
11449
+ }
11450
+ return { instance };
11451
+ }
11452
+ function optionalSize(record4, key) {
11453
+ return record4[key] === void 0 ? void 0 : sizeField(record4, key);
11375
11454
  }
11376
11455
 
11377
11456
  // src/core/term/client.ts
@@ -11503,6 +11582,7 @@ async function openTermClient(paths, options) {
11503
11582
  new DaemonLog(paths.log, paths.previousLog).write({ event: "ipc_impostor", pid: process.pid, message: error.message });
11504
11583
  }
11505
11584
  if (!options.start) {
11585
+ if (options.resetFails && isNodeError(error, "ECONNRESET")) throw error;
11506
11586
  return void 0;
11507
11587
  }
11508
11588
  }
@@ -11666,6 +11746,7 @@ function assertSessionName(name) {
11666
11746
  // src/core/term/session.ts
11667
11747
  var import_addon_serialize = __toESM(require_addon_serialize(), 1);
11668
11748
  var import_headless = __toESM(require_xterm_headless(), 1);
11749
+ import { randomUUID as randomUUID2 } from "crypto";
11669
11750
 
11670
11751
  // src/core/term/keys.ts
11671
11752
  var PLAIN_KEYS = {
@@ -12177,6 +12258,11 @@ var TermSession = class _TermSession {
12177
12258
  label;
12178
12259
  /** 마지막 출력 시각(ISO) — 원격 웹 목록의 «마지막 활동». */
12179
12260
  lastOutputAt;
12261
+ /**
12262
+ * 인스턴스 id — 데몬이 세션을 만들 때마다 새 무작위 값(설계 terminal-e2e §13-1). 이름이 같아도 다시 만든 세션은 다른 값이라,
12263
+ * 원격 명령은 이 값이 맞을 때만 이 세션에 적용된다(daemon.ts 의 이름 찾기 한 곳). 화면(read)도 이 객체에서 같이 낸다.
12264
+ */
12265
+ instance = randomUUID2();
12180
12266
  static async start(spec, onExit) {
12181
12267
  const ptyModule = await loadNodePty();
12182
12268
  const plan = planLaunch(spec.command ?? defaultShellCommand(spec.env), spec.env, void 0, void 0, spec.input ?? "terminal");
@@ -12211,6 +12297,7 @@ var TermSession = class _TermSession {
12211
12297
  cols: this.pty.cols,
12212
12298
  rows: this.pty.rows,
12213
12299
  clients: this.attached.size,
12300
+ instance: this.instance,
12214
12301
  ...this.label !== void 0 ? { label: this.label } : {},
12215
12302
  ...this.spec.project !== void 0 ? { project: this.spec.project } : {},
12216
12303
  ...this.lastOutputAt !== void 0 ? { lastOutputAt: this.lastOutputAt } : {}
@@ -12619,24 +12706,28 @@ var TermDaemon = class {
12619
12706
  }
12620
12707
  case "ls":
12621
12708
  return { data: { sessions: [...this.sessions.values()].map((session) => session.info()) } };
12622
- case "send":
12623
- await this.session(request.name).send(request.text, request.paste);
12624
- return { data: { name: request.name, sent: request.text.length } };
12625
- case "key":
12626
- await this.session(request.name).key(request.key);
12627
- return { data: { name: request.name, key: request.key } };
12709
+ case "send": {
12710
+ const session = this.session(request.name, request.instance);
12711
+ await session.send(request.text, request.paste);
12712
+ return { data: { name: request.name, instance: session.instance, sent: request.text.length } };
12713
+ }
12714
+ case "key": {
12715
+ const session = this.session(request.name, request.instance);
12716
+ await session.key(request.key);
12717
+ return { data: { name: request.name, instance: session.instance, key: request.key } };
12718
+ }
12628
12719
  case "read": {
12629
12720
  const session = this.session(request.name);
12630
12721
  const lines = await session.read({ scrollback: request.scrollback, lines: request.lines }, connection);
12631
- return { data: { name: request.name, lines, modes: await session.modes() } };
12722
+ return { data: { name: request.name, instance: session.instance, lines, modes: await session.modes() } };
12632
12723
  }
12633
12724
  case "kill": {
12634
- const session = this.session(request.name);
12725
+ const session = this.session(request.name, request.instance);
12635
12726
  this.sessions.delete(request.name);
12636
12727
  session.kill();
12637
12728
  this.updateManifest((entries2) => entries2.filter((item) => item.name !== request.name));
12638
12729
  this.notifySessions();
12639
- return { data: { name: request.name, killed: true } };
12730
+ return { data: { name: request.name, instance: session.instance, killed: true } };
12640
12731
  }
12641
12732
  case "kill-server": {
12642
12733
  this.stopAccepting();
@@ -12673,25 +12764,32 @@ var TermDaemon = class {
12673
12764
  this.listWatchers.add(connection);
12674
12765
  return { data: { watching: "sessions" } };
12675
12766
  case "label": {
12676
- const session = this.session(request.name);
12767
+ const session = this.session(request.name, request.instance);
12677
12768
  session.label = request.label;
12678
12769
  this.updateManifest((entries2) => entries2.map((item) => item.name === request.name ? { ...item, label: request.label } : item));
12679
12770
  this.notifySessions();
12680
- return { data: { name: request.name, label: request.label } };
12771
+ return { data: { name: request.name, instance: session.instance, label: request.label } };
12681
12772
  }
12682
12773
  case "set-size": {
12683
- const session = this.session(request.name);
12774
+ const session = this.session(request.name, request.instance);
12684
12775
  session.resizeTo(request.cols, request.rows);
12685
12776
  const { cols, rows } = session.info();
12686
- return { data: { name: request.name, cols, rows } };
12777
+ return { data: { name: request.name, instance: session.instance, cols, rows } };
12687
12778
  }
12688
12779
  }
12689
12780
  }
12690
- session(name) {
12781
+ /**
12782
+ * 이름으로 세션을 찾는 한 곳. instance 를 주면 ★지금 그 이름의 세션이 그 인스턴스일 때만 — 같은 이름으로 다시 만든 세션이면
12783
+ * SESSION_REPLACED(설계 terminal-e2e §13-1·§14-6 4). 원격 명령의 인스턴스 검사는 다리가 아니라 명령을 적용하는 여기서 한다.
12784
+ */
12785
+ session(name, instance) {
12691
12786
  const session = this.sessions.get(name);
12692
12787
  if (!session) {
12693
12788
  throw new TermError("TERM_NO_SESSION", `No session named "${name}".`);
12694
12789
  }
12790
+ if (instance !== void 0 && session.instance !== instance) {
12791
+ throw new TermError("SESSION_REPLACED", `The session "${name}" was replaced by a new one with the same name.`);
12792
+ }
12695
12793
  return session;
12696
12794
  }
12697
12795
  /**
@@ -13261,9 +13359,9 @@ function resetField(data) {
13261
13359
  return data && typeof data === "object" && "reset" in data && typeof data.reset === "string" ? data.reset : void 0;
13262
13360
  }
13263
13361
  function restoreSummary(data) {
13264
- const record3 = data && typeof data === "object" ? data : {};
13265
- const names = (key) => Array.isArray(record3[key]) ? record3[key].filter((item) => typeof item === "string") : [];
13266
- const failed = Array.isArray(record3.failed) ? record3.failed : [];
13362
+ const record4 = data && typeof data === "object" ? data : {};
13363
+ const names = (key) => Array.isArray(record4[key]) ? record4[key].filter((item) => typeof item === "string") : [];
13364
+ const failed = Array.isArray(record4.failed) ? record4.failed : [];
13267
13365
  const parts = [
13268
13366
  names("restored").length ? `Restored: ${names("restored").join(", ")}` : "",
13269
13367
  names("running").length ? `Already running: ${names("running").join(", ")}` : "",
@@ -13276,7 +13374,7 @@ function restoreSummary(data) {
13276
13374
  }
13277
13375
 
13278
13376
  // src/core/pc/pcSettings.ts
13279
- import { randomUUID as randomUUID2 } from "crypto";
13377
+ import { randomUUID as randomUUID3 } from "crypto";
13280
13378
  import { readFile as readFile10 } from "fs/promises";
13281
13379
  import { homedir as homedir3 } from "os";
13282
13380
  import { join as join7 } from "path";
@@ -13286,7 +13384,7 @@ function pcSettingsPath(home = homedir3()) {
13286
13384
  function accountKey(endpoint, userId) {
13287
13385
  return `${endpoint}#${userId}`;
13288
13386
  }
13289
- function normalizePcSettings(raw, hostName, newId = randomUUID2) {
13387
+ function normalizePcSettings(raw, hostName, newId = randomUUID3) {
13290
13388
  const fresh = { pcId: newId(), hostName, accounts: {} };
13291
13389
  if (!raw || typeof raw !== "object") {
13292
13390
  return fresh;
@@ -13298,9 +13396,9 @@ function normalizePcSettings(raw, hostName, newId = randomUUID2) {
13298
13396
  const accounts = {};
13299
13397
  if (value.accounts && typeof value.accounts === "object") {
13300
13398
  for (const [key, entry] of Object.entries(value.accounts)) {
13301
- const account = entry;
13302
- if (account && typeof account.consentedAt === "string" && typeof account.remoteTerminal === "boolean") {
13303
- accounts[key] = { consentedAt: account.consentedAt, remoteTerminal: account.remoteTerminal };
13399
+ const account2 = entry;
13400
+ if (account2 && typeof account2.consentedAt === "string" && typeof account2.remoteTerminal === "boolean") {
13401
+ accounts[key] = { consentedAt: account2.consentedAt, remoteTerminal: account2.remoteTerminal };
13304
13402
  }
13305
13403
  }
13306
13404
  }
@@ -13330,12 +13428,14 @@ function withConsent(settings, key, remoteTerminal, now) {
13330
13428
  return { ...settings, accounts: { ...settings.accounts, [key]: { consentedAt: now.toISOString(), remoteTerminal } } };
13331
13429
  }
13332
13430
  function withRemoteTerminal(settings, key, remoteTerminal) {
13333
- const account = settings.accounts[key];
13334
- return account ? { ...settings, accounts: { ...settings.accounts, [key]: { ...account, remoteTerminal } } } : void 0;
13431
+ const account2 = settings.accounts[key];
13432
+ return account2 ? { ...settings, accounts: { ...settings.accounts, [key]: { ...account2, remoteTerminal } } } : void 0;
13433
+ }
13434
+ function isEndpointAccount(key, endpoint) {
13435
+ return key.startsWith(`${endpoint}#`);
13335
13436
  }
13336
13437
  function withoutEndpoint(settings, endpoint) {
13337
- const prefix = `${endpoint}#`;
13338
- return { ...settings, accounts: Object.fromEntries(Object.entries(settings.accounts).filter(([key]) => !key.startsWith(prefix))) };
13438
+ return { ...settings, accounts: Object.fromEntries(Object.entries(settings.accounts).filter(([key]) => !isEndpointAccount(key, endpoint))) };
13339
13439
  }
13340
13440
 
13341
13441
  // src/core/async/sleep.ts
@@ -13387,7 +13487,7 @@ function agentEnv(env) {
13387
13487
  }
13388
13488
 
13389
13489
  // src/core/http/pcHttp.ts
13390
- import { randomUUID as randomUUID3 } from "crypto";
13490
+ import { randomUUID as randomUUID4 } from "crypto";
13391
13491
  var PcCallError = class extends Error {
13392
13492
  constructor(message2, op, status, code) {
13393
13493
  super(message2);
@@ -13437,7 +13537,7 @@ function createPcHttp(input) {
13437
13537
  sessionToken = token;
13438
13538
  },
13439
13539
  async call(op, body, options) {
13440
- const callId = randomUUID3();
13540
+ const callId = randomUUID4();
13441
13541
  const payload = JSON.stringify(body);
13442
13542
  const started = Date.now();
13443
13543
  log.write(input.logging.request({ callId, op, bytes: Buffer.byteLength(payload, "utf8") }, options));
@@ -13541,7 +13641,7 @@ function str(value) {
13541
13641
  // src/core/agent/reply.ts
13542
13642
  function replyForOutcome(outcome, limits, agentName) {
13543
13643
  const attached = attachedWork(outcome, limits);
13544
- const failed = (errorCode2, text2) => ({ status: "FAILED", errorCode: errorCode2, reply: clip(text2, limits.textMaxCharacters), ...attached });
13644
+ const failed = (errorCode3, text2) => ({ status: "FAILED", errorCode: errorCode3, reply: clip(text2, limits.textMaxCharacters), ...attached });
13545
13645
  switch (outcome.kind) {
13546
13646
  case "timeout":
13547
13647
  return failed("TURN_TIMEOUT", "\uC81C\uD55C \uC2DC\uAC04 \uC548\uC5D0 \uB05D\uB098\uC9C0 \uC54A\uC544 \uBA48\uCDC4\uC5B4\uC694. \uB2E4\uC2DC \uBCF4\uB0B4 \uC8FC\uC138\uC694.");
@@ -13580,13 +13680,13 @@ function schemaAnswer(value, textMaxCharacters) {
13580
13680
  if (!isStringArray2(openDocumentUuids) || !isStringArray2(openCardUuids)) return void 0;
13581
13681
  return { reply, openDocumentUuids, openCardUuids };
13582
13682
  }
13583
- function attachedWork(outcome, limits, open2) {
13683
+ function attachedWork(outcome, limits, open3) {
13584
13684
  const facts = outcome.kind === "result" ? outcome.facts : void 0;
13585
13685
  const seen = (uuids) => (uuids ?? []).filter((uuid) => facts?.seen.includes(uuid));
13586
- const documentUuids = unique([...facts?.documents ?? [], ...seen(open2?.openDocumentUuids)]).slice(0, limits.documentsMax);
13686
+ const documentUuids = unique([...facts?.documents ?? [], ...seen(open3?.openDocumentUuids)]).slice(0, limits.documentsMax);
13587
13687
  const createdDocumentUuids = (facts?.createdDocuments ?? []).filter((uuid) => documentUuids.includes(uuid));
13588
13688
  const foundDocumentUuids = documentUuids.filter((uuid) => !facts?.documents.includes(uuid));
13589
- const cardUuids = unique([...facts?.cards ?? [], ...seen(open2?.openCardUuids)]).slice(0, limits.documentsMax);
13689
+ const cardUuids = unique([...facts?.cards ?? [], ...seen(open3?.openCardUuids)]).slice(0, limits.documentsMax);
13590
13690
  return {
13591
13691
  documentUuids,
13592
13692
  ...createdDocumentUuids.length > 0 ? { createdDocumentUuids } : {},
@@ -13609,7 +13709,7 @@ function clip(text2, max) {
13609
13709
  }
13610
13710
 
13611
13711
  // src/core/agent/tools.ts
13612
- import { randomUUID as randomUUID4 } from "crypto";
13712
+ import { randomUUID as randomUUID5 } from "crypto";
13613
13713
  var AgentToolError = class extends Error {
13614
13714
  constructor(message2, tool, code, retryable = false) {
13615
13715
  super(message2);
@@ -13635,7 +13735,7 @@ function createAgentTools(input) {
13635
13735
  return found;
13636
13736
  };
13637
13737
  async function logged(tool, bytes, run, as) {
13638
- const callId = randomUUID4();
13738
+ const callId = randomUUID5();
13639
13739
  const started = Date.now();
13640
13740
  input.log.write({ event: "agent_call", callId, op: "tool", tool, ...as ? { agent: as.agent, agentName: as.name } : {}, bytes });
13641
13741
  let outcome = { ok: false, error: "no response" };
@@ -14526,37 +14626,37 @@ function lastRecord(text2, accept) {
14526
14626
  for (let index = lines.length - 1; index >= 0; index -= 1) {
14527
14627
  const line = lines[index]?.trim();
14528
14628
  if (!line?.startsWith("{")) continue;
14529
- let record3;
14629
+ let record4;
14530
14630
  try {
14531
- record3 = JSON.parse(line);
14631
+ record4 = JSON.parse(line);
14532
14632
  } catch {
14533
14633
  continue;
14534
14634
  }
14535
- const accepted = accept(record3);
14635
+ const accepted = accept(record4);
14536
14636
  if (accepted !== void 0) return accepted;
14537
14637
  }
14538
14638
  return void 0;
14539
14639
  }
14540
14640
  function lastServeStop(text2) {
14541
- return lastRecord(text2, (record3) => record3.event === "serve_stop" && typeof record3.reason === "string" ? { at: typeof record3.ts === "string" ? record3.ts : "", reason: record3.reason } : void 0);
14641
+ return lastRecord(text2, (record4) => record4.event === "serve_stop" && typeof record4.reason === "string" ? { at: typeof record4.ts === "string" ? record4.ts : "", reason: record4.reason } : void 0);
14542
14642
  }
14543
14643
  var UPGRADE_RESULTS = { upgrade_done: "upgraded", upgrade_failed: "failed", upgrade_refused: "refused" };
14544
14644
  function lastUpgrade(text2) {
14545
- return lastRecord(text2, (record3) => {
14546
- const event = record3.event;
14645
+ return lastRecord(text2, (record4) => {
14646
+ const event = record4.event;
14547
14647
  if (event !== "upgrade_done" && event !== "upgrade_failed" && event !== "upgrade_refused") return void 0;
14548
14648
  const text3 = (value) => typeof value === "string" ? value : "";
14549
14649
  return {
14550
- at: text3(record3.ts),
14650
+ at: text3(record4.ts),
14551
14651
  result: UPGRADE_RESULTS[event],
14552
- from: text3(record3.from),
14553
- to: text3(record3.to),
14554
- ...typeof record3.reason === "string" ? { reason: record3.reason } : {}
14652
+ from: text3(record4.from),
14653
+ to: text3(record4.to),
14654
+ ...typeof record4.reason === "string" ? { reason: record4.reason } : {}
14555
14655
  };
14556
14656
  });
14557
14657
  }
14558
14658
  function agentMissing(text2) {
14559
- return lastRecord(text2, (record3) => record3.event === "serve_start" || record3.event === "serve_stop" ? record3.event === "serve_stop" && record3.reason === NO_AGENTS_REASON : void 0) ?? false;
14659
+ return lastRecord(text2, (record4) => record4.event === "serve_start" || record4.event === "serve_stop" ? record4.event === "serve_stop" && record4.reason === NO_AGENTS_REASON : void 0) ?? false;
14560
14660
  }
14561
14661
 
14562
14662
  // src/core/term/remoteLimits.ts
@@ -14572,85 +14672,928 @@ function retryWait(attempt, random) {
14572
14672
  // src/core/term/remote.ts
14573
14673
  import { StringDecoder } from "string_decoder";
14574
14674
 
14575
- // src/core/term/remoteSessions.ts
14576
- function wireSessions(listed3, exclude) {
14577
- return listed3.filter((session) => !exclude.includes(session.name)).map((session) => ({
14578
- name: session.name,
14579
- ...session.label !== void 0 ? { label: session.label } : {},
14580
- ...session.project !== void 0 ? { project: session.project } : {},
14581
- cols: session.cols,
14582
- rows: session.rows,
14583
- ...session.lastOutputAt !== void 0 ? { lastOutputAt: session.lastOutputAt } : {}
14584
- }));
14675
+ // src/core/pc/pcKeys.ts
14676
+ import { readFile as readFile12 } from "fs/promises";
14677
+ import { homedir as homedir4 } from "os";
14678
+ import { join as join8 } from "path";
14679
+
14680
+ // src/core/fs/fileLock.ts
14681
+ import { randomUUID as randomUUID6 } from "crypto";
14682
+ import { link, open as open2, readFile as readFile11, unlink as unlink2 } from "fs/promises";
14683
+ import { dirname as dirname7 } from "path";
14684
+ var FileLockTimeoutError = class extends Error {
14685
+ constructor(lockPath, holderPid) {
14686
+ super(`${lockPath} is held by another ainecto${holderPid !== void 0 ? ` (pid ${holderPid})` : ""} \u2014 try again in a moment.`);
14687
+ this.lockPath = lockPath;
14688
+ this.holderPid = holderPid;
14689
+ }
14690
+ lockPath;
14691
+ holderPid;
14692
+ };
14693
+ var FileLockConflictError = class extends Error {
14694
+ constructor(lockPath, reason) {
14695
+ super(`${lockPath}: ${reason} \u2014 nothing was written.`);
14696
+ this.lockPath = lockPath;
14697
+ }
14698
+ lockPath;
14699
+ };
14700
+ async function withFileLock(lockPath, options, run) {
14701
+ const token = await acquire(lockPath, options);
14702
+ try {
14703
+ return await run();
14704
+ } finally {
14705
+ await release(lockPath, token);
14706
+ }
14585
14707
  }
14586
- function sessionsKey(sessions) {
14587
- return JSON.stringify(sessions);
14708
+ async function acquire(lockPath, options) {
14709
+ await ensurePrivateDir(dirname7(lockPath));
14710
+ const token = randomUUID6();
14711
+ const deadline = Date.now() + options.waitMs;
14712
+ for (; ; ) {
14713
+ if (await create(lockPath, token)) return token;
14714
+ const holder = await readLock(lockPath);
14715
+ if (holder.raw === void 0) continue;
14716
+ if (!holder.content) {
14717
+ throw new FileLockConflictError(lockPath, "it has no owner recorded (it was not made by this version of ainecto), so it cannot be told apart from a lock still being made \u2014 check that no other ainecto is running, delete it and try again");
14718
+ }
14719
+ if (isDead(holder.content, options)) {
14720
+ await options.testHooks?.beforeReclaim?.();
14721
+ if (await reclaim(lockPath, holder.raw, token, options)) continue;
14722
+ }
14723
+ if (Date.now() >= deadline) {
14724
+ throw new FileLockTimeoutError(lockPath, holder.content?.pid);
14725
+ }
14726
+ await new Promise((resolve4) => setTimeout(resolve4, options.pollMs));
14727
+ }
14588
14728
  }
14589
-
14590
- // src/core/term/remoteFrame.ts
14591
- import { createHash as createHash6 } from "crypto";
14592
- function screenFrame(lines, maxD) {
14593
- const sizes = lines.map((line) => Buffer.byteLength(line, "utf8"));
14594
- let start = 0;
14595
- let bytes = sizes.reduce((sum, size) => sum + size, 0) + Math.max(0, lines.length - 1) * 2;
14596
- while (start < lines.length && base64Length(bytes) > maxD) {
14597
- bytes -= (sizes[start] ?? 0) + (start < lines.length - 1 ? 2 : 0);
14598
- start += 1;
14729
+ async function create(path, token) {
14730
+ const staging = `${path}.${token}.tmp`;
14731
+ const handle = await open2(staging, "wx", PRIVATE_FILE_MODE);
14732
+ try {
14733
+ try {
14734
+ await handle.writeFile(JSON.stringify({ pid: process.pid, token }));
14735
+ await handle.sync();
14736
+ } finally {
14737
+ await handle.close();
14738
+ }
14739
+ await link(staging, path);
14740
+ return true;
14741
+ } catch (error) {
14742
+ if (isNodeError(error, "EEXIST")) return false;
14743
+ throw error;
14744
+ } finally {
14745
+ await unlink2(staging);
14599
14746
  }
14600
- const text2 = lines.slice(start).join("\r\n");
14601
- return {
14602
- d: Buffer.from(text2, "utf8").toString("base64"),
14603
- hash: createHash6("sha256").update(text2, "utf8").digest("hex"),
14604
- dropped: start
14605
- };
14606
14747
  }
14607
- function frameBudget(frameMaxBytes, body) {
14608
- return frameMaxBytes - Buffer.byteLength(JSON.stringify({ ...body, d: "" }), "utf8");
14748
+ async function readLock(path) {
14749
+ let raw;
14750
+ try {
14751
+ raw = await readFile11(path, "utf8");
14752
+ } catch (error) {
14753
+ if (isNodeError(error, "ENOENT")) return { raw: void 0, content: void 0 };
14754
+ throw error;
14755
+ }
14756
+ try {
14757
+ const value = JSON.parse(raw);
14758
+ const content = value && Number.isSafeInteger(value.pid) && typeof value.token === "string" ? { pid: value.pid, token: value.token } : void 0;
14759
+ return { raw, content };
14760
+ } catch {
14761
+ return { raw, content: void 0 };
14762
+ }
14609
14763
  }
14610
- function base64Length(bytes) {
14611
- return 4 * Math.ceil(bytes / 3);
14764
+ function isDead(holder, options) {
14765
+ return !(options.isAlive ?? processAlive)(holder.pid);
14612
14766
  }
14613
-
14614
- // src/core/term/remoteViewer.ts
14615
- var RemoteViewer = class {
14616
- constructor(deps) {
14617
- this.deps = deps;
14618
- this.size = deps.size;
14767
+ async function reclaim(lockPath, observed, token, options) {
14768
+ const guard = `${lockPath}.reclaim`;
14769
+ if (!await create(guard, token)) {
14770
+ const other = await readLock(guard);
14771
+ if (other.raw !== void 0 && (!other.content || isDead(other.content, options))) {
14772
+ throw new FileLockConflictError(lockPath, `${guard} was left by an ainecto that stopped while clearing a stale lock, so the stale lock cannot be matched to its owner \u2014 check that no other ainecto is running, delete both files and try again`);
14773
+ }
14774
+ return other.raw === void 0;
14619
14775
  }
14620
- deps;
14621
- stopper = new AbortController();
14622
- dirty = true;
14623
- wakeUp;
14624
- size;
14625
- client;
14626
- get stopped() {
14627
- return this.stopper.signal.aborted;
14776
+ try {
14777
+ await options.testHooks?.duringReclaim?.();
14778
+ const now = await readLock(lockPath);
14779
+ if (now.raw === observed && now.content && isDead(now.content, options)) {
14780
+ await unlink2(lockPath);
14781
+ }
14782
+ } finally {
14783
+ await unlink2(guard);
14628
14784
  }
14629
- stop() {
14630
- if (this.stopped) return;
14631
- this.stopper.abort();
14632
- this.nudge();
14633
- this.client?.close();
14785
+ return true;
14786
+ }
14787
+ async function release(lockPath, token) {
14788
+ if ((await readLock(lockPath)).content?.token !== token) return;
14789
+ try {
14790
+ await unlink2(lockPath);
14791
+ } catch (error) {
14792
+ if (!isNodeError(error, "ENOENT")) throw error;
14634
14793
  }
14635
- /** 세션 크기가 바뀌었다(웹 패널 크기 → 데몬 set-size) — 다시 올린다. */
14636
- setSize(size) {
14637
- this.size = size;
14638
- this.refresh();
14794
+ }
14795
+
14796
+ // src/core/term/e2e.ts
14797
+ import { webcrypto } from "crypto";
14798
+ var subtle = webcrypto.subtle;
14799
+ var VERSION = "ainecto-e2e-v1";
14800
+ var PAIR_LABEL = "ainecto-pair-v1";
14801
+ var PAIR_DONE_LABEL = "ainecto-pair-v1/done";
14802
+ var PAIR_CODE_INFO = { a: "ainecto-pair-code-A", b: "ainecto-pair-code-B" };
14803
+ 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
+ var MAX_MESSAGES_PER_KEY = 2 ** 32;
14806
+ var PUBLIC_KEY_BYTES = 65;
14807
+ var NONCE_SEED_BYTES = 32;
14808
+ var SIGNATURE_BYTES = 64;
14809
+ var CONN_ID_BYTES = 16;
14810
+ var PAIR_CODE_DIGITS = 6;
14811
+ var E2eError = class extends Error {
14812
+ constructor(code, message2) {
14813
+ super(message2);
14814
+ this.code = code;
14639
14815
  }
14640
- /** 다시 그려 보낸다(다시 열린 링크·목록을 올린 뒤). */
14641
- refresh() {
14642
- this.dirty = true;
14643
- this.nudge();
14816
+ code;
14817
+ };
14818
+ var utf8 = (text2) => new TextEncoder().encode(text2);
14819
+ function concatBytes(...parts) {
14820
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
14821
+ let offset = 0;
14822
+ for (const part of parts) {
14823
+ out.set(part, offset);
14824
+ offset += part.length;
14644
14825
  }
14645
- async run() {
14646
- const name = this.deps.session;
14647
- const client = await openTermClient(this.deps.paths, { start: false });
14648
- if (!client || this.stopped) {
14649
- client?.close();
14650
- if (!client) this.deps.onGone("the term daemon is not running");
14651
- return;
14826
+ return out;
14827
+ }
14828
+ function enc(...fields) {
14829
+ return concatBytes(...fields.map((field) => {
14830
+ const bytes = typeof field === "string" ? utf8(field) : field;
14831
+ if (bytes.length > 65535) {
14832
+ throw new E2eError("E2E_BAD_INPUT", `a field is ${bytes.length} bytes (max 65535).`);
14652
14833
  }
14653
- this.client = client;
14834
+ const out = new Uint8Array(2 + bytes.length);
14835
+ new DataView(out.buffer).setUint16(0, bytes.length, false);
14836
+ out.set(bytes, 2);
14837
+ return out;
14838
+ }));
14839
+ }
14840
+ function u64be(value) {
14841
+ const out = new Uint8Array(8);
14842
+ new DataView(out.buffer).setBigUint64(0, BigInt(value), false);
14843
+ return out;
14844
+ }
14845
+ async function sha256(data) {
14846
+ return new Uint8Array(await subtle.digest("SHA-256", data));
14847
+ }
14848
+ function randomBytes3(length = NONCE_SEED_BYTES) {
14849
+ return webcrypto.getRandomValues(new Uint8Array(length));
14850
+ }
14851
+ function expectLength(name, bytes, length) {
14852
+ if (bytes.length !== length) {
14853
+ throw new E2eError("E2E_BAD_INPUT", `${name} must be ${length} bytes, got ${bytes.length}.`);
14854
+ }
14855
+ }
14856
+ var ECDSA = { name: "ECDSA", namedCurve: "P-256" };
14857
+ var ECDH = { name: "ECDH", namedCurve: "P-256" };
14858
+ var SIGN_PARAMS = { name: "ECDSA", hash: "SHA-256" };
14859
+ function base64url(bytes) {
14860
+ return Buffer.from(bytes).toString("base64url");
14861
+ }
14862
+ function fromBase64url(name, text2, length) {
14863
+ if (!/^[A-Za-z0-9_-]+$/.test(text2)) {
14864
+ throw new E2eError("E2E_BAD_INPUT", `${name} is not base64url.`);
14865
+ }
14866
+ const bytes = new Uint8Array(Buffer.from(text2, "base64url"));
14867
+ expectLength(name, bytes, length);
14868
+ return bytes;
14869
+ }
14870
+ function asPublicJwk(raw) {
14871
+ if (!raw || typeof raw !== "object") return void 0;
14872
+ const value = raw;
14873
+ if (value.kty !== "EC" || value.crv !== "P-256" || typeof value.x !== "string" || typeof value.y !== "string") return void 0;
14874
+ try {
14875
+ fromBase64url("x", value.x, 32);
14876
+ fromBase64url("y", value.y, 32);
14877
+ } catch {
14878
+ return void 0;
14879
+ }
14880
+ return { kty: "EC", crv: "P-256", x: value.x, y: value.y };
14881
+ }
14882
+ function asPrivateJwk(raw) {
14883
+ const pub = asPublicJwk(raw);
14884
+ const d = raw?.d;
14885
+ if (!pub || typeof d !== "string") return void 0;
14886
+ try {
14887
+ fromBase64url("d", d, 32);
14888
+ } catch {
14889
+ return void 0;
14890
+ }
14891
+ return { ...pub, d };
14892
+ }
14893
+ function publicRawFromJwk(jwk) {
14894
+ return concatBytes(Uint8Array.of(4), fromBase64url("x", jwk.x, 32), fromBase64url("y", jwk.y, 32));
14895
+ }
14896
+ function publicJwkFromRaw(raw) {
14897
+ expectLength("public key", raw, PUBLIC_KEY_BYTES);
14898
+ if (raw[0] !== 4) {
14899
+ throw new E2eError("E2E_BAD_INPUT", "public key must be an uncompressed P-256 point (0x04 \u2016 X \u2016 Y).");
14900
+ }
14901
+ return { kty: "EC", crv: "P-256", x: base64url(raw.subarray(1, 33)), y: base64url(raw.subarray(33, 65)) };
14902
+ }
14903
+ async function generateSigningJwk() {
14904
+ const pair2 = await subtle.generateKey(ECDSA, true, ["sign", "verify"]);
14905
+ const jwk = asPrivateJwk(await subtle.exportKey("jwk", pair2.privateKey));
14906
+ if (!jwk) {
14907
+ throw new Error("WebCrypto returned an unexpected P-256 JWK.");
14908
+ }
14909
+ return jwk;
14910
+ }
14911
+ async function importSigningKey(jwk) {
14912
+ return await subtle.importKey("jwk", { ...jwk }, ECDSA, false, ["sign"]);
14913
+ }
14914
+ async function assertSigningPublicKey(publicKey) {
14915
+ try {
14916
+ await subtle.importKey("jwk", { ...publicKey }, ECDSA, false, ["verify"]);
14917
+ } catch {
14918
+ throw new E2eError("E2E_BAD_INPUT", "public key is not a valid P-256 point.");
14919
+ }
14920
+ }
14921
+ async function signBytes(privateKey, data) {
14922
+ return new Uint8Array(await subtle.sign(SIGN_PARAMS, privateKey, data));
14923
+ }
14924
+ async function verifyBytes(publicKey, signature, data) {
14925
+ if (signature.length !== SIGNATURE_BYTES) return false;
14926
+ try {
14927
+ const key = await subtle.importKey("jwk", { ...publicKey }, ECDSA, false, ["verify"]);
14928
+ return await subtle.verify(SIGN_PARAMS, key, signature, data);
14929
+ } catch {
14930
+ return false;
14931
+ }
14932
+ }
14933
+ 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)) };
14936
+ }
14937
+ var USER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
14938
+ function transcriptUserId(raw) {
14939
+ const userId = raw.toLowerCase();
14940
+ expectUserId(userId);
14941
+ return userId;
14942
+ }
14943
+ function expectUserId(userId) {
14944
+ if (!USER_ID.test(userId)) {
14945
+ throw new E2eError("E2E_BAD_INPUT", "userId must be a lowercase 36-character UUID.");
14946
+ }
14947
+ }
14948
+ async function browserKeyIdOf(browserPublicRaw) {
14949
+ expectLength("browserPub", browserPublicRaw, PUBLIC_KEY_BYTES);
14950
+ return Buffer.from((await sha256(browserPublicRaw)).subarray(0, 16)).toString("hex");
14951
+ }
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
+ async function pairCommitment(pcPublicRaw, nP) {
14958
+ expectLength("pcPub", pcPublicRaw, PUBLIC_KEY_BYTES);
14959
+ expectLength("nP", nP, NONCE_SEED_BYTES);
14960
+ return await sha256(concatBytes(pcPublicRaw, nP));
14961
+ }
14962
+ async function pairTranscript(input) {
14963
+ expectUserId(input.userId);
14964
+ expectLength("pcPub", input.pcPublicRaw, PUBLIC_KEY_BYTES);
14965
+ expectLength("browserPub", input.browserPublicRaw, PUBLIC_KEY_BYTES);
14966
+ expectLength("nP", input.nP, NONCE_SEED_BYTES);
14967
+ expectLength("nB", input.nB, NONCE_SEED_BYTES);
14968
+ return await sha256(enc(PAIR_LABEL, input.userId, input.pcId, input.pcPublicRaw, input.browserPublicRaw, input.nP, input.nB));
14969
+ }
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
+ function pairDoneInput(transcript) {
14995
+ expectLength("transcript", transcript, 32);
14996
+ return enc(PAIR_DONE_LABEL, transcript);
14997
+ }
14998
+ function assertHello(hello) {
14999
+ expectUserId(hello.userId);
15000
+ expectLength("eB", hello.eB, PUBLIC_KEY_BYTES);
15001
+ expectLength("nB", hello.nB, NONCE_SEED_BYTES);
15002
+ }
15003
+ function helloSignatureInput(hello) {
15004
+ assertHello(hello);
15005
+ return enc(VERSION, "browser", "hello", hello.userId, hello.pcId, hello.channel, hello.browserKeyId, hello.eB, hello.nB);
15006
+ }
15007
+ async function channelTranscript(input) {
15008
+ const { hello } = input;
15009
+ assertHello(hello);
15010
+ expectLength("pcPub", input.pcPublicRaw, PUBLIC_KEY_BYTES);
15011
+ expectLength("browserPub", input.browserPublicRaw, PUBLIC_KEY_BYTES);
15012
+ expectLength("eP", input.eP, PUBLIC_KEY_BYTES);
15013
+ expectLength("nP'", input.nP, NONCE_SEED_BYTES);
15014
+ return await sha256(enc(
15015
+ VERSION,
15016
+ hello.userId,
15017
+ hello.pcId,
15018
+ hello.channel,
15019
+ hello.browserKeyId,
15020
+ input.pcPublicRaw,
15021
+ input.browserPublicRaw,
15022
+ hello.eB,
15023
+ hello.nB,
15024
+ input.eP,
15025
+ input.nP
15026
+ ));
15027
+ }
15028
+ async function deriveChannelSecrets(input) {
15029
+ expectLength("peer ephemeral key", input.peerPublicRaw, PUBLIC_KEY_BYTES);
15030
+ expectLength("transcript", input.transcript, 32);
15031
+ let peer;
15032
+ try {
15033
+ peer = await subtle.importKey("raw", input.peerPublicRaw, ECDH, false, []);
15034
+ } catch {
15035
+ throw new E2eError("E2E_BAD_INPUT", "peer ephemeral key is not a valid P-256 point.");
15036
+ }
15037
+ const shared = new Uint8Array(await subtle.deriveBits({ name: "ECDH", public: peer }, input.own, 256));
15038
+ const ikm = await subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);
15039
+ const derive = async (info, bytes) => new Uint8Array(await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: input.transcript, info: utf8(info) }, ikm, bytes * 8));
15040
+ return {
15041
+ browserToPc: await derive(KEY_INFO.browserToPc, 32),
15042
+ pcToBrowser: await derive(KEY_INFO.pcToBrowser, 32),
15043
+ connId: await derive(KEY_INFO.connId, CONN_ID_BYTES)
15044
+ };
15045
+ }
15046
+ async function importMessageKey(secret) {
15047
+ expectLength("message key", secret, 32);
15048
+ return await subtle.importKey("raw", secret, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
15049
+ }
15050
+ function assertCounter(counter) {
15051
+ if (!Number.isSafeInteger(counter) || counter < 0 || counter >= MAX_MESSAGES_PER_KEY) {
15052
+ throw new E2eError("E2E_COUNTER_REJECTED", `counter must be an integer from 0 to ${MAX_MESSAGES_PER_KEY - 1} (then start a new hello).`);
15053
+ }
15054
+ }
15055
+ function messageNonce(counter) {
15056
+ assertCounter(counter);
15057
+ return concatBytes(new Uint8Array(4), u64be(counter));
15058
+ }
15059
+ function messageAad(header) {
15060
+ assertCounter(header.counter);
15061
+ expectLength("connId", header.connId, CONN_ID_BYTES);
15062
+ return enc(VERSION, header.type, header.connId, header.pcId, header.session, header.operationId, header.projectUuid, u64be(header.counter));
15063
+ }
15064
+ async function sealMessage(key, header, plaintext) {
15065
+ return new Uint8Array(await subtle.encrypt(
15066
+ { name: "AES-GCM", iv: messageNonce(header.counter), additionalData: messageAad(header), tagLength: 128 },
15067
+ key,
15068
+ plaintext
15069
+ ));
15070
+ }
15071
+ async function openMessage(key, header, ciphertext, state) {
15072
+ assertCounter(header.counter);
15073
+ const inOrder = state.order === "exact" ? header.counter === state.next : header.counter >= state.next;
15074
+ if (!inOrder) {
15075
+ throw new E2eError(
15076
+ "E2E_COUNTER_REJECTED",
15077
+ `counter ${header.counter} rejected (${state.order === "exact" ? `expected exactly ${state.next}` : `expected ${state.next} or more`}).`
15078
+ );
15079
+ }
15080
+ let plaintext;
15081
+ try {
15082
+ plaintext = await subtle.decrypt(
15083
+ { name: "AES-GCM", iv: messageNonce(header.counter), additionalData: messageAad(header), tagLength: 128 },
15084
+ key,
15085
+ ciphertext
15086
+ );
15087
+ } catch {
15088
+ throw new E2eError("E2E_DECRYPT_FAILED", "message failed authentication (wrong key, header or ciphertext).");
15089
+ }
15090
+ return { plaintext: new Uint8Array(plaintext), state: { order: state.order, next: header.counter + 1 } };
15091
+ }
15092
+
15093
+ // src/core/pc/pcKeys.ts
15094
+ var BROWSER_NAME_MAX = 40;
15095
+ var DEFAULT_BROWSER_NAME = "Browser";
15096
+ function pcKeysPath(home = homedir4()) {
15097
+ return join8(home, ".ainecto", "pc-keys.json");
15098
+ }
15099
+ function normalizePcKeys(raw) {
15100
+ const accounts = {};
15101
+ const stored = raw && typeof raw === "object" ? raw.accounts : void 0;
15102
+ if (stored && typeof stored === "object") {
15103
+ for (const [key, entry] of Object.entries(stored)) {
15104
+ const value = entry && typeof entry === "object" ? entry : void 0;
15105
+ const pcKey = asPrivateJwk(value?.pcKey);
15106
+ if (!pcKey) continue;
15107
+ const browsers = Array.isArray(value?.browsers) ? value.browsers.flatMap((item) => {
15108
+ const browser = asPairedBrowser(item);
15109
+ return browser ? [browser] : [];
15110
+ }) : [];
15111
+ const pending = value?.pendingTurnOff;
15112
+ accounts[key] = typeof pending?.removedAt === "string" ? { pcKey, browsers, pendingTurnOff: {
15113
+ removedAt: pending.removedAt,
15114
+ groups: Array.isArray(pending.groups) ? pending.groups.flatMap(asPcGroup) : [],
15115
+ removals: Array.isArray(pending.removals) ? pending.removals.flatMap(asPendingRemoval) : []
15116
+ } } : { pcKey, browsers };
15117
+ }
15118
+ }
15119
+ return { accounts };
15120
+ }
15121
+ function asPcGroup(raw) {
15122
+ const value = raw && typeof raw === "object" ? raw : void 0;
15123
+ const positive = (n) => Number.isSafeInteger(n) && n > 0;
15124
+ return value && typeof value.session === "string" && positive(value.pid) && positive(value.pgid) ? [{ session: value.session, pid: value.pid, pgid: value.pgid }] : [];
15125
+ }
15126
+ function asPendingRemoval(raw) {
15127
+ const value = raw && typeof raw === "object" ? raw : void 0;
15128
+ if (!value || typeof value.keyId !== "string" || value.keyId === "" || typeof value.name !== "string") return [];
15129
+ const removalId = typeof value.removalId === "string" && value.removalId !== "" ? value.removalId : value.keyId;
15130
+ return [{ removalId, keyId: value.keyId, name: value.name }];
15131
+ }
15132
+ function asPairedBrowser(raw) {
15133
+ if (!raw || typeof raw !== "object") return void 0;
15134
+ const value = raw;
15135
+ const publicJwk = asPublicJwk(value.publicJwk);
15136
+ if (!publicJwk || typeof value.keyId !== "string" || value.keyId === "" || typeof value.name !== "string" || typeof value.pairedAt !== "string") {
15137
+ return void 0;
15138
+ }
15139
+ return { keyId: value.keyId, publicJwk, name: value.name, pairedAt: value.pairedAt };
15140
+ }
15141
+ async function loadPcKeys(path) {
15142
+ let raw;
15143
+ try {
15144
+ raw = await readFile12(path, "utf8");
15145
+ } catch (error) {
15146
+ if (isNodeError(error, "ENOENT")) {
15147
+ return { accounts: {} };
15148
+ }
15149
+ throw error;
15150
+ }
15151
+ try {
15152
+ return normalizePcKeys(JSON.parse(raw));
15153
+ } catch (error) {
15154
+ throw new Error(`${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}). Delete it to pair again.`);
15155
+ }
15156
+ }
15157
+ var PC_KEYS_LOCK = { waitMs: 5e3, pollMs: 50 };
15158
+ async function updatePcKeys(path, change, lock = PC_KEYS_LOCK) {
15159
+ return await withFileLock(`${path}.lock`, lock, async () => {
15160
+ const current = await loadPcKeys(path);
15161
+ const next = await change(current);
15162
+ if (next === void 0) return current;
15163
+ await writePrivateFileAtomic(path, `${JSON.stringify(next, null, 2)}
15164
+ `);
15165
+ return next;
15166
+ });
15167
+ }
15168
+ function browserNameOf(raw) {
15169
+ const cleaned = [...raw.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, "").trim()].slice(0, BROWSER_NAME_MAX).join("").trim();
15170
+ return cleaned === "" ? DEFAULT_BROWSER_NAME : cleaned;
15171
+ }
15172
+ function uniqueName(account2, wanted, keyId) {
15173
+ const named = [...account2.browsers, ...account2.pendingTurnOff?.removals ?? []];
15174
+ const taken = new Set(named.filter((item) => item.keyId !== keyId).map((item) => item.name));
15175
+ if (!taken.has(wanted)) return wanted;
15176
+ for (let n = 2; ; n += 1) {
15177
+ const candidate = `${wanted} (${n})`;
15178
+ if (!taken.has(candidate)) return candidate;
15179
+ }
15180
+ }
15181
+ function withBrowser(keys, account2, pcKey, browser) {
15182
+ const current = keys.accounts[account2] ?? { pcKey, browsers: [] };
15183
+ const others = current.browsers.filter((item) => item.keyId !== browser.keyId);
15184
+ const added = { ...browser, name: uniqueName(current, browser.name, browser.keyId) };
15185
+ return { accounts: { ...keys.accounts, [account2]: { ...current, browsers: [...others, added] } } };
15186
+ }
15187
+ function withoutBrowser(keys, account2, keyIdOrName) {
15188
+ const current = keys.accounts[account2];
15189
+ const removed = current?.browsers.find((item) => item.keyId === keyIdOrName) ?? current?.browsers.find((item) => item.name === keyIdOrName);
15190
+ if (!current || !removed) {
15191
+ return { keys, removed: void 0 };
15192
+ }
15193
+ return {
15194
+ keys: { accounts: { ...keys.accounts, [account2]: { ...current, browsers: current.browsers.filter((item) => item !== removed) } } },
15195
+ removed
15196
+ };
15197
+ }
15198
+ function withPendingTurnOff(keys, account2, add) {
15199
+ const current = keys.accounts[account2];
15200
+ if (!current) return keys;
15201
+ const { pendingTurnOff: previous, ...rest } = current;
15202
+ const known = previous?.groups ?? [];
15203
+ const fresh = add.groups.filter((group) => !known.some((item) => sameGroup(item, group)));
15204
+ const removals = previous?.removals ?? [];
15205
+ const removal = add.removal && !removals.some((item) => item.removalId === add.removal?.removalId) ? [add.removal] : [];
15206
+ if (previous && fresh.length === 0 && removal.length === 0) return keys;
15207
+ const pendingTurnOff = {
15208
+ removedAt: previous?.removedAt ?? add.at.toISOString(),
15209
+ groups: [...known, ...fresh],
15210
+ removals: [...removals, ...removal]
15211
+ };
15212
+ return { accounts: { ...keys.accounts, [account2]: { ...rest, pendingTurnOff } } };
15213
+ }
15214
+ function pendingRemovalOf(account2, keyIdOrName) {
15215
+ const removals = account2?.pendingTurnOff?.removals ?? [];
15216
+ return removals.find((item) => item.keyId === keyIdOrName) ?? removals.find((item) => item.name === keyIdOrName);
15217
+ }
15218
+ function withTurnOffConfirmed(keys, account2, done) {
15219
+ const current = keys.accounts[account2];
15220
+ if (!current?.pendingTurnOff) return keys;
15221
+ const { pendingTurnOff: previous, ...rest } = current;
15222
+ const groups = previous.groups.filter((group) => !done.groups.some((item) => sameGroup(item, group)));
15223
+ const removals = previous.removals.filter((item) => item.removalId !== done.removalId);
15224
+ if (groups.length === previous.groups.length && removals.length === previous.removals.length) return keys;
15225
+ const left = groups.length > 0 || removals.length > 0;
15226
+ return { accounts: { ...keys.accounts, [account2]: left ? { ...rest, pendingTurnOff: { ...previous, groups, removals } } : rest } };
15227
+ }
15228
+ function sameGroup(a, b) {
15229
+ return a.pid === b.pid && a.pgid === b.pgid;
15230
+ }
15231
+ function withoutEndpointKeys(keys, endpoint) {
15232
+ return { accounts: Object.fromEntries(Object.entries(keys.accounts).filter(([key]) => !isEndpointAccount(key, endpoint))) };
15233
+ }
15234
+
15235
+ // src/core/term/remoteChannel.ts
15236
+ import { createHash as createHash6 } from "crypto";
15237
+ var HANDSHAKE_TTL_MS = 3e4;
15238
+ var HANDSHAKE_MAX = 4;
15239
+ var ACTIVE_CHANNEL_MAX = 8;
15240
+ var ANSWER_CODES = ["TERM_NO_SESSION", "TERM_SESSION_EXISTS", "TERM_BAD_REQUEST", "SESSION_REPLACED", "REMOTE_OFF"];
15241
+ function answerCodeOf(code) {
15242
+ return ANSWER_CODES.includes(code) ? code : "TERM_FAILED";
15243
+ }
15244
+ var COMMAND_KINDS = ["confirm", "input", "key", "resize", "create", "kill", "label"];
15245
+ var ChannelSealError = class extends Error {
15246
+ constructor(reason, message2) {
15247
+ super(message2);
15248
+ this.reason = reason;
15249
+ }
15250
+ reason;
15251
+ };
15252
+ var ChannelBook = class {
15253
+ constructor(pcId, now = Date.now) {
15254
+ this.pcId = pcId;
15255
+ this.now = now;
15256
+ }
15257
+ pcId;
15258
+ now;
15259
+ channels = /* @__PURE__ */ new Map();
15260
+ /** 장부에 있나(미확정 포함). */
15261
+ has(channelId) {
15262
+ return this.channels.has(channelId);
15263
+ }
15264
+ isActive(channelId) {
15265
+ return this.channels.get(channelId)?.active === true;
15266
+ }
15267
+ activeIds() {
15268
+ return [...this.channels.values()].filter((channel) => channel.active).map((channel) => channel.channelId);
15269
+ }
15270
+ browserOf(channelId) {
15271
+ return this.channels.get(channelId)?.browser;
15272
+ }
15273
+ /** 활성 채널의 연속 실행 확인 지점 — 없으면 undefined. */
15274
+ executedThrough(channelId) {
15275
+ const channel = this.channels.get(channelId);
15276
+ return channel?.active ? channel.executedThrough : void 0;
15277
+ }
15278
+ /** 웹→PC n 번 실행이 확인됐다 — 연속일 때만 오른다(건너뛰지 않는다, §14-6 1). 올랐으면 true. */
15279
+ executed(channelId, n) {
15280
+ const channel = this.channels.get(channelId);
15281
+ if (!channel?.active || n !== channel.executedThrough + 1) return false;
15282
+ channel.executedThrough = n;
15283
+ return true;
15284
+ }
15285
+ /** 채널을 장부에서 지운다(닫힘·웹 닫음·키 폐기). 있었으면 true. */
15286
+ drop(channelId) {
15287
+ return this.channels.delete(channelId);
15288
+ }
15289
+ /** 모두 지운다(원격 끔·링크 다시 열기) — 지운 id 들. */
15290
+ dropAll() {
15291
+ const ids = [...this.channels.keys()];
15292
+ this.channels.clear();
15293
+ return ids;
15294
+ }
15295
+ /** 기한(C-E8)이 지난 미확정 handshake 를 지운다 — 지운 id 들(다리가 HANDSHAKE_EXPIRED 로 닫는다). */
15296
+ expired() {
15297
+ const now = this.now();
15298
+ const ids = [...this.channels.values()].filter((channel) => !channel.active && now >= channel.expiresAt).map((channel) => channel.channelId);
15299
+ for (const id of ids) this.channels.delete(id);
15300
+ return ids;
15301
+ }
15302
+ /** hello 하나(§11-2·§13-4·A4). 신뢰가 없으면(짝짓지 않음·계정 모름) PAIRING_REQUIRED. */
15303
+ async hello(channelId, raw, trust) {
15304
+ if (this.channels.has(channelId)) return { type: "ignored" };
15305
+ const hello = wireHello(raw);
15306
+ if (!trust || !hello) return { type: "refuse" };
15307
+ const browser = trust.browsers.find((item) => item.keyId === hello.browserKeyId);
15308
+ if (!browser) return { type: "refuse" };
15309
+ const fields = { userId: trust.userId, pcId: this.pcId, channel: hello.channel, browserKeyId: hello.browserKeyId, eB: hello.eB, nB: hello.nB };
15310
+ if (!await verifyBytes(browser.publicJwk, hello.sig, helloSignatureInput(fields))) return { type: "refuse" };
15311
+ const now = this.now();
15312
+ const pending = [...this.channels.values()].filter((channel) => !channel.active && now < channel.expiresAt).length;
15313
+ if (pending >= HANDSHAKE_MAX) return { type: "close", reason: "HANDSHAKE_LIMIT" };
15314
+ const ephemeral = await generateEphemeral();
15315
+ const nP = randomBytes3(NONCE_SEED_BYTES);
15316
+ const transcript = await channelTranscript({
15317
+ hello: fields,
15318
+ pcPublicRaw: publicRawFromJwk(trust.pcKey),
15319
+ browserPublicRaw: publicRawFromJwk(browser.publicJwk),
15320
+ eP: ephemeral.publicRaw,
15321
+ nP
15322
+ });
15323
+ let secrets;
15324
+ try {
15325
+ secrets = await deriveChannelSecrets({ own: ephemeral.privateKey, peerPublicRaw: hello.eB, transcript });
15326
+ } catch (error) {
15327
+ if (error instanceof E2eError) return { type: "refuse" };
15328
+ throw error;
15329
+ }
15330
+ const sig = await signBytes(await importSigningKey(trust.pcKey), transcript);
15331
+ const channelBrowser = { keyId: browser.keyId, name: browser.name };
15332
+ this.channels.set(channelId, {
15333
+ channelId,
15334
+ browser: channelBrowser,
15335
+ connId: secrets.connId,
15336
+ b2p: await importMessageKey(secrets.browserToPc),
15337
+ p2b: await importMessageKey(secrets.pcToBrowser),
15338
+ receive: { order: "exact", next: 0 },
15339
+ sendNext: 0,
15340
+ active: false,
15341
+ expiresAt: now + HANDSHAKE_TTL_MS,
15342
+ executedThrough: -1,
15343
+ last: void 0
15344
+ });
15345
+ return { type: "welcome", welcome: { eP: b64u(ephemeral.publicRaw), nP: b64u(nP), sig: b64u(sig) }, browser: channelBrowser };
15346
+ }
15347
+ /** 웹→PC 명령 하나(§14-3). 닫는 결과면 장부에서 이미 지웠다. */
15348
+ async receive(wire) {
15349
+ const channel = this.channels.get(wire.channelId);
15350
+ if (!channel) return { type: "unknown" };
15351
+ const close = (reason) => {
15352
+ this.channels.delete(wire.channelId);
15353
+ return { type: "close", reason };
15354
+ };
15355
+ if (!channel.active && this.now() >= channel.expiresAt) return close("HANDSHAKE_EXPIRED");
15356
+ const digest = createHash6("sha256").update(wire.c, "utf8").digest("hex");
15357
+ if (channel.last && wire.n === channel.last.n && digest === channel.last.digest) return { type: "duplicate" };
15358
+ if (wire.n >= MAX_MESSAGES_PER_KEY) return close("MESSAGE_LIMIT");
15359
+ if (wire.n !== channel.receive.next) return close("CHANNEL_OUT_OF_ORDER");
15360
+ if (wire.kind === "confirm" !== (wire.n === 0)) return close("CHANNEL_OUT_OF_ORDER");
15361
+ const ciphertext = fromB64u(wire.c);
15362
+ if (!ciphertext) return close("DECRYPT_FAILED");
15363
+ let opened;
15364
+ try {
15365
+ opened = await openMessage(channel.b2p, {
15366
+ type: wire.kind,
15367
+ connId: channel.connId,
15368
+ pcId: this.pcId,
15369
+ session: wire.session ?? "",
15370
+ operationId: wire.opId ?? "",
15371
+ projectUuid: wire.projectUuid ?? "",
15372
+ counter: wire.n
15373
+ }, ciphertext, channel.receive);
15374
+ } catch {
15375
+ return close("DECRYPT_FAILED");
15376
+ }
15377
+ const command = sealedCommand(wire, opened.plaintext);
15378
+ if (!command) return close("DECRYPT_FAILED");
15379
+ channel.receive = opened.state;
15380
+ channel.last = { n: wire.n, digest };
15381
+ if (command.kind !== "confirm") return { type: "command", command, browser: channel.browser };
15382
+ if (this.activeIds().length >= ACTIVE_CHANNEL_MAX) return close("CHANNEL_LIMIT");
15383
+ channel.active = true;
15384
+ channel.executedThrough = 0;
15385
+ return { type: "confirmed", browser: channel.browser };
15386
+ }
15387
+ /**
15388
+ * PC→웹 봉인(frame·answer — A3 AAD). 번호는 await 전에 배정한다. 활성 채널이 아니면 CHANNEL_GONE, 번호가 다 됐으면 MESSAGE_LIMIT.
15389
+ * c = base64url(AES-GCM 암호문 ‖ 태그).
15390
+ */
15391
+ async seal(channelId, header, body) {
15392
+ const channel = this.channels.get(channelId);
15393
+ if (!channel?.active) throw new ChannelSealError("CHANNEL_GONE", `channel ${channelId} is not open`);
15394
+ const n = channel.sendNext;
15395
+ if (n >= MAX_MESSAGES_PER_KEY) throw new ChannelSealError("MESSAGE_LIMIT", `channel ${channelId} used up its message numbers`);
15396
+ channel.sendNext = n + 1;
15397
+ const sealed = await sealMessage(channel.p2b, {
15398
+ type: header.kind,
15399
+ connId: channel.connId,
15400
+ pcId: this.pcId,
15401
+ session: header.session,
15402
+ operationId: header.opId ?? "",
15403
+ projectUuid: header.projectUuid ?? "",
15404
+ counter: n
15405
+ }, new TextEncoder().encode(JSON.stringify(body)));
15406
+ return { n, c: b64u(sealed) };
15407
+ }
15408
+ };
15409
+ function wireHello(raw) {
15410
+ const value = record2(raw);
15411
+ const channel = text(value?.channel);
15412
+ const browserKeyId = text(value?.browserKeyId);
15413
+ const eB = fromB64u(value?.eB, PUBLIC_KEY_BYTES);
15414
+ const nB = fromB64u(value?.nB, NONCE_SEED_BYTES);
15415
+ const sig = fromB64u(value?.sig, SIGNATURE_BYTES);
15416
+ return channel && browserKeyId && eB && nB && sig ? { channel, eB, nB, browserKeyId, sig } : void 0;
15417
+ }
15418
+ function wireCommand(raw) {
15419
+ const value = record2(raw);
15420
+ const channelId = text(value?.channelId);
15421
+ const n = value?.n;
15422
+ const c = text(value?.c);
15423
+ const kind = value?.kind;
15424
+ if (!value || !channelId || typeof n !== "number" || !Number.isSafeInteger(n) || n < 0 || !c || typeof kind !== "string" || !COMMAND_KINDS.includes(kind)) {
15425
+ return void 0;
15426
+ }
15427
+ const optional = (key) => {
15428
+ const item = text(value[key]);
15429
+ return item ? { [key]: item } : {};
15430
+ };
15431
+ return {
15432
+ channelId,
15433
+ n,
15434
+ c,
15435
+ kind,
15436
+ ...optional("session"),
15437
+ ...optional("opId"),
15438
+ ...optional("projectUuid"),
15439
+ ...optional("requestId")
15440
+ };
15441
+ }
15442
+ function sealedCommand(wire, plaintext) {
15443
+ let parsed;
15444
+ try {
15445
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(plaintext));
15446
+ } catch {
15447
+ return void 0;
15448
+ }
15449
+ const body = record2(parsed);
15450
+ if (!body) return void 0;
15451
+ const session = text(body.session);
15452
+ const instance = text(body.instance);
15453
+ const opId = text(body.opId);
15454
+ const targets = (withOp) => session !== void 0 && instance !== void 0 && wire.session === session && wire.opId === (withOp ? opId : void 0) && (!withOp || opId !== void 0) && wire.projectUuid === void 0;
15455
+ switch (wire.kind) {
15456
+ case "confirm":
15457
+ return wire.session === void 0 && wire.opId === void 0 && wire.projectUuid === void 0 ? { kind: "confirm" } : void 0;
15458
+ case "input": {
15459
+ const d = body.d;
15460
+ return targets(false) && typeof d === "string" && /^[A-Za-z0-9+/_-]*={0,2}$/.test(d) ? { kind: "input", session, instance, bytes: Buffer.from(d, "base64") } : void 0;
15461
+ }
15462
+ case "key": {
15463
+ const key = text(body.key);
15464
+ return targets(false) && key ? { kind: "key", session, instance, key } : void 0;
15465
+ }
15466
+ case "resize": {
15467
+ const { cols, rows } = body;
15468
+ return targets(false) && isSize(cols) && isSize(rows) ? { kind: "resize", session, instance, cols, rows } : void 0;
15469
+ }
15470
+ case "create": {
15471
+ const name = text(body.name);
15472
+ const projectUuid = text(body.projectUuid);
15473
+ const cwd = text(body.cwd);
15474
+ const command = body.command;
15475
+ if (!name || !opId || wire.session !== name || wire.opId !== opId || wire.projectUuid !== projectUuid) return void 0;
15476
+ if (command !== void 0 && typeof command !== "string") return void 0;
15477
+ return {
15478
+ kind: "create",
15479
+ opId,
15480
+ name,
15481
+ ...projectUuid ? { projectUuid } : {},
15482
+ ...cwd ? { cwd } : {},
15483
+ ...typeof command === "string" ? { command } : {}
15484
+ };
15485
+ }
15486
+ case "kill":
15487
+ return targets(true) ? { kind: "kill", opId, session, instance } : void 0;
15488
+ case "label": {
15489
+ const label = text(body.label);
15490
+ return targets(true) && label ? { kind: "label", opId, session, instance, label } : void 0;
15491
+ }
15492
+ }
15493
+ }
15494
+ function record2(value) {
15495
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
15496
+ }
15497
+ function text(value) {
15498
+ return typeof value === "string" && value !== "" ? value : void 0;
15499
+ }
15500
+ function isSize(value) {
15501
+ return typeof value === "number" && Number.isInteger(value) && value >= 1;
15502
+ }
15503
+ function b64u(bytes) {
15504
+ return Buffer.from(bytes).toString("base64url");
15505
+ }
15506
+ function fromB64u(value, length) {
15507
+ if (typeof value !== "string" || value === "" || !/^[A-Za-z0-9_-]+$/.test(value)) return void 0;
15508
+ const bytes = new Uint8Array(Buffer.from(value, "base64url"));
15509
+ return length === void 0 || bytes.length === length ? bytes : void 0;
15510
+ }
15511
+
15512
+ // src/core/term/remoteSessions.ts
15513
+ function wireSessions(listed3, exclude) {
15514
+ return listed3.filter((session) => !exclude.includes(session.name)).map((session) => ({
15515
+ name: session.name,
15516
+ ...session.label !== void 0 ? { label: session.label } : {},
15517
+ ...session.project !== void 0 ? { project: session.project } : {},
15518
+ cols: session.cols,
15519
+ rows: session.rows,
15520
+ ...session.lastOutputAt !== void 0 ? { lastOutputAt: session.lastOutputAt } : {},
15521
+ ...session.instance !== void 0 ? { instance: session.instance } : {}
15522
+ }));
15523
+ }
15524
+ function sessionsKey(sessions) {
15525
+ return JSON.stringify(sessions);
15526
+ }
15527
+
15528
+ // src/core/term/remoteFrame.ts
15529
+ import { createHash as createHash7 } from "crypto";
15530
+ function screenFrame(lines, maxD) {
15531
+ const sizes = lines.map((line) => Buffer.byteLength(line, "utf8"));
15532
+ let start = 0;
15533
+ let bytes = sizes.reduce((sum, size) => sum + size, 0) + Math.max(0, lines.length - 1) * 2;
15534
+ while (start < lines.length && base64Length(bytes) > maxD) {
15535
+ bytes -= (sizes[start] ?? 0) + (start < lines.length - 1 ? 2 : 0);
15536
+ start += 1;
15537
+ }
15538
+ const text2 = lines.slice(start).join("\r\n");
15539
+ return {
15540
+ d: Buffer.from(text2, "utf8").toString("base64"),
15541
+ hash: createHash7("sha256").update(text2, "utf8").digest("hex"),
15542
+ dropped: start
15543
+ };
15544
+ }
15545
+ var GCM_TAG_BYTES = 16;
15546
+ var MAX_COUNTER = 2 ** 32 - 1;
15547
+ function frameBudget(frameMaxBytes, outer, sealed) {
15548
+ const outside = Buffer.byteLength(JSON.stringify({ ...outer, n: MAX_COUNTER, c: "" }), "utf8");
15549
+ const cipherBytes = Math.floor((frameMaxBytes - outside) * 3 / 4);
15550
+ const inside = Buffer.byteLength(JSON.stringify({ ...sealed, d: "", executedThrough: MAX_COUNTER }), "utf8");
15551
+ return cipherBytes - GCM_TAG_BYTES - inside;
15552
+ }
15553
+ function base64Length(bytes) {
15554
+ return 4 * Math.ceil(bytes / 3);
15555
+ }
15556
+
15557
+ // src/core/term/remoteViewer.ts
15558
+ var RemoteViewer = class {
15559
+ constructor(deps) {
15560
+ this.deps = deps;
15561
+ this.size = deps.size;
15562
+ }
15563
+ deps;
15564
+ stopper = new AbortController();
15565
+ dirty = true;
15566
+ wakeUp;
15567
+ size;
15568
+ client;
15569
+ get stopped() {
15570
+ return this.stopper.signal.aborted;
15571
+ }
15572
+ stop() {
15573
+ if (this.stopped) return;
15574
+ this.stopper.abort();
15575
+ this.nudge();
15576
+ this.client?.close();
15577
+ }
15578
+ /** 세션 크기가 바뀌었다(웹 패널 크기 → 데몬 set-size) — 다시 올린다. */
15579
+ setSize(size) {
15580
+ this.size = size;
15581
+ this.refresh();
15582
+ }
15583
+ /** 다시 그려 보낸다(다시 열린 링크·목록을 올린 뒤·실행 확인 지점이 오른 뒤). */
15584
+ refresh() {
15585
+ this.dirty = true;
15586
+ this.nudge();
15587
+ }
15588
+ async run() {
15589
+ const name = this.deps.session;
15590
+ const client = await openTermClient(this.deps.paths, { start: false });
15591
+ if (!client || this.stopped) {
15592
+ client?.close();
15593
+ if (!client) this.deps.onGone("the term daemon is not running");
15594
+ return;
15595
+ }
15596
+ this.client = client;
14654
15597
  client.onEvent((event) => {
14655
15598
  if (event.event === "changed") {
14656
15599
  this.refresh();
@@ -14703,6 +15646,12 @@ var RemoteViewer = class {
14703
15646
  this.dirty = false;
14704
15647
  lastRead = Date.now();
14705
15648
  const { cols, rows } = this.size;
15649
+ const executedThrough = this.deps.executedThrough();
15650
+ if (executedThrough === void 0) {
15651
+ this.stop();
15652
+ this.deps.onChannelEnded("CHANNEL_GONE");
15653
+ return;
15654
+ }
14706
15655
  let data;
14707
15656
  try {
14708
15657
  data = await client.request({ op: "read", name, scrollback: true, lines: FRAME_SCROLLBACK_LINES + rows });
@@ -14710,17 +15659,34 @@ var RemoteViewer = class {
14710
15659
  this.daemonFailed("read", error);
14711
15660
  return;
14712
15661
  }
15662
+ const instance = sessionInstance(data);
15663
+ if (instance === void 0) {
15664
+ this.daemonFailed("read", new TermError(
15665
+ "TERM_DAEMON_OUTDATED",
15666
+ "The term daemon is older than this CLI (no session instance) \u2014 restart it with `ainecto term kill-server`."
15667
+ ));
15668
+ return;
15669
+ }
14713
15670
  const modes = readModes(data);
14714
- const head = { linkId: target.linkId, session: name, cols, rows, ...modes ? { modes } : {} };
14715
- const frame = screenFrame(readLines(data), frameBudget(target.frameMaxBytes, head));
15671
+ const outer = { linkId: target.linkId, channelId: this.deps.channelId, session: name, cols, rows };
15672
+ const sealed = { ...modes ? { modes } : {}, instance };
15673
+ const frame = screenFrame(readLines(data), frameBudget(target.frameMaxBytes, outer, sealed));
14716
15674
  if (frame.dropped !== dropped) {
14717
15675
  dropped = frame.dropped;
14718
- this.deps.log.write({ event: "remote_frame_trimmed", session: name, dropped });
15676
+ this.deps.log.write({ event: "remote_frame_trimmed", channelId: this.deps.channelId, session: name, dropped });
14719
15677
  }
14720
- const key = `${frame.hash}:${cols}x${rows}:${JSON.stringify(modes ?? null)}`;
15678
+ const key = `${frame.hash}:${cols}x${rows}:${JSON.stringify(modes ?? null)}:${instance}:${executedThrough}`;
14721
15679
  if (key === sentKey) continue;
15680
+ let box;
14722
15681
  try {
14723
- await this.deps.http.call("frame", { ...head, d: frame.d }, { signal: this.stopper.signal });
15682
+ box = await this.deps.seal({ d: frame.d, ...sealed, executedThrough });
15683
+ } catch (error) {
15684
+ this.stop();
15685
+ this.deps.onChannelEnded(error instanceof ChannelSealError ? error.reason : "CHANNEL_GONE");
15686
+ return;
15687
+ }
15688
+ try {
15689
+ await this.deps.http.call("frame", { ...outer, ...box }, { signal: this.stopper.signal });
14724
15690
  sentKey = key;
14725
15691
  attempt = 0;
14726
15692
  } catch (error) {
@@ -14732,10 +15698,13 @@ var RemoteViewer = class {
14732
15698
  }
14733
15699
  if (error instanceof PcCallError && error.status === 404 && error.code === "SESSION_NOT_FOUND") {
14734
15700
  this.deps.onUnknownSession();
14735
- } else if (!(error instanceof PcCallError) || !error.retryable) {
15701
+ } else if (error instanceof PcCallError && (error.status === 401 || error.status === 403)) {
14736
15702
  this.stop();
14737
15703
  this.deps.onRefused(error);
14738
15704
  return;
15705
+ } else if (!(error instanceof PcCallError) || !error.retryable) {
15706
+ this.stop();
15707
+ return;
14739
15708
  }
14740
15709
  await sleep(retryWait(attempt, Math.random()), this.stopper.signal);
14741
15710
  attempt += 1;
@@ -14773,8 +15742,8 @@ import { rmdir as rmdir2 } from "fs/promises";
14773
15742
  // src/core/pc/pcUpgrade.ts
14774
15743
  var STABLE = /^\d+\.\d+\.\d+$/;
14775
15744
  var NEXT = /^\d+\.\d+\.\d+-next\.\d+(\.\d+)*$/;
14776
- function releaseChannel(version, release) {
14777
- if (!release) return void 0;
15745
+ function releaseChannel(version, release2) {
15746
+ if (!release2) return void 0;
14778
15747
  if (NEXT.test(version)) return "next";
14779
15748
  if (STABLE.test(version)) return "latest";
14780
15749
  return void 0;
@@ -14807,10 +15776,10 @@ function auditPassed(exitCode2, output) {
14807
15776
  }
14808
15777
  function provenanceWorkflow(body, name, version) {
14809
15778
  const subject = `pkg:npm/${encodeURIComponent(name).replace("%2F", "/")}@${version}`;
14810
- const attestations = record2(body)?.attestations;
15779
+ const attestations = record3(body)?.attestations;
14811
15780
  if (!Array.isArray(attestations)) return void 0;
14812
15781
  for (const item of attestations) {
14813
- const payload = record2(record2(record2(item)?.bundle)?.dsseEnvelope)?.payload;
15782
+ const payload = record3(record3(record3(item)?.bundle)?.dsseEnvelope)?.payload;
14814
15783
  if (typeof payload !== "string") continue;
14815
15784
  let statement;
14816
15785
  try {
@@ -14818,11 +15787,11 @@ function provenanceWorkflow(body, name, version) {
14818
15787
  } catch {
14819
15788
  continue;
14820
15789
  }
14821
- const subjects = record2(statement)?.subject;
14822
- const forThis = Array.isArray(subjects) && subjects.some((s) => record2(s)?.name === subject);
14823
- const workflow = record2(record2(record2(record2(statement)?.predicate)?.buildDefinition)?.externalParameters)?.workflow;
14824
- const repository = record2(workflow)?.repository;
14825
- const path = record2(workflow)?.path;
15790
+ const subjects = record3(statement)?.subject;
15791
+ const forThis = Array.isArray(subjects) && subjects.some((s) => record3(s)?.name === subject);
15792
+ const workflow = record3(record3(record3(record3(statement)?.predicate)?.buildDefinition)?.externalParameters)?.workflow;
15793
+ const repository = record3(workflow)?.repository;
15794
+ const path = record3(workflow)?.path;
14826
15795
  if (forThis && typeof repository === "string" && typeof path === "string") return { repository, path };
14827
15796
  }
14828
15797
  return void 0;
@@ -14830,7 +15799,7 @@ function provenanceWorkflow(body, name, version) {
14830
15799
  function sameWorkflow(a, b) {
14831
15800
  return a.repository === b.repository && a.path === b.path;
14832
15801
  }
14833
- function record2(value) {
15802
+ function record3(value) {
14834
15803
  return value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : void 0;
14835
15804
  }
14836
15805
 
@@ -14838,6 +15807,7 @@ function record2(value) {
14838
15807
  var REMOTE_STATE_PREFIX = "Remote terminal: ";
14839
15808
  var REMOTE_OFF_BY_WEB_LINE = `${REMOTE_STATE_PREFIX}turned off from the web.`;
14840
15809
  var REMOTE_NOT_FOUND = "REMOTE_NOT_FOUND";
15810
+ var E2E_VERSION = 1;
14841
15811
  function openRemoteLog(paths) {
14842
15812
  const log = new DaemonLog(paths.remoteLog, paths.previousRemoteLog);
14843
15813
  log.enableRotation();
@@ -14864,15 +15834,17 @@ function createRemoteHttp(input) {
14864
15834
  }
14865
15835
  });
14866
15836
  }
15837
+ var viewerKey = (watch) => `${watch.channelId}\0${watch.session}`;
14867
15838
  async function runRemoteBridge(deps) {
14868
15839
  let ending;
14869
15840
  const stopper = new AbortController();
14870
15841
  const viewers = /* @__PURE__ */ new Map();
15842
+ const book = new ChannelBook(deps.pcId);
14871
15843
  const end = (outcome) => {
14872
15844
  if (ending) return;
14873
15845
  ending = outcome;
14874
15846
  stopper.abort();
14875
- for (const viewer of viewers.values()) viewer.stop();
15847
+ for (const { viewer } of viewers.values()) viewer.stop();
14876
15848
  viewers.clear();
14877
15849
  };
14878
15850
  const onUserStop = () => end({ exitCode: 0, reason: "Stopped.", close: true });
@@ -14883,16 +15855,22 @@ async function runRemoteBridge(deps) {
14883
15855
  try {
14884
15856
  const first = await currentSessions(deps);
14885
15857
  if (ending) return { exitCode: ending.exitCode, reason: ending.reason };
14886
- let link = await openLink2(deps, 1, deps.remoteEnabled, deps.remoteEnabled ? first : [], void 0);
15858
+ let link2;
15859
+ try {
15860
+ link2 = await openLink2(deps, 1, deps.remoteEnabled, deps.remoteEnabled ? first : [], void 0);
15861
+ } catch (error) {
15862
+ return { exitCode: 1, reason: refused(error).reason };
15863
+ }
14887
15864
  let remote = startState(deps.remoteEnabled);
14888
15865
  let uploaded = deps.remoteEnabled ? sessionsKey(first) : void 0;
15866
+ let watchList = [];
14889
15867
  deps.log.write({
14890
15868
  event: "remote_opened",
14891
- linkId: link.linkId,
15869
+ linkId: link2.linkId,
14892
15870
  sessions: deps.remoteEnabled ? first.length : 0,
14893
15871
  remote,
14894
- pollHoldSeconds: link.pollHoldSeconds,
14895
- frameMaxBytes: link.frameMaxBytes
15872
+ pollHoldSeconds: link2.pollHoldSeconds,
15873
+ frameMaxBytes: link2.frameMaxBytes
14896
15874
  });
14897
15875
  deps.print(deps.remoteEnabled ? `${REMOTE_STATE_PREFIX}on \u2014 ${first.length} session(s) from ${deps.hostName} are listed in AiNecto on the web.` : `${REMOTE_STATE_PREFIX}off on this PC (\`ainecto remote on\` allows it).`);
14898
15876
  let syncing = Promise.resolve();
@@ -14909,9 +15887,9 @@ async function runRemoteBridge(deps) {
14909
15887
  const key = sessionsKey(sessions);
14910
15888
  if (key === uploaded) return;
14911
15889
  try {
14912
- await deps.http.call("sessions", { linkId: link.linkId, sessions }, { signal: stopper.signal });
15890
+ await deps.http.call("sessions", { linkId: link2.linkId, sessions }, { signal: stopper.signal });
14913
15891
  uploaded = key;
14914
- for (const viewer of viewers.values()) viewer.refresh();
15892
+ for (const { viewer } of viewers.values()) viewer.refresh();
14915
15893
  } catch {
14916
15894
  }
14917
15895
  });
@@ -14928,51 +15906,93 @@ async function runRemoteBridge(deps) {
14928
15906
  daemonFailed(deps, "watch-sessions", void 0, error);
14929
15907
  }
14930
15908
  }
14931
- const viewerFor = (name, size) => {
15909
+ const stopViewers = (channelId) => {
15910
+ for (const [key, { watch, viewer }] of viewers) {
15911
+ if (watch.channelId !== channelId) continue;
15912
+ viewer.stop();
15913
+ viewers.delete(key);
15914
+ }
15915
+ };
15916
+ const refreshChannel = (channelId) => {
15917
+ for (const { watch, viewer } of viewers.values()) {
15918
+ if (watch.channelId === channelId) viewer.refresh();
15919
+ }
15920
+ };
15921
+ const closeChannel = async (channelId, reason, browser) => {
15922
+ book.drop(channelId);
15923
+ stopViewers(channelId);
15924
+ commands.forgetChannel(channelId);
15925
+ deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "pc", reason, ...browser ? { browserKeyId: browser.keyId } : {} });
15926
+ try {
15927
+ await deps.http.call("channel/close", { linkId: link2.linkId, channelId, reason }, { signal: stopper.signal });
15928
+ } catch {
15929
+ }
15930
+ };
15931
+ const closeAllChannels = async (reason) => {
15932
+ for (const channelId of book.dropAll()) {
15933
+ stopViewers(channelId);
15934
+ commands.forgetChannel(channelId);
15935
+ deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "pc", reason });
15936
+ try {
15937
+ await deps.http.call("channel/close", { linkId: link2.linkId, channelId, reason }, { signal: stopper.signal });
15938
+ } catch {
15939
+ }
15940
+ }
15941
+ };
15942
+ const viewerFor = (watch, size) => {
15943
+ const key = viewerKey(watch);
14932
15944
  const viewer = new RemoteViewer({
14933
15945
  paths: deps.paths,
14934
- session: name,
15946
+ session: watch.session,
15947
+ channelId: watch.channelId,
14935
15948
  http: deps.http,
14936
15949
  log: deps.log,
14937
- link: () => link,
15950
+ link: () => link2,
14938
15951
  size,
15952
+ seal: (body) => book.seal(watch.channelId, { kind: "frame", session: watch.session }, { ...body }),
15953
+ executedThrough: () => book.executedThrough(watch.channelId),
14939
15954
  onGone: () => {
14940
- viewers.delete(name);
15955
+ if (viewers.get(key)?.viewer === viewer) viewers.delete(key);
14941
15956
  void syncList();
14942
15957
  },
14943
15958
  onRefused: (error) => end(refused(error)),
14944
15959
  onUnknownSession: () => {
14945
15960
  uploaded = void 0;
14946
15961
  void syncList();
15962
+ },
15963
+ onChannelEnded: (reason) => {
15964
+ if (viewers.get(key)?.viewer === viewer) viewers.delete(key);
15965
+ if (reason !== "CHANNEL_GONE") void closeChannel(watch.channelId, reason);
14947
15966
  }
14948
15967
  });
14949
15968
  void viewer.run();
14950
15969
  return viewer;
14951
15970
  };
14952
- const setWatching = async (names) => {
14953
- const wanted = remote === "on" ? names : [];
15971
+ const applyWatching = async () => {
15972
+ const wanted = remote === "on" ? watchList.filter((watch) => book.isActive(watch.channelId)) : [];
15973
+ const wantedKeys = new Set(wanted.map(viewerKey));
14954
15974
  let changed = false;
14955
- for (const [name, viewer] of viewers) {
14956
- if (!wanted.includes(name)) {
15975
+ for (const [key, { viewer }] of viewers) {
15976
+ if (!wantedKeys.has(key)) {
14957
15977
  viewer.stop();
14958
- viewers.delete(name);
15978
+ viewers.delete(key);
14959
15979
  changed = true;
14960
15980
  }
14961
15981
  }
14962
- const missing = wanted.filter((name) => !viewers.has(name));
15982
+ const missing = wanted.filter((watch) => !viewers.has(viewerKey(watch)));
14963
15983
  if (missing.length > 0) {
14964
15984
  const sizes = new Map((await currentSessions(deps).catch(() => [])).map((s) => [s.name, { cols: s.cols, rows: s.rows }]));
14965
- for (const name of missing) {
14966
- const size = sizes.get(name);
14967
- if (size) {
14968
- viewers.set(name, viewerFor(name, size));
15985
+ for (const watch of missing) {
15986
+ const size = sizes.get(watch.session);
15987
+ if (size && !viewers.has(viewerKey(watch))) {
15988
+ viewers.set(viewerKey(watch), { watch, viewer: viewerFor(watch, size) });
14969
15989
  changed = true;
14970
15990
  }
14971
15991
  }
14972
15992
  }
14973
- if (changed) deps.log.write({ event: "remote_watching", sessions: [...viewers.keys()] });
15993
+ if (changed) deps.log.write({ event: "remote_watching", watching: [...viewers.values()].map(({ watch }) => watch) });
14974
15994
  };
14975
- const applyRemote = (next) => {
15995
+ const applyRemote = async (next) => {
14976
15996
  if (next === remote) return;
14977
15997
  remote = next;
14978
15998
  deps.log.write({ event: "remote_state", remote });
@@ -14981,29 +16001,70 @@ async function runRemoteBridge(deps) {
14981
16001
  void syncList();
14982
16002
  deps.print(`${REMOTE_STATE_PREFIX}on.`);
14983
16003
  } else {
14984
- for (const viewer of viewers.values()) viewer.stop();
14985
- viewers.clear();
16004
+ await closeAllChannels("REMOTE_OFF");
14986
16005
  deps.print(remote === "off-by-web" ? `${REMOTE_OFF_BY_WEB_LINE} Run \`ainecto\` (or \`ainecto remote on\`) on this PC to turn it back on.` : `${REMOTE_STATE_PREFIX}off on this PC (\`ainecto remote on\` allows it).`);
14987
16006
  }
14988
16007
  };
14989
- const commands = new CommandRunner(deps, control, viewers, () => remote);
16008
+ const onHello = async (channelId, hello) => {
16009
+ if (remote !== "on") {
16010
+ deps.log.write({ event: "remote_hello", channelId, result: "closed", reason: "REMOTE_OFF" });
16011
+ await closeChannel(channelId, "REMOTE_OFF");
16012
+ return;
16013
+ }
16014
+ const outcome2 = await book.hello(channelId, hello, await loadTrust(deps));
16015
+ switch (outcome2.type) {
16016
+ case "ignored":
16017
+ deps.log.write({ event: "remote_hello", channelId, result: "ignored" });
16018
+ return;
16019
+ case "close":
16020
+ deps.log.write({ event: "remote_hello", channelId, result: "closed", reason: outcome2.reason });
16021
+ await closeChannel(channelId, outcome2.reason);
16022
+ return;
16023
+ case "refuse":
16024
+ deps.log.write({ event: "remote_hello", channelId, result: "refused", reason: "PAIRING_REQUIRED" });
16025
+ try {
16026
+ await deps.http.call("welcome", { linkId: link2.linkId, channelId, refuse: "PAIRING_REQUIRED" }, { signal: stopper.signal });
16027
+ } catch {
16028
+ }
16029
+ return;
16030
+ case "welcome":
16031
+ deps.log.write({ event: "remote_hello", channelId, result: "welcome", browserKeyId: outcome2.browser.keyId });
16032
+ try {
16033
+ await deps.http.call("welcome", { linkId: link2.linkId, channelId, welcome: outcome2.welcome }, { signal: stopper.signal });
16034
+ } catch {
16035
+ book.drop(channelId);
16036
+ deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "local", reason: "welcome-not-delivered" });
16037
+ }
16038
+ return;
16039
+ }
16040
+ };
16041
+ const commands = new CommandRunner(deps, control, book, () => remote, () => link2.linkId, stopper.signal, {
16042
+ closeChannel,
16043
+ refreshChannel,
16044
+ resized: (session, size) => {
16045
+ for (const { watch, viewer } of viewers.values()) {
16046
+ if (watch.session === session) viewer.setSize(size);
16047
+ }
16048
+ },
16049
+ applyWatching
16050
+ });
14990
16051
  let reopens = 0;
14991
16052
  let attempt = 0;
14992
16053
  while (!ending) {
14993
16054
  let answer;
14994
16055
  try {
14995
- answer = await deps.http.call("poll", { linkId: link.linkId }, { holdMs: link.pollHoldSeconds * 1e3, signal: stopper.signal });
16056
+ answer = await deps.http.call("poll", { linkId: link2.linkId }, { holdMs: link2.pollHoldSeconds * 1e3, signal: stopper.signal });
14996
16057
  } catch (error) {
14997
16058
  if (ending) break;
14998
16059
  if (forgotten(error)) {
14999
16060
  if (reopens > 0) await sleep(retryWait(reopens - 1, Math.random()), stopper.signal);
15000
16061
  if (ending) break;
15001
16062
  reopens += 1;
15002
- const previous = link;
16063
+ const previous = link2;
15003
16064
  try {
15004
16065
  const enabled = deps.remoteEnabled && remote !== "off-by-web";
15005
16066
  const sessions = enabled ? await currentSessions(deps) : [];
15006
- link = await openLink2(deps, previous.generation + 1, enabled, sessions, stopper.signal);
16067
+ link2 = await openLink2(deps, previous.generation + 1, enabled, sessions, stopper.signal);
15007
16068
  if (enabled) remote = "on";
15008
16069
  uploaded = enabled ? sessionsKey(sessions) : void 0;
15009
16070
  } catch (reopenError) {
@@ -15012,9 +16073,20 @@ async function runRemoteBridge(deps) {
15012
16073
  end(refused(reopenError));
15013
16074
  break;
15014
16075
  }
15015
- deps.log.write({ event: "remote_reopened", reason: REMOTE_NOT_FOUND, previousLinkId: previous.linkId, linkId: link.linkId });
16076
+ const dropped = book.dropAll();
16077
+ for (const channelId of dropped) {
16078
+ stopViewers(channelId);
16079
+ commands.forgetChannel(channelId);
16080
+ }
16081
+ watchList = [];
16082
+ deps.log.write({
16083
+ event: "remote_reopened",
16084
+ reason: REMOTE_NOT_FOUND,
16085
+ previousLinkId: previous.linkId,
16086
+ linkId: link2.linkId,
16087
+ channelsDropped: dropped.length
16088
+ });
15016
16089
  deps.print("AiNecto lost the remote terminal (it may have restarted); opened it again.");
15017
- for (const viewer of viewers.values()) viewer.refresh();
15018
16090
  continue;
15019
16091
  }
15020
16092
  if (!(error instanceof PcCallError) || !error.retryable) {
@@ -15036,17 +16108,45 @@ async function runRemoteBridge(deps) {
15036
16108
  break;
15037
16109
  }
15038
16110
  const state = remoteStateOf(answer.remote);
15039
- if (state) applyRemote(state);
15040
- await setWatching(watchingOf(answer));
15041
- deps.onAnswer?.({ tags: cliTagsOf(answer.cli), watching: watchingOf(answer).length });
15042
- await commands.run(remoteCommands(answer), { linkId: () => link.linkId, syncList, stopSignal: stopper.signal });
16111
+ if (state) await applyRemote(state);
16112
+ for (const channelId of book.expired()) {
16113
+ await closeChannel(channelId, "HANDSHAKE_EXPIRED");
16114
+ }
16115
+ for (const item of pollItems(answer)) {
16116
+ if (ending) break;
16117
+ switch (item.type) {
16118
+ case "hello":
16119
+ await onHello(item.channelId, item.hello);
16120
+ break;
16121
+ case "cmd":
16122
+ await commands.run(item.command);
16123
+ break;
16124
+ case "bad-cmd":
16125
+ deps.log.write({ event: "remote_command_skipped", channelId: item.channelId, n: item.n, why: "malformed" });
16126
+ if (book.has(item.channelId)) await closeChannel(item.channelId, "DECRYPT_FAILED");
16127
+ break;
16128
+ case "watch":
16129
+ watchList = item.channels;
16130
+ break;
16131
+ case "channel-closed":
16132
+ if (book.drop(item.channelId)) {
16133
+ deps.log.write({ event: "remote_channel", channelId: item.channelId, state: "closed", by: "web" });
16134
+ }
16135
+ stopViewers(item.channelId);
16136
+ commands.forgetChannel(item.channelId);
16137
+ break;
16138
+ }
16139
+ }
16140
+ await applyWatching();
16141
+ deps.onAnswer?.({ tags: cliTagsOf(answer.cli), watching: viewers.size });
15043
16142
  await syncList();
15044
16143
  }
15045
16144
  const outcome = ending ?? { exitCode: 1, reason: "The remote terminal stopped.", close: true };
15046
16145
  await syncing;
16146
+ await deps.notifier.flush();
15047
16147
  if (outcome.close) {
15048
16148
  try {
15049
- await deps.http.call("close", { linkId: link.linkId });
16149
+ await deps.http.call("close", { linkId: link2.linkId });
15050
16150
  } catch (error) {
15051
16151
  deps.print(`Could not tell AiNecto that the remote terminal stopped: ${error instanceof Error ? error.message : String(error)}`);
15052
16152
  }
@@ -15054,7 +16154,7 @@ async function runRemoteBridge(deps) {
15054
16154
  return { exitCode: outcome.exitCode, reason: outcome.reason };
15055
16155
  } finally {
15056
16156
  stopper.abort();
15057
- for (const viewer of viewers.values()) viewer.stop();
16157
+ for (const { viewer } of viewers.values()) viewer.stop();
15058
16158
  deps.signal.removeEventListener("abort", onUserStop);
15059
16159
  listWatch?.close();
15060
16160
  control.close();
@@ -15069,7 +16169,8 @@ async function openLink2(deps, generation, remoteEnabled, sessions, signal) {
15069
16169
  hostName: deps.hostName,
15070
16170
  cliVersion: deps.cliVersion,
15071
16171
  remoteEnabled,
15072
- sessions
16172
+ sessions,
16173
+ e2e: E2E_VERSION
15073
16174
  }, signal ? { signal } : void 0);
15074
16175
  const limits = serverLimits2(opened.limits);
15075
16176
  if (typeof opened.linkId !== "string" || typeof opened.linkToken !== "string" || !limits) {
@@ -15082,19 +16183,37 @@ async function currentSessions(deps) {
15082
16183
  const result = await termRequest(deps.paths, { op: "ls" }, { start: false });
15083
16184
  return wireSessions(listedSessions(result.daemon ? result.data : void 0), deps.exclude);
15084
16185
  }
16186
+ async function loadTrust(deps) {
16187
+ if (!deps.trust) return void 0;
16188
+ try {
16189
+ const account2 = (await loadPcKeys(deps.trust.keysPath)).accounts[deps.trust.accountKey];
16190
+ return account2 ? { userId: transcriptUserId(deps.trust.userId), pcKey: account2.pcKey, browsers: account2.browsers } : void 0;
16191
+ } catch (error) {
16192
+ deps.log.write({ event: "remote_trust_error", code: errorCode2(error) });
16193
+ return void 0;
16194
+ }
16195
+ }
15085
16196
  function refused(error) {
16197
+ if (error instanceof PcCallError && error.op === "open" && error.status === 400 && error.code === "INVALID") {
16198
+ return { exitCode: 1, reason: "AiNecto's server is not on the new version yet \u2014 run `ainecto start` again in a few minutes.", close: false };
16199
+ }
15086
16200
  const what = error instanceof PcCallError ? `${error.op}: ${error.status ?? "-"} ${error.code ?? ""} ${error.message}`.replace(/\s+/g, " ") : error instanceof Error ? error.message : String(error);
15087
16201
  return { exitCode: 1, reason: `AiNecto refused the remote terminal (${what}).`, close: true };
15088
16202
  }
15089
16203
  function forgotten(error) {
15090
16204
  return error instanceof PcCallError && error.status === 404 && error.code === REMOTE_NOT_FOUND;
15091
16205
  }
16206
+ function errorCode2(error) {
16207
+ if (error instanceof TermError) return error.code;
16208
+ if (error && typeof error === "object" && "code" in error && typeof error.code === "string") return error.code;
16209
+ return "UNKNOWN";
16210
+ }
15092
16211
  function daemonFailed(deps, op, session, error) {
15093
16212
  deps.log.write({
15094
16213
  event: "remote_daemon_error",
15095
16214
  op,
15096
16215
  ...session ? { session } : {},
15097
- code: error instanceof TermError ? error.code : "UNKNOWN",
16216
+ code: errorCode2(error),
15098
16217
  message: error instanceof Error ? error.message : String(error)
15099
16218
  });
15100
16219
  }
@@ -15121,114 +16240,188 @@ var DaemonControl = class {
15121
16240
  }
15122
16241
  };
15123
16242
  var CommandRunner = class {
15124
- constructor(deps, control, viewers, remote) {
16243
+ constructor(deps, control, book, remote, linkId, stopSignal, hooks) {
15125
16244
  this.deps = deps;
15126
16245
  this.control = control;
15127
- this.viewers = viewers;
16246
+ this.book = book;
15128
16247
  this.remote = remote;
16248
+ this.linkId = linkId;
16249
+ this.stopSignal = stopSignal;
16250
+ this.hooks = hooks;
15129
16251
  }
15130
16252
  deps;
15131
16253
  control;
15132
- viewers;
16254
+ book;
15133
16255
  remote;
15134
- /** 여러 바이트 글자가 poll 경계에서 갈려도 잇는다 — 세션마다(바이트는 그대로, 글자로 바꾸는 곳만 한 곳). */
16256
+ linkId;
16257
+ stopSignal;
16258
+ hooks;
16259
+ /** 여러 바이트 글자가 메시지 경계에서 갈려도 잇는다 — (채널, 세션)마다(바이트는 그대로, 글자로 바꾸는 곳만 한 곳). */
15135
16260
  decoders = /* @__PURE__ */ new Map();
15136
- /**
15137
- * 웹이 폴더를 비운 만들기 — {@link webSessionFolder}(꼬리표가 있으면 프로젝트 아래)를 만든다. requestId 는 서버가 만들기마다 새로
15138
- * 뽑는 UUID 라 세션마다 새 폴더가 되고, remote_command 로그 줄(같은 requestId)로 어느 만들기의 폴더인지 잇는다.
15139
- */
15140
- async sessionFolder(projectUuid, requestId) {
15141
- const folder = webSessionFolder(this.deps.appHome, projectUuid, requestId);
15142
- const made = !existsSync(folder);
15143
- await ensurePrivateDir(folder);
15144
- return { folder, made };
16261
+ forgetChannel(channelId) {
16262
+ for (const key of this.decoders.keys()) {
16263
+ if (key.startsWith(`${channelId}\0`)) this.decoders.delete(key);
16264
+ }
15145
16265
  }
15146
- /** 거절된 만들기 — 방금 만든 세션 폴더를 비어 있을 때만 지운다(rmdir, 재귀 아님). 못 지우면 한 줄 남기고 넘어간다. */
15147
- async dropSessionFolder(requestId, folder) {
15148
- try {
15149
- await rmdir2(folder);
15150
- } catch (error) {
15151
- this.deps.log.write({
15152
- event: "remote_session_folder_kept",
15153
- requestId,
15154
- folder,
15155
- code: error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : "UNKNOWN",
15156
- message: error instanceof Error ? error.message : String(error)
16266
+ /** cmd 하나 — 목록 올리기는 poll 한 바퀴 끝에 다리가 한다(바뀐 때만 올라간다). */
16267
+ async run(wire) {
16268
+ const outcome = await this.book.receive(wire);
16269
+ switch (outcome.type) {
16270
+ case "unknown":
16271
+ this.deps.log.write({ event: "remote_command_skipped", channelId: wire.channelId, n: wire.n, why: "unknown-channel" });
16272
+ return;
16273
+ case "duplicate":
16274
+ this.deps.log.write({ event: "remote_command_skipped", channelId: wire.channelId, n: wire.n, why: "duplicate" });
16275
+ return;
16276
+ case "close":
16277
+ await this.hooks.closeChannel(wire.channelId, outcome.reason);
16278
+ return;
16279
+ case "confirmed":
16280
+ this.deps.log.write({ event: "remote_channel", channelId: wire.channelId, state: "active", browserKeyId: outcome.browser.keyId });
16281
+ void this.deps.notifier.notify({ kind: "session", keyId: outcome.browser.keyId, browserName: outcome.browser.name });
16282
+ await this.hooks.applyWatching();
16283
+ return;
16284
+ case "command":
16285
+ await this.execute(wire, outcome.command, outcome.browser);
16286
+ return;
16287
+ }
16288
+ }
16289
+ async execute(wire, command, browser) {
16290
+ const session = command.kind === "create" ? command.name : command.session;
16291
+ const opId = "opId" in command ? command.opId : void 0;
16292
+ this.deps.log.write({
16293
+ event: "remote_command",
16294
+ type: command.kind,
16295
+ channelId: wire.channelId,
16296
+ n: wire.n,
16297
+ session,
16298
+ ...opId ? { opId } : {},
16299
+ ...wire.requestId ? { requestId: wire.requestId } : {},
16300
+ ...command.kind === "input" ? { bytes: command.bytes.length } : {}
16301
+ });
16302
+ let failure2;
16303
+ let applied = {};
16304
+ if (this.remote() !== "on") {
16305
+ failure2 = { code: "REMOTE_OFF", message: "Terminals from the web are turned off on this PC." };
16306
+ } else if (this.deps.exclude.includes(session)) {
16307
+ failure2 = { code: "TERM_NO_SESSION", message: `No session named "${session}".` };
16308
+ } else {
16309
+ try {
16310
+ applied = await this.apply(wire.channelId, command);
16311
+ } catch (error) {
16312
+ failure2 = { code: errorCode2(error), message: error instanceof Error ? error.message : String(error) };
16313
+ this.deps.log.write({ event: "remote_daemon_error", op: command.kind, session, code: failure2.code });
16314
+ }
16315
+ }
16316
+ const crud = command.kind === "create" || command.kind === "kill" || command.kind === "label";
16317
+ if (!crud && failure2) {
16318
+ this.logResult(wire, command.kind, session, false, failure2.code);
16319
+ await this.hooks.closeChannel(wire.channelId, failure2.code === "SESSION_REPLACED" ? "SESSION_REPLACED" : failure2.code === "REMOTE_OFF" ? "REMOTE_OFF" : "COMMAND_FAILED", browser);
16320
+ return;
16321
+ }
16322
+ if (command.kind === "create" && !failure2) {
16323
+ void this.deps.notifier.notify({
16324
+ kind: command.command !== void 0 && command.command.trim() !== "" ? "command" : "shell",
16325
+ keyId: browser.keyId,
16326
+ browserName: browser.name
15157
16327
  });
15158
16328
  }
16329
+ if (crud && !await this.answer(wire, command, applied, failure2)) return;
16330
+ const raised = this.book.executed(wire.channelId, wire.n);
16331
+ this.logResult(wire, command.kind, session, failure2 === void 0, failure2?.code, raised ? wire.n : void 0);
16332
+ if (raised) this.hooks.refreshChannel(wire.channelId);
15159
16333
  }
15160
- async run(commands, ctx) {
15161
- let listChanged = false;
15162
- for (const command of commands) {
15163
- const session = "session" in command ? command.session : command.type === "create" ? command.name : void 0;
15164
- const requestId = "requestId" in command ? command.requestId : void 0;
15165
- this.deps.log.write({
15166
- event: "remote_command",
15167
- type: command.type,
15168
- ...session ? { session } : {},
15169
- ...requestId ? { requestId } : {},
15170
- ...command.type === "input" ? { bytes: Buffer.byteLength(command.d, "base64") } : {}
15171
- });
15172
- let failure2;
15173
- if (this.remote() !== "on") {
15174
- failure2 = { code: "REMOTE_OFF", message: "Terminals from the web are turned off on this PC." };
15175
- } else if (session !== void 0 && this.deps.exclude.includes(session)) {
15176
- failure2 = { code: "TERM_NO_SESSION", message: `No session named "${session}".` };
15177
- } else {
15178
- try {
15179
- listChanged = await this.apply(command) || listChanged;
15180
- } catch (error) {
15181
- failure2 = { code: error instanceof TermError ? error.code : "UNKNOWN", message: error instanceof Error ? error.message : String(error) };
15182
- daemonFailed(this.deps, command.type, session, error);
15183
- }
15184
- }
15185
- this.deps.log.write({
15186
- event: "remote_command_result",
15187
- type: command.type,
15188
- ...session ? { session } : {},
15189
- ...requestId ? { requestId } : {},
16334
+ /** CRUD 답 — 봉인 본문 {opId, kind, session?, instance?, ok, detail?} · 바깥 code 는 허용 목록만(A7). 봉인을 못 하면 채널을 닫고 false. */
16335
+ async answer(wire, command, applied, failure2) {
16336
+ const session = command.kind === "create" ? command.name : command.session;
16337
+ const projectUuid = command.kind === "create" ? command.projectUuid : void 0;
16338
+ let box;
16339
+ try {
16340
+ box = await this.book.seal(wire.channelId, { kind: "answer", session, opId: command.opId, ...projectUuid ? { projectUuid } : {} }, {
16341
+ opId: command.opId,
16342
+ kind: command.kind,
16343
+ session,
16344
+ ...applied.instance ? { instance: applied.instance } : {},
15190
16345
  ok: failure2 === void 0,
15191
- ...failure2 ? { code: failure2.code } : {}
16346
+ ...failure2 ? { detail: `${failure2.code}: ${failure2.message}` } : {}
15192
16347
  });
15193
- if (requestId) {
15194
- try {
15195
- await this.deps.http.call(
15196
- "answer",
15197
- { linkId: ctx.linkId(), requestId, ok: failure2 === void 0, ...failure2 ?? {} },
15198
- { signal: ctx.stopSignal }
15199
- );
15200
- } catch {
15201
- }
15202
- }
16348
+ } catch (error) {
16349
+ const reason = error instanceof ChannelSealError && error.reason !== "CHANNEL_GONE" ? error.reason : "COMMAND_FAILED";
16350
+ this.logResult(wire, command.kind, session, false, failure2?.code ?? reason);
16351
+ await this.hooks.closeChannel(wire.channelId, reason);
16352
+ return false;
16353
+ }
16354
+ if (!wire.requestId) return true;
16355
+ try {
16356
+ await this.deps.http.call("answer", {
16357
+ linkId: this.linkId(),
16358
+ requestId: wire.requestId,
16359
+ channelId: wire.channelId,
16360
+ ...box,
16361
+ ok: failure2 === void 0,
16362
+ ...failure2 ? { code: answerCodeOf(failure2.code) } : {}
16363
+ }, { signal: this.stopSignal });
16364
+ } catch {
15203
16365
  }
15204
- if (listChanged) await ctx.syncList();
16366
+ return true;
16367
+ }
16368
+ logResult(wire, type, session, ok, code, executedThrough) {
16369
+ this.deps.log.write({
16370
+ event: "remote_command_result",
16371
+ type,
16372
+ channelId: wire.channelId,
16373
+ n: wire.n,
16374
+ session,
16375
+ ...wire.requestId ? { requestId: wire.requestId } : {},
16376
+ ok,
16377
+ ...code ? { code } : {},
16378
+ ...executedThrough !== void 0 ? { executedThrough } : {}
16379
+ });
15205
16380
  }
15206
- /** 명령 하나를 데몬에 — 목록이 바뀌었으면 true. */
15207
- async apply(command) {
15208
- switch (command.type) {
16381
+ /**
16382
+ * 명령 하나를 데몬에 — ★세션을 겨누는 명령은 인스턴스를 싣는다. 비교는 데몬이 적용하는 자리에서(§14-6 4 — 여기서 미리 보지 않는다).
16383
+ * 데몬 응답에 인스턴스가 없으면 옛 데몬이다(검사를 하지 않았다) — 실패로 친다.
16384
+ */
16385
+ async apply(channelId, command) {
16386
+ switch (command.kind) {
15209
16387
  case "input": {
15210
- let decoder = this.decoders.get(command.session);
16388
+ const key = `${channelId}\0${command.session}`;
16389
+ let decoder = this.decoders.get(key);
15211
16390
  if (!decoder) {
15212
16391
  decoder = new StringDecoder("utf8");
15213
- this.decoders.set(command.session, decoder);
16392
+ this.decoders.set(key, decoder);
15214
16393
  }
15215
- const text2 = decoder.write(Buffer.from(command.d, "base64"));
15216
- if (text2 !== "") await this.control.request({ op: "send", name: command.session, text: text2, paste: false });
15217
- return false;
16394
+ const text2 = decoder.write(command.bytes);
16395
+ if (text2 === "") return {};
16396
+ return { ...checked(await this.control.request({
16397
+ op: "send",
16398
+ name: command.session,
16399
+ text: text2,
16400
+ paste: false,
16401
+ instance: command.instance
16402
+ })) };
15218
16403
  }
15219
16404
  case "key":
15220
- await this.control.request({ op: "key", name: command.session, key: command.key });
15221
- return false;
16405
+ return { ...checked(await this.control.request({
16406
+ op: "key",
16407
+ name: command.session,
16408
+ key: command.key,
16409
+ instance: command.instance
16410
+ })) };
15222
16411
  case "resize": {
15223
- const result = await termRequest(
15224
- this.deps.paths,
15225
- { op: "set-size", name: command.session, cols: command.cols, rows: command.rows },
15226
- { start: false }
15227
- );
15228
- const applied = result.daemon ? appliedSize(result.data) : void 0;
16412
+ const result = await termRequest(this.deps.paths, {
16413
+ op: "set-size",
16414
+ name: command.session,
16415
+ cols: command.cols,
16416
+ rows: command.rows,
16417
+ instance: command.instance
16418
+ }, { start: false });
16419
+ if (!result.daemon) throw new TermError("TERM_DAEMON_GONE", "No term daemon is running.");
16420
+ const applied = appliedSize(result.data);
15229
16421
  if (!applied) throw new TermError("TERM_BAD_RESPONSE", "The term daemon answered set-size without cols and rows.");
15230
- this.viewers.get(command.session)?.setSize(applied);
15231
- return true;
16422
+ const instance = checked(result.data);
16423
+ this.hooks.resized(command.session, applied);
16424
+ return instance;
15232
16425
  }
15233
16426
  case "create": {
15234
16427
  const project = command.projectUuid;
@@ -15238,7 +16431,7 @@ var CommandRunner = class {
15238
16431
  let cwd = command.cwd;
15239
16432
  let made;
15240
16433
  if (cwd === void 0) {
15241
- const fresh = await this.sessionFolder(project, command.requestId);
16434
+ const fresh = await this.sessionFolder(project, command.opId);
15242
16435
  cwd = fresh.folder;
15243
16436
  if (fresh.made) made = fresh.folder;
15244
16437
  }
@@ -15253,26 +16446,62 @@ var CommandRunner = class {
15253
16446
  ...project !== void 0 ? { project } : {}
15254
16447
  });
15255
16448
  } catch (error) {
15256
- if (made) await this.dropSessionFolder(command.requestId, made);
16449
+ if (made) await this.dropSessionFolder(command.opId, made);
15257
16450
  throw error;
15258
16451
  }
15259
16452
  if (project !== void 0 && createdProject(created) !== project) {
15260
- this.deps.log.write({ event: "remote_create_project_dropped", requestId: command.requestId, session: command.name });
16453
+ this.deps.log.write({ event: "remote_create_project_dropped", opId: command.opId, session: command.name });
15261
16454
  }
15262
- return true;
16455
+ const instance = sessionInstance(created);
16456
+ return instance ? { instance } : {};
16457
+ }
16458
+ case "kill": {
16459
+ const instance = checked(await this.control.request({ op: "kill", name: command.session, instance: command.instance }));
16460
+ this.forgetSession(command.session);
16461
+ return instance;
15263
16462
  }
15264
- case "kill":
15265
- await this.control.request({ op: "kill", name: command.session });
15266
- this.decoders.delete(command.session);
15267
- return true;
15268
16463
  case "label": {
15269
- const result = await termRequest(this.deps.paths, { op: "label", name: command.session, label: command.label }, { start: false });
16464
+ const result = await termRequest(
16465
+ this.deps.paths,
16466
+ { op: "label", name: command.session, label: command.label, instance: command.instance },
16467
+ { start: false }
16468
+ );
15270
16469
  if (!result.daemon) throw new TermError("TERM_DAEMON_GONE", "No term daemon is running.");
15271
- return true;
16470
+ return checked(result.data);
15272
16471
  }
15273
16472
  }
15274
16473
  }
16474
+ forgetSession(session) {
16475
+ for (const key of this.decoders.keys()) {
16476
+ if (key.endsWith(`\0${session}`)) this.decoders.delete(key);
16477
+ }
16478
+ }
16479
+ /**
16480
+ * 웹이 폴더를 비운 만들기 — {@link webSessionFolder}(꼬리표가 있으면 프로젝트 아래)를 만든다. 폴더 이름은 브라우저가 봉인 전에 정한
16481
+ * 연산 ID(UUID — 만들기마다 새 값, §12-2)라 세션마다 새 폴더가 되고, remote_command 로그 줄(같은 opId)로 어느 만들기의 폴더인지 잇는다.
16482
+ */
16483
+ async sessionFolder(projectUuid, opId) {
16484
+ const folder = webSessionFolder(this.deps.appHome, projectUuid, opId);
16485
+ const made = !existsSync(folder);
16486
+ await ensurePrivateDir(folder);
16487
+ return { folder, made };
16488
+ }
16489
+ /** 거절된 만들기 — 방금 만든 세션 폴더를 비어 있을 때만 지운다(rmdir, 재귀 아님). 못 지우면 한 줄 남기고 넘어간다. */
16490
+ async dropSessionFolder(opId, folder) {
16491
+ try {
16492
+ await rmdir2(folder);
16493
+ } catch (error) {
16494
+ this.deps.log.write({ event: "remote_session_folder_kept", opId, code: errorCode2(error) });
16495
+ }
16496
+ }
15275
16497
  };
16498
+ function checked(data) {
16499
+ const instance = sessionInstance(data);
16500
+ if (!instance) {
16501
+ throw new TermError("TERM_DAEMON_OUTDATED", "The term daemon is older than this CLI (no session instance) \u2014 restart it with `ainecto term kill-server`.");
16502
+ }
16503
+ return { instance };
16504
+ }
15276
16505
  function answerSummary(body) {
15277
16506
  return {
15278
16507
  ...typeof body.state === "string" ? { state: body.state } : {},
@@ -15294,62 +16523,33 @@ function serverLimits2(value) {
15294
16523
  function remoteStateOf(value) {
15295
16524
  return value === "on" || value === "off-by-pc" || value === "off-by-web" ? value : void 0;
15296
16525
  }
15297
- function watchingOf(answer) {
15298
- return Array.isArray(answer.watching) ? answer.watching.filter((name) => typeof name === "string" && name !== "") : [];
15299
- }
15300
- function remoteCommands(answer) {
16526
+ function pollItems(answer) {
15301
16527
  if (!Array.isArray(answer.commands)) return [];
15302
16528
  return answer.commands.flatMap((raw) => {
15303
16529
  if (!raw || typeof raw !== "object") return [];
15304
- const c = new Map(Object.entries(raw));
15305
- const session = text(c.get("session"));
15306
- const requestId = text(c.get("requestId"));
15307
- switch (c.get("type")) {
15308
- case "input": {
15309
- const d = c.get("d");
15310
- return session && typeof d === "string" ? [{ type: "input", session, d }] : [];
15311
- }
15312
- case "key": {
15313
- const key = text(c.get("key"));
15314
- return session && key ? [{ type: "key", session, key }] : [];
15315
- }
15316
- case "resize": {
15317
- const cols = c.get("cols");
15318
- const rows = c.get("rows");
15319
- return session && isSize(cols) && isSize(rows) ? [{ type: "resize", session, cols, rows }] : [];
15320
- }
15321
- case "create": {
15322
- const name = text(c.get("name"));
15323
- const projectUuid = text(c.get("projectUuid"));
15324
- const cwd = text(c.get("cwd"));
15325
- const command = c.get("command");
15326
- if (!requestId || !name) return [];
15327
- return [{
15328
- type: "create",
15329
- requestId,
15330
- name,
15331
- ...projectUuid ? { projectUuid } : {},
15332
- ...cwd ? { cwd } : {},
15333
- ...typeof command === "string" ? { command } : {}
15334
- }];
15335
- }
15336
- case "kill":
15337
- return requestId && session ? [{ type: "kill", requestId, session }] : [];
15338
- case "label": {
15339
- const label = text(c.get("label"));
15340
- return requestId && session && label ? [{ type: "label", requestId, session, label }] : [];
16530
+ const item = raw;
16531
+ const channelId = typeof item.channelId === "string" && item.channelId !== "" ? item.channelId : void 0;
16532
+ switch (item.type) {
16533
+ case "hello":
16534
+ return channelId ? [{ type: "hello", channelId, hello: item.hello }] : [];
16535
+ case "cmd": {
16536
+ const command = wireCommand(item);
16537
+ if (command) return [{ type: "cmd", command }];
16538
+ return channelId ? [{ type: "bad-cmd", channelId, n: typeof item.n === "number" ? item.n : -1 }] : [];
15341
16539
  }
16540
+ case "watch":
16541
+ return [{ type: "watch", channels: Array.isArray(item.channels) ? item.channels.flatMap((entry) => {
16542
+ if (!entry || typeof entry !== "object") return [];
16543
+ const watch = entry;
16544
+ return typeof watch.channelId === "string" && watch.channelId !== "" && typeof watch.session === "string" && watch.session !== "" ? [{ channelId: watch.channelId, session: watch.session }] : [];
16545
+ }) : [] }];
16546
+ case "channel-closed":
16547
+ return channelId ? [{ type: "channel-closed", channelId }] : [];
15342
16548
  default:
15343
16549
  return [];
15344
16550
  }
15345
16551
  });
15346
16552
  }
15347
- function text(value) {
15348
- return typeof value === "string" && value !== "" ? value : void 0;
15349
- }
15350
- function isSize(value) {
15351
- return typeof value === "number" && Number.isInteger(value) && value >= 1;
15352
- }
15353
16553
 
15354
16554
  // src/core/pc/pcSession.ts
15355
16555
  var PC_SESSION_NAME = "ainecto-pc";
@@ -15455,7 +16655,7 @@ function pcOutcome(lines) {
15455
16655
  }
15456
16656
 
15457
16657
  // src/adapters/cli/pcCommand.ts
15458
- import { readFile as readFile11 } from "fs/promises";
16658
+ import { readFile as readFile13 } from "fs/promises";
15459
16659
 
15460
16660
  // src/adapters/cli/pcStartText.ts
15461
16661
  var DOCTOR_ONLY = /* @__PURE__ */ new Set(["AiNecto job title"]);
@@ -15633,7 +16833,7 @@ function reportOutcome(deps, outcome) {
15633
16833
  async function lastLogLineSince(path, since) {
15634
16834
  let text2;
15635
16835
  try {
15636
- text2 = await readFile11(path, "utf8");
16836
+ text2 = await readFile13(path, "utf8");
15637
16837
  } catch (error) {
15638
16838
  if (isNodeError(error, "ENOENT")) return void 0;
15639
16839
  throw error;
@@ -15664,6 +16864,15 @@ async function executePcStop(deps, argv) {
15664
16864
  if (forget) {
15665
16865
  await savePcSettings(deps.settingsPath, withoutEndpoint(await loadPcSettings(deps.settingsPath, deps.hostName), deps.endpoint));
15666
16866
  lines.push(`Removed your approval for ${deps.endpoint} on this PC; \`ainecto\` asks again next time.`);
16867
+ let removedKeys = false;
16868
+ await updatePcKeys(deps.keysPath, (keys) => {
16869
+ const kept = withoutEndpointKeys(keys, deps.endpoint);
16870
+ removedKeys = Object.keys(kept.accounts).length !== Object.keys(keys.accounts).length;
16871
+ return removedKeys ? kept : void 0;
16872
+ });
16873
+ if (removedKeys) {
16874
+ lines.push("Also removed this PC's terminal key and paired browsers for that server \u2014 pair again with `ainecto pair`.");
16875
+ }
15667
16876
  }
15668
16877
  return print2(deps, { stopped: running.map((pc) => pc.session), forgot: forget }, lines.join("\n"));
15669
16878
  }
@@ -15694,6 +16903,46 @@ async function executeRemoteSetting(deps, argv) {
15694
16903
  }
15695
16904
  return await launchPc(deps);
15696
16905
  }
16906
+ async function runningPcGroups(deps) {
16907
+ assertQueryable(deps);
16908
+ const groups = [];
16909
+ for (const session of (await listedToTurnOff(deps)).filter((item) => runningPcs([item]).length > 0)) {
16910
+ const pgid = await processGroupOf(session.pid);
16911
+ if (pgid === void 0) {
16912
+ throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not read the process group of the PC connection (session ${session.name}, pid ${session.pid}), so its end cannot be confirmed.${processGroupUnavailableHint()}`);
16913
+ }
16914
+ groups.push({ session: session.name, pid: session.pid, pgid });
16915
+ }
16916
+ return groups;
16917
+ }
16918
+ async function turnOffPcs(deps, groups) {
16919
+ assertQueryable(deps);
16920
+ for (const group of groups) {
16921
+ const session = (await listedToTurnOff(deps)).find((item) => item.name === group.session && item.pid === group.pid);
16922
+ const [pc] = session ? runningPcs([session]) : [];
16923
+ if (pc) await stopPc(deps, pc);
16924
+ await confirmEnded(deps, group);
16925
+ }
16926
+ }
16927
+ function assertQueryable(deps) {
16928
+ if (deps.termProblem !== void 0) {
16929
+ throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not check the PC connection (ainecto term: ${deps.termProblem}).`);
16930
+ }
16931
+ }
16932
+ var STOP_CONFIRM_POLL_MS = 100;
16933
+ async function confirmEnded(deps, group) {
16934
+ const deadline = Date.now() + deps.stopDeadlineMs;
16935
+ for (; ; ) {
16936
+ const stillListed = (await listedToTurnOff(deps)).some((session) => session.name === group.session && session.pid === group.pid);
16937
+ const alive = processGroupAlive(group.pgid);
16938
+ if (!stillListed && !alive) return;
16939
+ if (Date.now() >= deadline) {
16940
+ const what = stillListed ? "the session is still running" : `a process in its group ${group.pgid} is still alive`;
16941
+ throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not confirm that the PC connection (session ${group.session}, pid ${group.pid}) ended within ${deps.stopDeadlineMs / 1e3} s (${what}). See ${deps.agentLog}.`);
16942
+ }
16943
+ await new Promise((resolve4) => setTimeout(resolve4, STOP_CONFIRM_POLL_MS));
16944
+ }
16945
+ }
15697
16946
  async function stopPc(deps, pc) {
15698
16947
  const client = await openTermClient(deps.paths, { start: false });
15699
16948
  if (!client) {
@@ -15754,10 +17003,13 @@ async function prepare(deps) {
15754
17003
  throw new CliCommandError("PC_PREPARE_FAILED", `\`${[command, ...args].join(" ")}\` failed${result.missing ? ` (${command} is not on PATH)` : ""}: ${lastLine(result.stderr) ?? lastLine(result.stdout) ?? `exit ${result.exitCode}`}`);
15755
17004
  }
15756
17005
  }
15757
- async function listed2(deps) {
15758
- const result = await termRequest(deps.paths, { op: "ls" }, { start: false });
17006
+ async function listed2(deps, connect2 = { start: false }) {
17007
+ const result = await termRequest(deps.paths, { op: "ls" }, connect2);
15759
17008
  return listedSessions(result.daemon ? result.data : void 0);
15760
17009
  }
17010
+ async function listedToTurnOff(deps) {
17011
+ return await listed2(deps, { start: false, resetFails: true });
17012
+ }
15761
17013
  function assertTerm(deps) {
15762
17014
  if (deps.termProblem !== void 0) {
15763
17015
  throw new CliCommandError("PC_UNSUPPORTED", `Connecting this PC needs ainecto term: ${deps.termProblem}`);
@@ -15776,10 +17028,455 @@ function print2(deps, data, human) {
15776
17028
  return 0;
15777
17029
  }
15778
17030
 
17031
+ // src/adapters/cli/pairCommand.ts
17032
+ import { randomUUID as randomUUID7 } from "crypto";
17033
+ import { closeSync as closeSync3, openSync as openSync3 } from "fs";
17034
+ import { ReadStream, WriteStream } from "tty";
17035
+
17036
+ // src/core/pc/pcPairing.ts
17037
+ var PAIR_WAIT_MS = 5 * 6e4;
17038
+ async function runPairing(input) {
17039
+ const deadline = new AbortController();
17040
+ const timer = setTimeout(() => deadline.abort(), input.waitMs);
17041
+ const { signal } = deadline;
17042
+ const relayed = async (step) => {
17043
+ try {
17044
+ return await step();
17045
+ } catch (error) {
17046
+ if (signal.aborted) return "timeout";
17047
+ throw error;
17048
+ }
17049
+ };
17050
+ let outcome;
17051
+ try {
17052
+ outcome = await pairOnce();
17053
+ return outcome;
17054
+ } finally {
17055
+ clearTimeout(timer);
17056
+ if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
17057
+ }
17058
+ async function pairOnce() {
17059
+ const pcPublicRaw = publicRawFromJwk(input.pcKey);
17060
+ const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
17061
+ const commit = await pairCommitment(pcPublicRaw, nP);
17062
+ input.prompt.show(`Waiting up to ${Math.round(input.waitMs / 6e4)} min for a browser \u2014 in AiNecto on the web, open Terminal, pick this PC and choose \xABPair with this PC\xBB.`);
17063
+ const offer = await relayed(() => input.transport.offer(commit, signal));
17064
+ if (offer === "timeout") return { kind: "timeout" };
17065
+ const publicJwk = publicJwkFromRaw(offer.publicRaw);
17066
+ await assertSigningPublicKey(publicJwk);
17067
+ if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
17068
+ throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 pairing aborted.");
17069
+ }
17070
+ const name = browserNameOf(offer.name);
17071
+ if (await relayed(() => input.transport.reveal(pcPublicRaw, nP, signal)) === "timeout") return { kind: "timeout" };
17072
+ const transcript = await pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
17073
+ const codes = await pairCodes(transcript);
17074
+ input.prompt.show(`A browser asked to pair: ${name}`);
17075
+ input.prompt.show(`Type this code in the browser: ${codes.a}`);
17076
+ const answer = await input.prompt.ask("Then type the code the browser shows (one try): ", signal);
17077
+ if (signal.aborted) return { kind: "timeout" };
17078
+ const typed = pairCodeInput(answer);
17079
+ if (typed.kind === "empty") return { kind: "cancelled" };
17080
+ if (typed.kind !== "code" || typed.code !== codes.b) return { kind: "code-mismatch" };
17081
+ const browser = { keyId: offer.keyId, publicJwk, name };
17082
+ await input.pin(browser);
17083
+ const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
17084
+ let doneError;
17085
+ try {
17086
+ await input.transport.done(signature, signal);
17087
+ } catch (error) {
17088
+ doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
17089
+ }
17090
+ return { kind: "paired", browser, doneError };
17091
+ }
17092
+ }
17093
+
17094
+ // src/core/pc/pcPairRelay.ts
17095
+ var PairRelayError = class extends Error {
17096
+ constructor(code, message2) {
17097
+ super(message2);
17098
+ this.code = code;
17099
+ }
17100
+ code;
17101
+ };
17102
+ function createPairRelay(input) {
17103
+ const http = createPcHttp({
17104
+ endpoint: input.endpoint,
17105
+ path: "term/pc",
17106
+ tokenProvider: input.tokenProvider,
17107
+ timeoutMs: CALL_TIMEOUT_MS,
17108
+ sessionHeader: "X-Remote-Token",
17109
+ fetchImpl: input.fetchImpl,
17110
+ logging: {
17111
+ log: input.log,
17112
+ request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
17113
+ response: ({ callId, op, ms }, outcome) => ({
17114
+ event: "remote_call_response",
17115
+ callId,
17116
+ op,
17117
+ ...outcome.ok ? {
17118
+ ok: true,
17119
+ status: outcome.status,
17120
+ ...Array.isArray(outcome.body.msgs) ? { commands: outcome.body.msgs.length } : {},
17121
+ ...outcome.body.closed === true ? { state: "CLOSED" } : {}
17122
+ } : outcome,
17123
+ ms
17124
+ })
17125
+ }
17126
+ });
17127
+ let attemptId;
17128
+ let finished = false;
17129
+ const send = async (msg, signal) => {
17130
+ if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The pairing was not opened.");
17131
+ await http.call("pair/send", { attemptId, msg }, signal ? { signal } : void 0);
17132
+ };
17133
+ return {
17134
+ async offer(commit, signal) {
17135
+ const opened = await http.call("pair/open", { pcId: input.pcId }, { signal });
17136
+ if (typeof opened.attemptId !== "string" || opened.attemptId === "") {
17137
+ throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "AiNecto answered pair/open without an attemptId.");
17138
+ }
17139
+ attemptId = opened.attemptId;
17140
+ await send({ type: "commit", commit: b64u2(commit) }, signal);
17141
+ for (; ; ) {
17142
+ const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
17143
+ if (answer.closed === true) {
17144
+ finished = true;
17145
+ throw new PairRelayError("PAIR_CLOSED", "The pairing ended on AiNecto (the browser cancelled it, or it expired).");
17146
+ }
17147
+ const offer = offerOf(Array.isArray(answer.msgs) ? answer.msgs : []);
17148
+ if (offer === "abort") {
17149
+ finished = true;
17150
+ throw new PairRelayError("PAIR_CLOSED", "The browser cancelled the pairing.");
17151
+ }
17152
+ if (offer) return offer;
17153
+ }
17154
+ },
17155
+ async reveal(pcPublicRaw, nP, signal) {
17156
+ await send({ type: "reveal", publicKey: b64u2(pcPublicRaw), nP: b64u2(nP) }, signal);
17157
+ },
17158
+ async done(signature, signal) {
17159
+ await send({ type: "done", signature: b64u2(signature) }, signal);
17160
+ finished = true;
17161
+ },
17162
+ async abort(reason) {
17163
+ if (!attemptId || finished) return;
17164
+ finished = true;
17165
+ try {
17166
+ await send({ type: "abort", reason });
17167
+ } catch {
17168
+ }
17169
+ }
17170
+ };
17171
+ }
17172
+ function offerOf(msgs) {
17173
+ if (msgs.length === 0) return void 0;
17174
+ const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
17175
+ if (items.some((item2) => item2.type === "abort")) return "abort";
17176
+ if (items.length > 1) {
17177
+ throw new PairRelayError("PAIR_DUPLICATE", "More than one pairing request arrived \u2014 this try was ended. Run `ainecto pair` again.");
17178
+ }
17179
+ const [item] = items;
17180
+ const publicRaw = fromB64u2(item?.publicKey, PUBLIC_KEY_BYTES);
17181
+ const nB = fromB64u2(item?.nB, NONCE_SEED_BYTES);
17182
+ if (item?.type !== "offer" || !publicRaw || !nB || typeof item.keyId !== "string" || typeof item.name !== "string") {
17183
+ throw new PairRelayError("PAIR_BAD_MESSAGE", "AiNecto relayed a pairing message this CLI does not understand \u2014 this try was ended.");
17184
+ }
17185
+ return { keyId: item.keyId, publicRaw, nB, name: item.name };
17186
+ }
17187
+ function b64u2(bytes) {
17188
+ return Buffer.from(bytes).toString("base64url");
17189
+ }
17190
+ function fromB64u2(value, length) {
17191
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) return void 0;
17192
+ const bytes = new Uint8Array(Buffer.from(value, "base64url"));
17193
+ return bytes.length === length ? bytes : void 0;
17194
+ }
17195
+
17196
+ // src/adapters/cli/pairCommand.ts
17197
+ var USAGE = "Usage: ainecto pair [--list | --remove <keyId|name>]";
17198
+ function openDevTty() {
17199
+ let inFd;
17200
+ try {
17201
+ inFd = openSync3("/dev/tty", "r");
17202
+ const outFd = openSync3("/dev/tty", "w");
17203
+ const stdin = new ReadStream(inFd);
17204
+ const stderr = new WriteStream(outFd);
17205
+ return { stdin, stderr, close: () => {
17206
+ stdin.destroy();
17207
+ stderr.destroy();
17208
+ } };
17209
+ } catch (error) {
17210
+ if (inFd !== void 0) closeSync3(inFd);
17211
+ throw new CliCommandError("PAIR_NO_TTY", `\`ainecto pair\` needs this PC's terminal (/dev/tty): ${error instanceof Error ? error.message : String(error)}`);
17212
+ }
17213
+ }
17214
+ async function executePair(deps, argv) {
17215
+ const [first, ...rest] = argv;
17216
+ if (first === "--list" && rest.length === 0) {
17217
+ return await listBrowsers(deps);
17218
+ }
17219
+ if (first === "--remove" && rest.length === 1 && rest[0] !== void 0 && rest[0] !== "") {
17220
+ return await removeBrowser(deps, rest[0]);
17221
+ }
17222
+ if (first !== void 0) {
17223
+ throw new CliCommandError("USAGE", USAGE);
17224
+ }
17225
+ return await pair(deps);
17226
+ }
17227
+ async function pair(deps) {
17228
+ if (deps.json || !deps.interactive) {
17229
+ throw new CliCommandError(
17230
+ "PAIR_INTERACTIVE_ONLY",
17231
+ "`ainecto pair` shows a code and asks you to type the code the browser shows \u2014 run it yourself in a terminal (not with --json or a pipe)."
17232
+ );
17233
+ }
17234
+ if (deps.insideTermSession) {
17235
+ throw new CliCommandError(
17236
+ "PAIR_IN_TERM_SESSION",
17237
+ "`ainecto pair` does not run inside an AiNecto terminal session (its screen can be shown on the web). Run it in a regular terminal on this PC."
17238
+ );
17239
+ }
17240
+ const { key, userId } = await account(deps);
17241
+ const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
17242
+ if (!settings.accounts[key]) {
17243
+ throw new CliCommandError("PC_NOT_APPROVED", "This PC is not connected yet \u2014 run `ainecto` in a terminal once to approve, then `ainecto pair`.");
17244
+ }
17245
+ const pcKey = (await loadPcKeys(deps.keysPath)).accounts[key]?.pcKey ?? await generateSigningJwk();
17246
+ const transport = await deps.transport(settings.pcId);
17247
+ const tty = deps.openTty();
17248
+ let outcome;
17249
+ try {
17250
+ outcome = await relayErrors(() => runPairing({
17251
+ userId: transcriptUserId(userId),
17252
+ pcId: settings.pcId,
17253
+ pcKey,
17254
+ transport,
17255
+ prompt: { show: (line) => {
17256
+ tty.stderr.write(`${line}
17257
+ `);
17258
+ }, ask: (question, signal) => promptLine(tty, question, signal) },
17259
+ pin: (browser2) => pin(deps, key, pcKey, browser2),
17260
+ waitMs: deps.waitMs
17261
+ }));
17262
+ } finally {
17263
+ tty.close();
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
+ // src/core/pc/pcNotify.ts
17372
+ var NOTIFY_BATCH_MS = 6e4;
17373
+ var WHAT = {
17374
+ paired: "was paired with this PC",
17375
+ session: "opened a terminal connection to this PC",
17376
+ shell: "started a new shell on this PC",
17377
+ command: "started a command in a new terminal on this PC"
17378
+ };
17379
+ function notificationText(event, more) {
17380
+ const time = `${String(event.at.getHours()).padStart(2, "0")}:${String(event.at.getMinutes()).padStart(2, "0")}`;
17381
+ return {
17382
+ title: "AiNecto",
17383
+ body: `${event.browserName} ${WHAT[event.kind]} \u2014 ${time}${more > 0 ? ` (+${more} more)` : ""}. Not you? Run \`ainecto remote off\`.`
17384
+ };
17385
+ }
17386
+ var systemClock = {
17387
+ now: () => Date.now(),
17388
+ setTimer: (run, ms) => {
17389
+ const timer = setTimeout(run, ms);
17390
+ timer.unref?.();
17391
+ return timer;
17392
+ },
17393
+ clearTimer: (timer) => clearTimeout(timer)
17394
+ };
17395
+ var NotifyBatcher = class {
17396
+ constructor(show, clock = systemClock) {
17397
+ this.show = show;
17398
+ this.clock = clock;
17399
+ }
17400
+ show;
17401
+ clock;
17402
+ slots = /* @__PURE__ */ new Map();
17403
+ add(event) {
17404
+ const key = `${event.keyId}\0${event.kind}`;
17405
+ const now = this.clock.now();
17406
+ const slot = this.slots.get(key);
17407
+ if (!slot || now >= slot.endsAt) {
17408
+ this.show(event, 0);
17409
+ this.slots.set(key, { endsAt: now + NOTIFY_BATCH_MS, pending: void 0, timer: void 0 });
17410
+ return;
17411
+ }
17412
+ slot.pending = { event, count: (slot.pending?.count ?? 0) + 1 };
17413
+ slot.timer ??= this.clock.setTimer(() => this.close(key), slot.endsAt - now);
17414
+ }
17415
+ flush() {
17416
+ for (const [key, slot] of this.slots) {
17417
+ if (slot.timer !== void 0) this.clock.clearTimer(slot.timer);
17418
+ if (slot.pending) this.show(slot.pending.event, slot.pending.count - 1);
17419
+ this.slots.delete(key);
17420
+ }
17421
+ }
17422
+ close(key) {
17423
+ const slot = this.slots.get(key);
17424
+ if (!slot) return;
17425
+ slot.timer = void 0;
17426
+ if (!slot.pending) return;
17427
+ const { event, count } = slot.pending;
17428
+ slot.pending = void 0;
17429
+ slot.endsAt = this.clock.now() + NOTIFY_BATCH_MS;
17430
+ this.show(event, count - 1);
17431
+ }
17432
+ };
17433
+ function notifyFailureReason(error) {
17434
+ if (error && typeof error === "object") {
17435
+ const value = error;
17436
+ if (value.code === "ENOENT") return "not-found";
17437
+ if (value.code === "EACCES") return "no-permission";
17438
+ if (typeof value.signal === "string" && value.signal !== "") return "signal";
17439
+ if (typeof value.code === "number") return `exit-${value.code}`;
17440
+ }
17441
+ return "failed";
17442
+ }
17443
+ function createPcNotifier(input) {
17444
+ const tool = notifyTool(input.platform);
17445
+ const run = input.run ?? runQuiet;
17446
+ const clock = input.clock ?? systemClock;
17447
+ let last = Promise.resolve();
17448
+ const show = (event, more) => {
17449
+ input.log.write({ event: "pc_notify", kind: event.kind, browserKeyId: event.keyId, more, tool: tool?.name ?? "none" });
17450
+ if (!tool) {
17451
+ input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: "none", reason: "no-tool-on-this-os" });
17452
+ last = Promise.resolve();
17453
+ return;
17454
+ }
17455
+ const { title, body } = notificationText(event, more);
17456
+ last = run(tool.file, tool.args(title, body)).then(
17457
+ () => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: true, tool: tool.name }),
17458
+ (error) => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: tool.name, reason: notifyFailureReason(error) })
17459
+ );
17460
+ };
17461
+ const batcher = new NotifyBatcher(show, clock);
17462
+ return {
17463
+ async notify(event) {
17464
+ const before = last;
17465
+ batcher.add({ ...event, at: new Date(clock.now()) });
17466
+ if (last !== before) await last;
17467
+ },
17468
+ async flush() {
17469
+ const before = last;
17470
+ batcher.flush();
17471
+ if (last !== before) await last;
17472
+ }
17473
+ };
17474
+ }
17475
+
15779
17476
  // src/adapters/cli/pcSwap.ts
15780
- import { randomUUID as randomUUID5 } from "crypto";
17477
+ import { randomUUID as randomUUID8 } from "crypto";
15781
17478
  import { writeFile as writeFile7 } from "fs/promises";
15782
- import { join as join8 } from "path";
17479
+ import { join as join9 } from "path";
15783
17480
  var Refused = class extends Error {
15784
17481
  constructor(reason, detail) {
15785
17482
  super(detail);
@@ -15853,7 +17550,7 @@ async function checkRuns(deps) {
15853
17550
  async function checkProvenance(deps) {
15854
17551
  const dir = await deps.makeTempDir();
15855
17552
  try {
15856
- await writeFile7(join8(dir, "package.json"), `${JSON.stringify({ name: "ainecto-upgrade-check", private: true })}
17553
+ await writeFile7(join9(dir, "package.json"), `${JSON.stringify({ name: "ainecto-upgrade-check", private: true })}
15857
17554
  `);
15858
17555
  const run = deps.runner(dir);
15859
17556
  const spec = `${deps.packageName}@${deps.to}`;
@@ -15879,7 +17576,7 @@ async function workflowOf(deps, run, version) {
15879
17576
  const view = await call(deps, "verify", run, "npm", ["view", `${deps.packageName}@${version}`, "dist.attestations.url"]);
15880
17577
  const url = view.exitCode === 0 ? view.stdout.trim() : "";
15881
17578
  if (url === "") return void 0;
15882
- const callId = randomUUID5();
17579
+ const callId = randomUUID8();
15883
17580
  const started = Date.now();
15884
17581
  deps.log.write({ event: "upgrade_call", callId, step: "verify", command: `GET ${url}` });
15885
17582
  let ok = false;
@@ -15897,7 +17594,7 @@ async function workflowOf(deps, run, version) {
15897
17594
  }
15898
17595
  }
15899
17596
  async function call(deps, step, run, command, args) {
15900
- const callId = randomUUID5();
17597
+ const callId = randomUUID8();
15901
17598
  const started = Date.now();
15902
17599
  deps.log.write({ event: "upgrade_call", callId, step, command: [command, ...args].join(" ") });
15903
17600
  let result = { exitCode: null, stdout: "", stderr: "no result", missing: false };
@@ -15973,24 +17670,24 @@ function swapArgsOf(argv) {
15973
17670
 
15974
17671
  // src/adapters/cli/ainectoCli.ts
15975
17672
  import { mkdtemp, rm as rm3 } from "fs/promises";
15976
- import { join as join10 } from "path";
17673
+ import { join as join11 } from "path";
15977
17674
 
15978
17675
  // src/adapters/cli/pcStatus.ts
15979
- import { readFile as readFile12 } from "fs/promises";
17676
+ import { readFile as readFile14 } from "fs/promises";
15980
17677
  import { hostname } from "os";
15981
17678
 
15982
17679
  // src/core/agent/paths.ts
15983
- import { homedir as homedir4 } from "os";
15984
- import { join as join9 } from "path";
15985
- function agentPaths(home = homedir4()) {
15986
- const dir = join9(home, ".ainecto", "agent");
17680
+ import { homedir as homedir5 } from "os";
17681
+ import { join as join10 } from "path";
17682
+ function agentPaths(home = homedir5()) {
17683
+ const dir = join10(home, ".ainecto", "agent");
15987
17684
  return {
15988
17685
  dir,
15989
- work: join9(dir, "work"),
15990
- sessions: join9(dir, "sessions.json"),
15991
- runs: join9(dir, "runs.json"),
15992
- log: join9(dir, "agent.log"),
15993
- previousLog: join9(dir, "agent.log.1")
17686
+ work: join10(dir, "work"),
17687
+ sessions: join10(dir, "sessions.json"),
17688
+ runs: join10(dir, "runs.json"),
17689
+ log: join10(dir, "agent.log"),
17690
+ previousLog: join10(dir, "agent.log.1")
15994
17691
  };
15995
17692
  }
15996
17693
 
@@ -16001,7 +17698,7 @@ async function pcStatus(status, endpoint) {
16001
17698
  const userId = status.account?.userId;
16002
17699
  const settings = await loadPcSettings(pcSettingsPath(), hostname());
16003
17700
  const agentLog = agentPaths().log;
16004
- const logText = await readFile12(agentLog, "utf8").catch((error) => {
17701
+ const logText = await readFile14(agentLog, "utf8").catch((error) => {
16005
17702
  if (isNodeError(error, "ENOENT")) return "";
16006
17703
  throw error;
16007
17704
  });
@@ -16537,10 +18234,10 @@ function codexServerRequestAnswer(method) {
16537
18234
  }
16538
18235
  }
16539
18236
  function codexAuthFromAccount(result) {
16540
- const account = result.account && typeof result.account === "object" ? result.account : void 0;
16541
- const method = typeof account?.type === "string" ? account.type : void 0;
16542
- const plan = typeof account?.planType === "string" ? account.planType : void 0;
16543
- if (account) return { ready: true, mode: method === "apiKey" ? "apiKey" : "subscription", method, plan };
18237
+ const account2 = result.account && typeof result.account === "object" ? result.account : void 0;
18238
+ const method = typeof account2?.type === "string" ? account2.type : void 0;
18239
+ const plan = typeof account2?.planType === "string" ? account2.planType : void 0;
18240
+ if (account2) return { ready: true, mode: method === "apiKey" ? "apiKey" : "subscription", method, plan };
16544
18241
  if (result.requiresOpenaiAuth === false) return { ready: true, method: "none-required" };
16545
18242
  return { ready: false, detail: "not signed in with an API key or ChatGPT (run `codex login`, or `codex login --with-api-key`)" };
16546
18243
  }
@@ -16862,7 +18559,7 @@ function toError(error) {
16862
18559
  }
16863
18560
 
16864
18561
  // src/core/agent/runs.ts
16865
- import { readFile as readFile13, rename as rename7, writeFile as writeFile8 } from "fs/promises";
18562
+ import { readFile as readFile15, rename as rename7, writeFile as writeFile8 } from "fs/promises";
16866
18563
  var AgentRunLog = class {
16867
18564
  constructor(path, log) {
16868
18565
  this.path = path;
@@ -16876,7 +18573,7 @@ var AgentRunLog = class {
16876
18573
  let reason;
16877
18574
  const runs = /* @__PURE__ */ new Map();
16878
18575
  try {
16879
- const parsed = JSON.parse(await readFile13(this.path, "utf8"));
18576
+ const parsed = JSON.parse(await readFile15(this.path, "utf8"));
16880
18577
  for (const value of Array.isArray(parsed.runs) ? parsed.runs : []) {
16881
18578
  const e = value ?? {};
16882
18579
  if (typeof e.cardUuid === "string" && typeof e.startedAt === "string") {
@@ -16921,7 +18618,7 @@ var AgentRunLog = class {
16921
18618
  };
16922
18619
 
16923
18620
  // src/core/agent/readiness.ts
16924
- import { randomUUID as randomUUID6 } from "crypto";
18621
+ import { randomUUID as randomUUID9 } from "crypto";
16925
18622
  async function checkAgents(adapters, log) {
16926
18623
  return await Promise.all(adapters.map(async (adapter) => {
16927
18624
  const detected = await probe(
@@ -16955,7 +18652,7 @@ function openAgents(checks) {
16955
18652
  return checks.filter((check) => check.installed).map((check) => ({ id: check.id, ready: check.ready, ...check.auth ? { auth: check.auth } : {} }));
16956
18653
  }
16957
18654
  async function probe(log, agent, kind, work, summary2) {
16958
- const callId = randomUUID6();
18655
+ const callId = randomUUID9();
16959
18656
  const started = Date.now();
16960
18657
  log.write({ event: "agent_probe", callId, agent, probe: kind });
16961
18658
  try {
@@ -16977,7 +18674,7 @@ async function probe(log, agent, kind, work, summary2) {
16977
18674
  }
16978
18675
 
16979
18676
  // src/core/agent/sessions.ts
16980
- import { readFile as readFile14, rename as rename8, writeFile as writeFile9 } from "fs/promises";
18677
+ import { readFile as readFile16, rename as rename8, writeFile as writeFile9 } from "fs/promises";
16981
18678
  var AgentSessionMap = class {
16982
18679
  constructor(path) {
16983
18680
  this.path = path;
@@ -16986,7 +18683,7 @@ var AgentSessionMap = class {
16986
18683
  map = emptyMap();
16987
18684
  async load() {
16988
18685
  try {
16989
- const parsed = JSON.parse(await readFile14(this.path, "utf8"));
18686
+ const parsed = JSON.parse(await readFile16(this.path, "utf8"));
16990
18687
  const map = emptyMap();
16991
18688
  map[DEFAULT_AGENT] = entries(parsed.conversations);
16992
18689
  const byAgent = parsed.byAgent && typeof parsed.byAgent === "object" ? parsed.byAgent : {};
@@ -17085,6 +18782,7 @@ async function pcRemoteSetup(input) {
17085
18782
  pcId: settings.pcId,
17086
18783
  hostName,
17087
18784
  remoteEnabled: userId !== void 0 && settings.accounts[accountKey(input.endpoint, userId)]?.remoteTerminal === true,
18785
+ trust: userId !== void 0 ? { keysPath: input.keysPath ?? pcKeysPath(), accountKey: accountKey(input.endpoint, userId), userId } : void 0,
17088
18786
  appHome: input.appHome ?? appHome(),
17089
18787
  env: input.env ?? stringEnv()
17090
18788
  };
@@ -17110,6 +18808,8 @@ async function runPcRemote(setup, signal, onAnswer) {
17110
18808
  hostName: setup.hostName,
17111
18809
  cliVersion: CLI_VERSION_LABEL,
17112
18810
  remoteEnabled: setup.remoteEnabled,
18811
+ trust: setup.trust,
18812
+ notifier: createPcNotifier({ log }),
17113
18813
  exclude: [PC_SESSION_NAME],
17114
18814
  sessionEnv: setup.env,
17115
18815
  appHome: setup.appHome,
@@ -17137,8 +18837,9 @@ async function runPcRemote(setup, signal, onAnswer) {
17137
18837
  var AGENT_HELP_LINES = [
17138
18838
  " ainecto in a terminal, with no arguments: check sign-in, ask once, then connect this PC in the background (same as ainecto start)",
17139
18839
  " ainecto start [--env prod|dev] connect this PC in the background \u2014 keeps running after you close the window (log: ~/.ainecto/agent/agent.log)",
17140
- " ainecto stop [--forget] disconnect this PC now (--forget also removes your approval on this PC)",
17141
- " ainecto remote on|off allow or block terminals from AiNecto on the web on this PC"
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)"
17142
18843
  ];
17143
18844
  function isPcRunCommand(domain, action) {
17144
18845
  return domain === "pc" && action === "run";
@@ -17247,7 +18948,7 @@ async function executeAgentServe(input) {
17247
18948
  }
17248
18949
 
17249
18950
  // src/adapters/cli/ainectoCli.ts
17250
- import { homedir as homedir5, hostname as hostname4, tmpdir } from "os";
18951
+ import { homedir as homedir6, hostname as hostname4, tmpdir } from "os";
17251
18952
  async function runAinectoCli(argv, io) {
17252
18953
  let parsed = { json: argv.includes("--json"), help: false, version: false, positionals: [] };
17253
18954
  try {
@@ -17336,8 +19037,8 @@ async function runAinectoCli(argv, io) {
17336
19037
  auth,
17337
19038
  client: client2,
17338
19039
  // ★외부 CLI 는 홈 폴더에서 돈다 — 지금 저장소의 local·project 범위 항목이 사용자 범위 판정에 끼지 않게.
17339
- runner: systemCommandRunner({ cwd: homedir5() }),
17340
- home: homedir5(),
19040
+ runner: systemCommandRunner({ cwd: homedir6() }),
19041
+ home: homedir6(),
17341
19042
  json: parsed.json,
17342
19043
  io
17343
19044
  });
@@ -17351,9 +19052,9 @@ async function runAinectoCli(argv, io) {
17351
19052
  tokenStore,
17352
19053
  auth,
17353
19054
  client: client2,
17354
- runner: systemCommandRunner({ cwd: homedir5() }),
19055
+ runner: systemCommandRunner({ cwd: homedir6() }),
17355
19056
  hereRunner: systemCommandRunner({ cwd: process.cwd() }),
17356
- home: homedir5(),
19057
+ home: homedir6(),
17357
19058
  cwd: process.cwd(),
17358
19059
  envVars: process.env
17359
19060
  };
@@ -17364,6 +19065,7 @@ async function runAinectoCli(argv, io) {
17364
19065
  interactive,
17365
19066
  paths: termPaths(),
17366
19067
  settingsPath: pcSettingsPath(),
19068
+ keysPath: pcKeysPath(),
17367
19069
  hostName: hostname4(),
17368
19070
  endpoint: resolved.endpoint,
17369
19071
  cwd: process.cwd(),
@@ -17392,6 +19094,35 @@ async function runAinectoCli(argv, io) {
17392
19094
  if (domain === "remote") {
17393
19095
  return await executeRemoteSetting(pcDeps(), parsed.positionals.slice(1));
17394
19096
  }
19097
+ if (domain === "pair") {
19098
+ return await executePair({
19099
+ io,
19100
+ json: parsed.json,
19101
+ interactive,
19102
+ insideTermSession: process.env[SESSION_ENV] !== void 0,
19103
+ openTty: openDevTty,
19104
+ settingsPath: pcSettingsPath(),
19105
+ keysPath: pcKeysPath(),
19106
+ hostName: hostname4(),
19107
+ endpoint: resolved.endpoint,
19108
+ 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
+ findPcs: () => runningPcGroups(pcDeps()),
19121
+ turnOffPcs: (groups) => turnOffPcs(pcDeps(), groups),
19122
+ waitMs: PAIR_WAIT_MS,
19123
+ now: () => /* @__PURE__ */ new Date()
19124
+ }, parsed.positionals.slice(1));
19125
+ }
17395
19126
  if (domain === "init") {
17396
19127
  return await runInit(parsed.positionals.slice(1));
17397
19128
  }
@@ -17441,9 +19172,9 @@ async function runAinectoCli(argv, io) {
17441
19172
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
17442
19173
  return await response.json();
17443
19174
  },
17444
- makeTempDir: () => mkdtemp(join10(tmpdir(), "ainecto-upgrade-")),
19175
+ makeTempDir: () => mkdtemp(join11(tmpdir(), "ainecto-upgrade-")),
17445
19176
  removeDir: (path) => rm3(path, { recursive: true, force: true }),
17446
- home: homedir5(),
19177
+ home: homedir6(),
17447
19178
  log: openAgentLog(swapPaths)
17448
19179
  });
17449
19180
  }