@ainecto/cli 0.14.0 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5541,6 +5541,19 @@ function tokenKey(endpoint) {
5541
5541
  return createHash("sha256").update(endpoint).digest("hex");
5542
5542
  }
5543
5543
 
5544
+ // src/core/async/stopSignals.ts
5545
+ var STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
5546
+ function onStopSignals(handler) {
5547
+ for (const signal of STOP_SIGNALS) {
5548
+ process.on(signal, handler);
5549
+ }
5550
+ return () => {
5551
+ for (const signal of STOP_SIGNALS) {
5552
+ process.off(signal, handler);
5553
+ }
5554
+ };
5555
+ }
5556
+
5544
5557
  // src/core/auth/oauth.ts
5545
5558
  import { createHash as createHash3, randomBytes } from "crypto";
5546
5559
  import { createServer } from "http";
@@ -5686,10 +5699,10 @@ function legacyRoleInput(flag, envVars = process.env) {
5686
5699
 
5687
5700
  // src/core/version.ts
5688
5701
  var UNBUNDLED_VERSION = "dev";
5689
- var CLI_VERSION = true ? "0.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}`;
5702
+ var CLI_VERSION = true ? "0.15.2" : UNBUNDLED_VERSION;
5703
+ var CLI_BUILD = true ? "cdf776d" : void 0;
5704
+ function cliVersionLabel(version, build, release2) {
5705
+ return release2 || build === void 0 ? version : `${version}-dev+${build}`;
5693
5706
  }
5694
5707
  var CLI_RELEASE = true;
5695
5708
  var CLI_VERSION_LABEL = cliVersionLabel(CLI_VERSION, CLI_BUILD, CLI_RELEASE);
@@ -6606,19 +6619,22 @@ function launchBrowser(url, deps = {}) {
6606
6619
  reject(unavailable(error instanceof Error ? error.message : String(error)));
6607
6620
  return;
6608
6621
  }
6609
- child.once("error", (error) => reject(unavailable(error.message)));
6622
+ const settle = (finish) => {
6623
+ child.unref();
6624
+ finish();
6625
+ };
6626
+ child.once("error", (error) => settle(() => reject(unavailable(error.message))));
6610
6627
  if (platform === "win32") {
6611
- child.once("spawn", () => resolve4());
6628
+ child.once("spawn", () => settle(resolve4));
6612
6629
  } else {
6613
6630
  child.once("exit", (code, signal) => {
6614
6631
  if (code === 0) {
6615
- resolve4();
6632
+ settle(resolve4);
6616
6633
  } else {
6617
- reject(unavailable(code === null ? `stopped by ${signal ?? "a signal"}` : `exited with code ${code}`));
6634
+ settle(() => reject(unavailable(code === null ? `stopped by ${signal ?? "a signal"}` : `exited with code ${code}`)));
6618
6635
  }
6619
6636
  });
6620
6637
  }
6621
- child.unref();
6622
6638
  });
6623
6639
  }
6624
6640
  function openBrowser(url) {
@@ -7367,14 +7383,14 @@ function managedBlockProblem(key, body) {
7367
7383
  return void 0;
7368
7384
  }
7369
7385
  function hasUnclosedFence(content) {
7370
- let open2;
7386
+ let open3;
7371
7387
  for (const line of content.split("\n")) {
7372
7388
  const fence = fenceOf(line);
7373
7389
  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;
7390
+ if (!open3) open3 = { char: fence.char, length: fence.length };
7391
+ else if (fence.char === open3.char && fence.length >= open3.length && fence.info === "") open3 = void 0;
7376
7392
  }
7377
- return open2 !== void 0;
7393
+ return open3 !== void 0;
7378
7394
  }
7379
7395
  function canonicalManagedBlock(block) {
7380
7396
  return block.trim();
@@ -7434,24 +7450,24 @@ function hit(at, marker) {
7434
7450
  return at >= 0 ? { at, length: marker.length } : void 0;
7435
7451
  }
7436
7452
  function isInsideFencedBlock(content, index) {
7437
- let open2;
7453
+ let open3;
7438
7454
  let offset = 0;
7439
7455
  for (const line of content.split("\n")) {
7440
7456
  const nextOffset = offset + line.length + 1;
7441
7457
  if (index < nextOffset) {
7442
- return open2 !== void 0;
7458
+ return open3 !== void 0;
7443
7459
  }
7444
7460
  const fence = fenceOf(line);
7445
7461
  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;
7462
+ if (!open3) {
7463
+ open3 = { char: fence.char, length: fence.length };
7464
+ } else if (fence.char === open3.char && fence.length >= open3.length && fence.info === "") {
7465
+ open3 = void 0;
7450
7466
  }
7451
7467
  }
7452
7468
  offset = nextOffset;
7453
7469
  }
7454
- return open2 !== void 0;
7470
+ return open3 !== void 0;
7455
7471
  }
7456
7472
  function fenceOf(line) {
7457
7473
  const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
@@ -8020,15 +8036,19 @@ async function confirmDestructiveCommand(options) {
8020
8036
  });
8021
8037
  }
8022
8038
  }
8023
- async function promptLine(io, message2) {
8039
+ async function promptLine(io, message2, signal) {
8040
+ if (signal?.aborted) return "";
8024
8041
  io.stderr.write(message2);
8025
8042
  const rl = createInterface2({ input: io.stdin, terminal: false });
8043
+ const close = () => rl.close();
8044
+ signal?.addEventListener("abort", close, { once: true });
8026
8045
  try {
8027
8046
  for await (const line of rl) {
8028
8047
  return line;
8029
8048
  }
8030
8049
  return "";
8031
8050
  } finally {
8051
+ signal?.removeEventListener("abort", close);
8032
8052
  rl.close();
8033
8053
  }
8034
8054
  }
@@ -8807,12 +8827,12 @@ function readRecord(content) {
8807
8827
  }
8808
8828
  };
8809
8829
  }
8810
- function serializeRecord(record3) {
8830
+ function serializeRecord(record4) {
8811
8831
  return `${JSON.stringify({
8812
8832
  kind: RECORD_KIND,
8813
8833
  version: RECORD_VERSION,
8814
- files: record3.files,
8815
- createdDirectories: record3.createdDirectories
8834
+ files: record4.files,
8835
+ createdDirectories: record4.createdDirectories
8816
8836
  }, null, 2)}
8817
8837
  `;
8818
8838
  }
@@ -9069,20 +9089,20 @@ function planInit(input) {
9069
9089
  const carriedRecord = previous.state === "valid" ? previous.record : emptyRecord();
9070
9090
  const writes = [];
9071
9091
  const notes = [];
9072
- const record3 = {
9092
+ const record4 = {
9073
9093
  version: carriedRecord.version,
9074
9094
  files: { ...carriedRecord.files },
9075
9095
  createdDirectories: [...carriedRecord.createdDirectories]
9076
9096
  };
9077
9097
  const priorOf = (path, current) => {
9078
- const prior = record3.files[path];
9098
+ const prior = record4.files[path];
9079
9099
  if (prior === void 0) {
9080
9100
  return void 0;
9081
9101
  }
9082
9102
  if (sameOwned(prior.written, current) || sameOwned(prior.original, current)) {
9083
9103
  return prior;
9084
9104
  }
9085
- delete record3.files[path];
9105
+ delete record4.files[path];
9086
9106
  notes.push(`${path}: it changed outside ainecto, so the older backup was dropped and this is the new baseline.`);
9087
9107
  return void 0;
9088
9108
  };
@@ -9091,7 +9111,7 @@ function planInit(input) {
9091
9111
  if (prior === void 0 && original.at !== "absent") {
9092
9112
  notes.push(`${path} already existed; its original was saved and --undo will restore it.`);
9093
9113
  }
9094
- record3.files[path] = {
9114
+ record4.files[path] = {
9095
9115
  scope: "whole",
9096
9116
  createdByUs: prior?.createdByUs ?? existing === void 0,
9097
9117
  original,
@@ -9134,7 +9154,7 @@ function planInit(input) {
9134
9154
  if (prior === void 0 && original.at !== "absent") {
9135
9155
  notes.push(`${target.path}: your existing "${SERVER_NAME}" entry was saved and will be restored by --undo`);
9136
9156
  }
9137
- record3.files[target.path] = {
9157
+ record4.files[target.path] = {
9138
9158
  scope: "entry",
9139
9159
  createdByUs: prior?.createdByUs ?? existing === void 0,
9140
9160
  original,
@@ -9179,7 +9199,7 @@ ${codexContent}`);
9179
9199
  continue;
9180
9200
  }
9181
9201
  const blockNow = existing === void 0 ? void 0 : existingMarkerBlock(existing);
9182
- const carried = record3.files[target.path];
9202
+ const carried = record4.files[target.path];
9183
9203
  let content;
9184
9204
  try {
9185
9205
  content = upsertMarkerBlock(existing, note);
@@ -9201,7 +9221,7 @@ ${codexContent}`);
9201
9221
  if (prior === void 0 && original.at !== "absent") {
9202
9222
  notes.push(`${target.path}: an existing ainecto block was saved and will be restored by --undo`);
9203
9223
  }
9204
- record3.files[target.path] = {
9224
+ record4.files[target.path] = {
9205
9225
  scope: "block",
9206
9226
  createdByUs: prior?.createdByUs ?? existing === void 0,
9207
9227
  original,
@@ -9227,7 +9247,7 @@ ${codexContent}`);
9227
9247
  if (existingConfig !== void 0 && theirConfig === void 0) {
9228
9248
  notes.push(`${HARNESS_CONFIG_PATH} is not a JSON object \u2014 left untouched.`);
9229
9249
  } else {
9230
- const priorConfig = record3.files[HARNESS_CONFIG_PATH];
9250
+ const priorConfig = record4.files[HARNESS_CONFIG_PATH];
9231
9251
  const originalFields = {};
9232
9252
  for (const field of OUR_CONFIG_FIELDS) {
9233
9253
  const presentNow = theirConfig !== void 0 && hasField(theirConfig, field);
@@ -9259,7 +9279,7 @@ ${codexContent}`);
9259
9279
  }
9260
9280
  }
9261
9281
  const mergedConfig = serialize({ ...retained, ...ourFields });
9262
- record3.files[HARNESS_CONFIG_PATH] = {
9282
+ record4.files[HARNESS_CONFIG_PATH] = {
9263
9283
  scope: "fields",
9264
9284
  createdByUs: priorConfig?.createdByUs ?? existingConfig === void 0,
9265
9285
  original: ABSENT,
@@ -9277,7 +9297,7 @@ ${codexContent}`);
9277
9297
  }
9278
9298
  }
9279
9299
  const existingRecord = input.files.get(HARNESS_RECORD_PATH);
9280
- const recordContent = serializeRecord(record3);
9300
+ const recordContent = serializeRecord(record4);
9281
9301
  if (recordContent !== existingRecord) {
9282
9302
  writes.push({
9283
9303
  path: HARNESS_RECORD_PATH,
@@ -9285,7 +9305,7 @@ ${codexContent}`);
9285
9305
  existed: existingRecord !== void 0
9286
9306
  });
9287
9307
  }
9288
- return { writes, deletes: [], notes, record: record3 };
9308
+ return { writes, deletes: [], notes, record: record4 };
9289
9309
  }
9290
9310
  function planUndo(input) {
9291
9311
  const state = input.record ?? readRecord(input.files.get(HARNESS_RECORD_PATH));
@@ -9307,9 +9327,9 @@ function planUndo(input) {
9307
9327
  tail();
9308
9328
  return { writes, deletes, notes };
9309
9329
  }
9310
- const record3 = state.record;
9311
- const remaining = { ...record3.files };
9312
- for (const [path, contract] of Object.entries(record3.files)) {
9330
+ const record4 = state.record;
9331
+ const remaining = { ...record4.files };
9332
+ for (const [path, contract] of Object.entries(record4.files)) {
9313
9333
  const outcome = undoOne(path, contract, input.files.get(path));
9314
9334
  if (outcome.kind !== "unresolved" && outcome.kind !== "keep" && outcome.note !== void 0) {
9315
9335
  notes.push(outcome.note);
@@ -9329,7 +9349,7 @@ function planUndo(input) {
9329
9349
  tail();
9330
9350
  if (input.files.get(HARNESS_RECORD_PATH) !== void 0) {
9331
9351
  if (Object.keys(remaining).length > 0) {
9332
- const reduced = { ...record3, files: remaining };
9352
+ const reduced = { ...record4, files: remaining };
9333
9353
  writes.push({ path: HARNESS_RECORD_PATH, content: serializeRecord(reduced), existed: true });
9334
9354
  notes.push(
9335
9355
  `${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 +9358,7 @@ function planUndo(input) {
9338
9358
  deletes.push(HARNESS_RECORD_PATH);
9339
9359
  }
9340
9360
  }
9341
- const removableDirectories = parentsOf(deletes).filter((directory) => record3.createdDirectories.includes(directory));
9361
+ const removableDirectories = parentsOf(deletes).filter((directory) => record4.createdDirectories.includes(directory));
9342
9362
  return { writes, deletes, notes, removableDirectories };
9343
9363
  }
9344
9364
  function unexplainedMarkers(existing, contract) {
@@ -9820,9 +9840,9 @@ Already applied before this failure: ${applied.join(", ") || "(nothing)"}`
9820
9840
  }
9821
9841
  }
9822
9842
  function orderedWrites(writes, recordFirst) {
9823
- const record3 = writes.filter((write) => write.path === HARNESS_RECORD_PATH);
9843
+ const record4 = writes.filter((write) => write.path === HARNESS_RECORD_PATH);
9824
9844
  const rest = writes.filter((write) => write.path !== HARNESS_RECORD_PATH);
9825
- return recordFirst ? [...record3, ...rest] : [...rest, ...record3];
9845
+ return recordFirst ? [...record4, ...rest] : [...rest, ...record4];
9826
9846
  }
9827
9847
  async function assertUnchangedSinceSnapshot(root, relativePath, snapshot) {
9828
9848
  if (!snapshot.has(relativePath)) {
@@ -9918,55 +9938,9 @@ function isRecord13(value) {
9918
9938
  return typeof value === "object" && value !== null && !Array.isArray(value);
9919
9939
  }
9920
9940
 
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
9941
  // src/core/os/launch.ts
9969
9942
  import {
9943
+ execFile,
9970
9944
  spawn as spawn2
9971
9945
  } from "child_process";
9972
9946
  import { statSync } from "fs";
@@ -10156,6 +10130,135 @@ function stuckProcessHint(pid, platform = process.platform) {
10156
10130
  function loginShell(env) {
10157
10131
  return env.SHELL || userInfo().shell || "/bin/sh";
10158
10132
  }
10133
+ function processAlive(pid) {
10134
+ return signalZero(pid);
10135
+ }
10136
+ function processGroupAlive(pgid) {
10137
+ return signalZero(-pgid);
10138
+ }
10139
+ function signalZero(target) {
10140
+ try {
10141
+ process.kill(target, 0);
10142
+ return true;
10143
+ } catch (error) {
10144
+ return isNodeError(error, "EPERM");
10145
+ }
10146
+ }
10147
+ async function processGroupOf(pid, platform = process.platform) {
10148
+ if (platform !== "darwin" && platform !== "linux") return void 0;
10149
+ return await new Promise((resolve4) => {
10150
+ execFile("ps", ["-o", "pgid=", "-p", String(pid)], { timeout: 5e3 }, (error, stdout) => {
10151
+ const pgid = Number.parseInt(String(stdout).trim(), 10);
10152
+ resolve4(error || !Number.isSafeInteger(pgid) || pgid <= 0 ? void 0 : pgid);
10153
+ });
10154
+ });
10155
+ }
10156
+ function processGroupUnavailableHint(platform = process.platform) {
10157
+ 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`)." : "";
10158
+ }
10159
+ function runQuiet(file, args) {
10160
+ return new Promise((resolve4, reject) => {
10161
+ execFile(file, [...args], { windowsHide: true }, (error) => error ? reject(error) : resolve4());
10162
+ });
10163
+ }
10164
+ function endedFromOutside(exitCode2, signal, platform = process.platform) {
10165
+ if (signal !== 0) return true;
10166
+ return platform === "win32" && exitCode2 !== 0;
10167
+ }
10168
+ function controllingTerminal(platform = process.platform) {
10169
+ return platform === "win32" ? { input: "\\\\.\\CONIN$", inputFlags: "r+", output: "\\\\.\\CONOUT$", outputFlags: "r+" } : { input: "/dev/tty", inputFlags: "r", output: "/dev/tty", outputFlags: "w" };
10170
+ }
10171
+ function notifyTool(platform = process.platform) {
10172
+ if (platform === "darwin") {
10173
+ return {
10174
+ name: "osascript",
10175
+ file: "osascript",
10176
+ args: (title, body) => [
10177
+ "-e",
10178
+ "on run argv",
10179
+ "-e",
10180
+ "display notification (item 2 of argv) with title (item 1 of argv)",
10181
+ "-e",
10182
+ "end run",
10183
+ title,
10184
+ body
10185
+ ]
10186
+ };
10187
+ }
10188
+ if (platform === "linux") {
10189
+ return { name: "notify-send", file: "notify-send", args: (title, body) => ["--", title, body] };
10190
+ }
10191
+ if (platform === "win32") {
10192
+ return { name: "powershell", file: "powershell.exe", args: (title, body) => ["-NoProfile", "-NonInteractive", "-EncodedCommand", windowsToastScript(title, body)] };
10193
+ }
10194
+ return void 0;
10195
+ }
10196
+ function windowsToastScript(title, body) {
10197
+ const b64 = (text2) => Buffer.from(text2, "utf8").toString("base64");
10198
+ const script = [
10199
+ "$ErrorActionPreference = 'Stop'",
10200
+ `$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title)}'))`,
10201
+ `$b = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(body)}'))`,
10202
+ "[void][Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]",
10203
+ "$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)",
10204
+ "$n = $x.GetElementsByTagName('text')",
10205
+ "[void]$n.Item(0).AppendChild($x.CreateTextNode($t))",
10206
+ "[void]$n.Item(1).AppendChild($x.CreateTextNode($b))",
10207
+ "$app = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe'",
10208
+ "[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show([Windows.UI.Notifications.ToastNotification]::new($x))"
10209
+ ].join("\n");
10210
+ return Buffer.from(script, "utf16le").toString("base64");
10211
+ }
10212
+ function notificationHint(platform = process.platform) {
10213
+ return platform === "darwin" ? "macOS: allow notifications for \xABScript Editor\xBB (System Settings \u203A Notifications) so this PC can alert you when a browser is registered or opens a terminal here." : void 0;
10214
+ }
10215
+
10216
+ // src/core/setup/accountSummary.ts
10217
+ async function readAccount(client) {
10218
+ const summary2 = {};
10219
+ try {
10220
+ await client.initialize();
10221
+ const self = unwrapMcpToolPayload(await client.toolsCall("identity_get_self", {}));
10222
+ if (typeof self?.userId === "string") summary2.userId = self.userId;
10223
+ if (typeof self?.displayName === "string") summary2.displayName = self.displayName;
10224
+ if ("jobProfile" in (self ?? {})) {
10225
+ const profile = self.jobProfile;
10226
+ summary2.jobTitle = profile && typeof profile.title === "string" ? profile.title : null;
10227
+ }
10228
+ summary2.projectCount = extractProjects(unwrapMcpToolPayload(await client.toolsCall("list_projects", {}))).length;
10229
+ } catch (error) {
10230
+ summary2.problem = classify(error);
10231
+ }
10232
+ return summary2;
10233
+ }
10234
+ function classify(error) {
10235
+ const message2 = error instanceof Error ? error.message : String(error);
10236
+ if (error instanceof McpRpcError && error.code === "MCP_HTTP_ERROR") {
10237
+ const status = error.details?.status;
10238
+ if (status === 401) return { kind: "unauthorized", message: message2 };
10239
+ if (status === 403) return { kind: "forbidden", message: message2 };
10240
+ return { kind: "other", message: message2 };
10241
+ }
10242
+ if (error instanceof McpRpcError) {
10243
+ return { kind: "other", message: message2 };
10244
+ }
10245
+ return { kind: "network", message: message2 };
10246
+ }
10247
+
10248
+ // src/core/setup/agentConnections.ts
10249
+ import { chmod as chmod4, mkdir as mkdir5, readFile as readFile6, rename as rename5, stat as stat5, writeFile as writeFile4 } from "fs/promises";
10250
+ import { dirname as dirname6, join as join4 } from "path";
10251
+
10252
+ // src/core/agent/limits.ts
10253
+ var AGENT_CALL_TIMEOUT_MS = 1e4;
10254
+ var AGENT_RETRY_MIN_MS = 500;
10255
+ var AGENT_RETRY_MAX_MS = 1e4;
10256
+ var AGENT_TURN_TIMEOUT_MS = 15 * 6e4;
10257
+ var AGENT_STOP_WAIT_MS = 5e3;
10258
+ function nextRetryDelay(previousMs) {
10259
+ if (previousMs === void 0) return AGENT_RETRY_MIN_MS;
10260
+ return Math.min(previousMs * 2, AGENT_RETRY_MAX_MS);
10261
+ }
10159
10262
 
10160
10263
  // src/core/setup/commandRunner.ts
10161
10264
  var COMMAND_TIMEOUT_MS = 9e4;
@@ -10524,7 +10627,7 @@ async function executeSetupCommand(options) {
10524
10627
  options.io.stderr.write("Signed in.\n");
10525
10628
  signedIn = true;
10526
10629
  }
10527
- const account = signedIn ? await readAccount(options.client) : void 0;
10630
+ const account2 = signedIn ? await readAccount(options.client) : void 0;
10528
10631
  const agents = [];
10529
10632
  const remote = [];
10530
10633
  for (const state of await inspectAgents(context)) {
@@ -10535,33 +10638,33 @@ async function executeSetupCommand(options) {
10535
10638
  remote.push(state.client);
10536
10639
  }
10537
10640
  }
10538
- const failed = agents.some((agent) => agent.status === "failed") || account?.problem !== void 0;
10641
+ const failed = agents.some((agent) => agent.status === "failed") || account2?.problem !== void 0;
10539
10642
  options.io.stdout.write(renderSuccess({
10540
10643
  action: args.dryRun ? "setup (dry-run)" : "setup",
10541
10644
  setup: failed ? "partial" : "complete",
10542
10645
  endpoint: options.endpoint,
10543
- account: accountView(account, signedIn, options.endpoint),
10646
+ account: accountView(account2, signedIn, options.endpoint),
10544
10647
  agents,
10545
10648
  commands,
10546
- next: nextSteps(account, agents, remote, options.endpoint)
10649
+ next: nextSteps(account2, agents, remote, options.endpoint)
10547
10650
  }, { json: options.json }));
10548
10651
  return failed ? 1 : 0;
10549
10652
  }
10550
- function accountView(account, signedIn, endpoint) {
10653
+ function accountView(account2, signedIn, endpoint) {
10551
10654
  if (!signedIn) {
10552
10655
  return { signedIn: false, note: "sign-in required \u2014 `ainecto setup` (without --dry-run) opens the browser once" };
10553
10656
  }
10554
10657
  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)}`;
10658
+ if (account2?.userId) view.userId = account2.userId;
10659
+ if (account2?.displayName) view.name = account2.displayName;
10660
+ if (account2?.jobTitle !== void 0) {
10661
+ view.jobTitle = account2.jobTitle ?? `not set \u2014 set it at ${profileSettingsUrl(endpoint)}`;
10559
10662
  }
10560
- if (account?.projectCount !== void 0) view.projects = account.projectCount;
10561
- if (account?.problem) view.problem = `${account.problem.kind}: ${account.problem.message}`;
10663
+ if (account2?.projectCount !== void 0) view.projects = account2.projectCount;
10664
+ if (account2?.problem) view.problem = `${account2.problem.kind}: ${account2.problem.message}`;
10562
10665
  return view;
10563
10666
  }
10564
- function nextSteps(account, agents, remote, endpoint) {
10667
+ function nextSteps(account2, agents, remote, endpoint) {
10565
10668
  const next = [];
10566
10669
  if (agents.some((agent) => agent.status === "connected" || agent.status === "updated")) {
10567
10670
  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 +10672,12 @@ function nextSteps(account, agents, remote, endpoint) {
10569
10672
  if (remote.length > 0) {
10570
10673
  next.push(`Each agent signs in to AiNecto by itself the first time it connects: ${remote.map((client) => REMOTE_SIGN_IN[client]).join("; ")}.`);
10571
10674
  }
10572
- if (account?.jobTitle === null) {
10675
+ if (account2?.jobTitle === null) {
10573
10676
  next.push(`Set your AiNecto role (your job) at ${profileSettingsUrl(endpoint)} \u2014 AI uses it to pitch explanations; it does not change permissions.`);
10574
10677
  }
10575
10678
  next.push("To add AiNecto's working rules to a repository, run `ainecto init` from its root.");
10679
+ const notifyHint = notificationHint();
10680
+ if (notifyHint) next.push(notifyHint);
10576
10681
  next.push("`ainecto doctor` shows anything still missing.");
10577
10682
  return next;
10578
10683
  }
@@ -10858,9 +10963,12 @@ async function executeDoctorCommand(options) {
10858
10963
  const checks = doctorChecks(status);
10859
10964
  const failed = checks.filter((check) => check.level === "fail").length;
10860
10965
  const warned = checks.filter((check) => check.level === "warn").length;
10966
+ const notifyHint = notificationHint();
10861
10967
  options.io.stdout.write(renderSuccess({
10862
10968
  summary: failed > 0 ? `${failed} problem(s) to fix` : warned > 0 ? `working \u2014 ${warned} suggestion(s)` : "all good",
10863
- checks
10969
+ checks,
10970
+ // macOS 첫 알림 허용 안내 한 줄(설계 terminal-e2e §4-6) — 판정(ok/warn/fail)에는 넣지 않는다.
10971
+ ...notifyHint ? { note: notifyHint } : {}
10864
10972
  }, { json: options.json }));
10865
10973
  return failed > 0 ? 1 : 0;
10866
10974
  }
@@ -11014,8 +11122,8 @@ var DaemonLog = class {
11014
11122
  enableRotation() {
11015
11123
  this.rotating = true;
11016
11124
  }
11017
- write(record3) {
11018
- const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record3 })}
11125
+ write(record4) {
11126
+ const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record4 })}
11019
11127
  `;
11020
11128
  try {
11021
11129
  if (this.rotating) {
@@ -11202,28 +11310,28 @@ function parseClientMessage(line) {
11202
11310
  } catch {
11203
11311
  throw new TermProtocolError("Not a JSON line.");
11204
11312
  }
11205
- const record3 = asRecord(value);
11206
- const op = stringField(record3, "op");
11313
+ const record4 = asRecord(value);
11314
+ const op = stringField(record4, "op");
11207
11315
  if (op === "in") {
11208
- return { op, d: stringField(record3, "d") };
11316
+ return { op, d: stringField(record4, "d") };
11209
11317
  }
11210
11318
  if (op === "resize") {
11211
- return { op, cols: sizeField(record3, "cols"), rows: sizeField(record3, "rows") };
11319
+ return { op, cols: sizeField(record4, "cols"), rows: sizeField(record4, "rows") };
11212
11320
  }
11213
- const id = stringField(record3, "id");
11321
+ const id = stringField(record4, "id");
11214
11322
  switch (op) {
11215
11323
  case "new":
11216
11324
  return {
11217
11325
  id,
11218
11326
  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") }
11327
+ name: stringField(record4, "name"),
11328
+ cwd: stringField(record4, "cwd"),
11329
+ command: record4.command === null ? null : stringArrayField(record4, "command"),
11330
+ env: stringMapField(record4, "env"),
11331
+ cols: optionalSize(record4, "cols"),
11332
+ rows: optionalSize(record4, "rows"),
11333
+ ...record4.project === void 0 ? {} : { project: projectField(record4, "project") },
11334
+ ...record4.input === void 0 ? {} : { input: noInputField(record4, "input") }
11227
11335
  };
11228
11336
  case "ls":
11229
11337
  case "kill-server":
@@ -11231,39 +11339,41 @@ function parseClientMessage(line) {
11231
11339
  case "watch-sessions":
11232
11340
  return { id, op };
11233
11341
  case "label": {
11234
- const label = stringField(record3, "label");
11342
+ const label = stringField(record4, "label");
11235
11343
  if (label.length === 0) {
11236
11344
  throw new TermProtocolError(`"label" must not be empty.`);
11237
11345
  }
11238
- return { id, op, name: stringField(record3, "name"), label };
11346
+ return { id, op, name: stringField(record4, "name"), label, ...optionalInstance(record4) };
11239
11347
  }
11240
11348
  case "send":
11241
- return { id, op, name: stringField(record3, "name"), text: stringField(record3, "text"), paste: record3.paste === true };
11349
+ return { id, op, name: stringField(record4, "name"), text: stringField(record4, "text"), paste: record4.paste === true, ...optionalInstance(record4) };
11242
11350
  case "key":
11243
- return { id, op, name: stringField(record3, "name"), key: stringField(record3, "key") };
11351
+ return { id, op, name: stringField(record4, "name"), key: stringField(record4, "key"), ...optionalInstance(record4) };
11244
11352
  case "read":
11245
- return { id, op, name: stringField(record3, "name"), scrollback: record3.scrollback === true, lines: optionalSize(record3, "lines") };
11353
+ return { id, op, name: stringField(record4, "name"), scrollback: record4.scrollback === true, lines: optionalSize(record4, "lines") };
11246
11354
  case "kill":
11355
+ return { id, op, name: stringField(record4, "name"), ...optionalInstance(record4) };
11247
11356
  case "watch":
11248
- return { id, op, name: stringField(record3, "name") };
11357
+ return { id, op, name: stringField(record4, "name") };
11249
11358
  case "restore":
11250
- return { id, op, env: stringMapField(record3, "env") };
11359
+ return { id, op, env: stringMapField(record4, "env") };
11251
11360
  case "hello":
11252
- return { id, op, nonce: stringField(record3, "nonce") };
11361
+ return { id, op, nonce: stringField(record4, "nonce") };
11253
11362
  case "attach":
11363
+ return { id, op, name: stringField(record4, "name"), cols: sizeField(record4, "cols"), rows: sizeField(record4, "rows") };
11254
11364
  case "set-size":
11255
- return { id, op, name: stringField(record3, "name"), cols: sizeField(record3, "cols"), rows: sizeField(record3, "rows") };
11365
+ return { id, op, name: stringField(record4, "name"), cols: sizeField(record4, "cols"), rows: sizeField(record4, "rows"), ...optionalInstance(record4) };
11256
11366
  default:
11257
11367
  throw new TermProtocolError(`Unknown op "${op}".`);
11258
11368
  }
11259
11369
  }
11260
11370
  function parseDaemonMessage(line) {
11261
- const record3 = asRecord(JSON.parse(line));
11262
- if (typeof record3.event === "string") {
11263
- switch (record3.event) {
11371
+ const record4 = asRecord(JSON.parse(line));
11372
+ if (typeof record4.event === "string") {
11373
+ switch (record4.event) {
11264
11374
  case "screen":
11265
11375
  case "out":
11266
- return { event: record3.event, d: stringField(record3, "d") };
11376
+ return { event: record4.event, d: stringField(record4, "d") };
11267
11377
  case "changed":
11268
11378
  return { event: "changed" };
11269
11379
  case "sessions":
@@ -11271,19 +11381,19 @@ function parseDaemonMessage(line) {
11271
11381
  case "exit":
11272
11382
  return {
11273
11383
  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")
11384
+ exitCode: typeof record4.exitCode === "number" ? record4.exitCode : 0,
11385
+ signal: typeof record4.signal === "number" ? record4.signal : 0,
11386
+ reset: stringField(record4, "reset")
11277
11387
  };
11278
11388
  default:
11279
- throw new TermProtocolError(`Unknown event "${record3.event}".`);
11389
+ throw new TermProtocolError(`Unknown event "${record4.event}".`);
11280
11390
  }
11281
11391
  }
11282
- const id = stringField(record3, "id");
11283
- if (record3.ok === true) {
11284
- return { id, ok: true, data: record3.data };
11392
+ const id = stringField(record4, "id");
11393
+ if (record4.ok === true) {
11394
+ return { id, ok: true, data: record4.data };
11285
11395
  }
11286
- const error = asRecord(record3.error);
11396
+ const error = asRecord(record4.error);
11287
11397
  return { id, ok: false, error: { code: stringField(error, "code"), message: stringField(error, "message") } };
11288
11398
  }
11289
11399
  function listedSessions(data) {
@@ -11314,6 +11424,9 @@ function readModes(data) {
11314
11424
  const bracketedPaste = "bracketedPaste" in modes ? modes.bracketedPaste : void 0;
11315
11425
  return typeof altScreen === "boolean" && typeof appCursor === "boolean" && typeof bracketedPaste === "boolean" ? { altScreen, appCursor, bracketedPaste } : void 0;
11316
11426
  }
11427
+ function sessionInstance(data) {
11428
+ return data && typeof data === "object" && "instance" in data && typeof data.instance === "string" && data.instance !== "" ? data.instance : void 0;
11429
+ }
11317
11430
  function readLines(data) {
11318
11431
  if (data && typeof data === "object" && "lines" in data && Array.isArray(data.lines)) {
11319
11432
  return data.lines.filter((line) => typeof line === "string");
@@ -11326,22 +11439,22 @@ function asRecord(value) {
11326
11439
  }
11327
11440
  return value;
11328
11441
  }
11329
- function stringField(record3, key) {
11330
- const value = record3[key];
11442
+ function stringField(record4, key) {
11443
+ const value = record4[key];
11331
11444
  if (typeof value !== "string") {
11332
11445
  throw new TermProtocolError(`"${key}" must be a string.`);
11333
11446
  }
11334
11447
  return value;
11335
11448
  }
11336
- function stringArrayField(record3, key) {
11337
- const value = record3[key];
11449
+ function stringArrayField(record4, key) {
11450
+ const value = record4[key];
11338
11451
  if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string")) {
11339
11452
  throw new TermProtocolError(`"${key}" must be a non-empty string array.`);
11340
11453
  }
11341
11454
  return value;
11342
11455
  }
11343
- function stringMapField(record3, key) {
11344
- const value = asRecord(record3[key]);
11456
+ function stringMapField(record4, key) {
11457
+ const value = asRecord(record4[key]);
11345
11458
  const output = {};
11346
11459
  for (const [name, item] of Object.entries(value)) {
11347
11460
  if (typeof item === "string") {
@@ -11350,28 +11463,36 @@ function stringMapField(record3, key) {
11350
11463
  }
11351
11464
  return output;
11352
11465
  }
11353
- function sizeField(record3, key) {
11354
- const value = record3[key];
11466
+ function sizeField(record4, key) {
11467
+ const value = record4[key];
11355
11468
  if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
11356
11469
  throw new TermProtocolError(`"${key}" must be a positive integer.`);
11357
11470
  }
11358
11471
  return value;
11359
11472
  }
11360
- function projectField(record3, key) {
11361
- const value = stringField(record3, key);
11473
+ function projectField(record4, key) {
11474
+ const value = stringField(record4, key);
11362
11475
  if (!isUuid(value)) {
11363
11476
  throw new TermProtocolError(`"${key}" must be a lowercase UUID.`);
11364
11477
  }
11365
11478
  return value;
11366
11479
  }
11367
- function noInputField(record3, key) {
11368
- if (record3[key] !== "none") {
11480
+ function noInputField(record4, key) {
11481
+ if (record4[key] !== "none") {
11369
11482
  throw new TermProtocolError(`"${key}" must be "none" when present.`);
11370
11483
  }
11371
11484
  return "none";
11372
11485
  }
11373
- function optionalSize(record3, key) {
11374
- return record3[key] === void 0 ? void 0 : sizeField(record3, key);
11486
+ function optionalInstance(record4) {
11487
+ if (record4.instance === void 0) return {};
11488
+ const instance = stringField(record4, "instance");
11489
+ if (instance === "") {
11490
+ throw new TermProtocolError(`"instance" must not be empty.`);
11491
+ }
11492
+ return { instance };
11493
+ }
11494
+ function optionalSize(record4, key) {
11495
+ return record4[key] === void 0 ? void 0 : sizeField(record4, key);
11375
11496
  }
11376
11497
 
11377
11498
  // src/core/term/client.ts
@@ -11503,6 +11624,7 @@ async function openTermClient(paths, options) {
11503
11624
  new DaemonLog(paths.log, paths.previousLog).write({ event: "ipc_impostor", pid: process.pid, message: error.message });
11504
11625
  }
11505
11626
  if (!options.start) {
11627
+ if (options.resetFails && isNodeError(error, "ECONNRESET")) throw error;
11506
11628
  return void 0;
11507
11629
  }
11508
11630
  }
@@ -11666,6 +11788,7 @@ function assertSessionName(name) {
11666
11788
  // src/core/term/session.ts
11667
11789
  var import_addon_serialize = __toESM(require_addon_serialize(), 1);
11668
11790
  var import_headless = __toESM(require_xterm_headless(), 1);
11791
+ import { randomUUID as randomUUID2 } from "crypto";
11669
11792
 
11670
11793
  // src/core/term/keys.ts
11671
11794
  var PLAIN_KEYS = {
@@ -12177,6 +12300,11 @@ var TermSession = class _TermSession {
12177
12300
  label;
12178
12301
  /** 마지막 출력 시각(ISO) — 원격 웹 목록의 «마지막 활동». */
12179
12302
  lastOutputAt;
12303
+ /**
12304
+ * 인스턴스 id — 데몬이 세션을 만들 때마다 새 무작위 값(설계 terminal-e2e §13-1). 이름이 같아도 다시 만든 세션은 다른 값이라,
12305
+ * 원격 명령은 이 값이 맞을 때만 이 세션에 적용된다(daemon.ts 의 이름 찾기 한 곳). 화면(read)도 이 객체에서 같이 낸다.
12306
+ */
12307
+ instance = randomUUID2();
12180
12308
  static async start(spec, onExit) {
12181
12309
  const ptyModule = await loadNodePty();
12182
12310
  const plan = planLaunch(spec.command ?? defaultShellCommand(spec.env), spec.env, void 0, void 0, spec.input ?? "terminal");
@@ -12211,6 +12339,7 @@ var TermSession = class _TermSession {
12211
12339
  cols: this.pty.cols,
12212
12340
  rows: this.pty.rows,
12213
12341
  clients: this.attached.size,
12342
+ instance: this.instance,
12214
12343
  ...this.label !== void 0 ? { label: this.label } : {},
12215
12344
  ...this.spec.project !== void 0 ? { project: this.spec.project } : {},
12216
12345
  ...this.lastOutputAt !== void 0 ? { lastOutputAt: this.lastOutputAt } : {}
@@ -12619,24 +12748,28 @@ var TermDaemon = class {
12619
12748
  }
12620
12749
  case "ls":
12621
12750
  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 } };
12751
+ case "send": {
12752
+ const session = this.session(request.name, request.instance);
12753
+ await session.send(request.text, request.paste);
12754
+ return { data: { name: request.name, instance: session.instance, sent: request.text.length } };
12755
+ }
12756
+ case "key": {
12757
+ const session = this.session(request.name, request.instance);
12758
+ await session.key(request.key);
12759
+ return { data: { name: request.name, instance: session.instance, key: request.key } };
12760
+ }
12628
12761
  case "read": {
12629
12762
  const session = this.session(request.name);
12630
12763
  const lines = await session.read({ scrollback: request.scrollback, lines: request.lines }, connection);
12631
- return { data: { name: request.name, lines, modes: await session.modes() } };
12764
+ return { data: { name: request.name, instance: session.instance, lines, modes: await session.modes() } };
12632
12765
  }
12633
12766
  case "kill": {
12634
- const session = this.session(request.name);
12767
+ const session = this.session(request.name, request.instance);
12635
12768
  this.sessions.delete(request.name);
12636
12769
  session.kill();
12637
12770
  this.updateManifest((entries2) => entries2.filter((item) => item.name !== request.name));
12638
12771
  this.notifySessions();
12639
- return { data: { name: request.name, killed: true } };
12772
+ return { data: { name: request.name, instance: session.instance, killed: true } };
12640
12773
  }
12641
12774
  case "kill-server": {
12642
12775
  this.stopAccepting();
@@ -12673,25 +12806,32 @@ var TermDaemon = class {
12673
12806
  this.listWatchers.add(connection);
12674
12807
  return { data: { watching: "sessions" } };
12675
12808
  case "label": {
12676
- const session = this.session(request.name);
12809
+ const session = this.session(request.name, request.instance);
12677
12810
  session.label = request.label;
12678
12811
  this.updateManifest((entries2) => entries2.map((item) => item.name === request.name ? { ...item, label: request.label } : item));
12679
12812
  this.notifySessions();
12680
- return { data: { name: request.name, label: request.label } };
12813
+ return { data: { name: request.name, instance: session.instance, label: request.label } };
12681
12814
  }
12682
12815
  case "set-size": {
12683
- const session = this.session(request.name);
12816
+ const session = this.session(request.name, request.instance);
12684
12817
  session.resizeTo(request.cols, request.rows);
12685
12818
  const { cols, rows } = session.info();
12686
- return { data: { name: request.name, cols, rows } };
12819
+ return { data: { name: request.name, instance: session.instance, cols, rows } };
12687
12820
  }
12688
12821
  }
12689
12822
  }
12690
- session(name) {
12823
+ /**
12824
+ * 이름으로 세션을 찾는 한 곳. instance 를 주면 ★지금 그 이름의 세션이 그 인스턴스일 때만 — 같은 이름으로 다시 만든 세션이면
12825
+ * SESSION_REPLACED(설계 terminal-e2e §13-1·§14-6 4). 원격 명령의 인스턴스 검사는 다리가 아니라 명령을 적용하는 여기서 한다.
12826
+ */
12827
+ session(name, instance) {
12691
12828
  const session = this.sessions.get(name);
12692
12829
  if (!session) {
12693
12830
  throw new TermError("TERM_NO_SESSION", `No session named "${name}".`);
12694
12831
  }
12832
+ if (instance !== void 0 && session.instance !== instance) {
12833
+ throw new TermError("SESSION_REPLACED", `The session "${name}" was replaced by a new one with the same name.`);
12834
+ }
12695
12835
  return session;
12696
12836
  }
12697
12837
  /**
@@ -12721,12 +12861,13 @@ var TermDaemon = class {
12721
12861
  }
12722
12862
  }
12723
12863
  /**
12724
- * 세션이 스스로 끝났다. ★매니페스트에서 지우는 것은 «신호 없이» 끝났을 때만이다 — 신호로 끝난 세션(재부팅·로그아웃 때
12725
- * 시스템이 보낸 SIGTERM·SIGHUP 포함)은 `restore` 가 다시 띄울 수 있게 남긴다. kill 로 지운 세션은 이미 표에 없다.
12864
+ * 세션이 스스로 끝났다. ★매니페스트에서 지우는 것은 «바깥 사정 없이» 끝났을 때만이다 — 신호로 끝난 세션(재부팅·로그아웃 때
12865
+ * 시스템이 보낸 SIGTERM·SIGHUP 포함 · Windows 는 콘솔 닫힘 끝 코드 — launch.endedFromOutside)은 `restore` 가 다시 띄울 수 있게
12866
+ * 남긴다. kill 로 지운 세션은 이미 표에 없다.
12726
12867
  */
12727
12868
  sessionEnded(session, exitCode2, signal) {
12728
12869
  const current = this.sessions.get(session.name) === session;
12729
- const kept = current && signal !== 0;
12870
+ const kept = current && endedFromOutside(exitCode2, signal);
12730
12871
  if (current) {
12731
12872
  this.sessions.delete(session.name);
12732
12873
  if (!kept) {
@@ -13261,9 +13402,9 @@ function resetField(data) {
13261
13402
  return data && typeof data === "object" && "reset" in data && typeof data.reset === "string" ? data.reset : void 0;
13262
13403
  }
13263
13404
  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 : [];
13405
+ const record4 = data && typeof data === "object" ? data : {};
13406
+ const names = (key) => Array.isArray(record4[key]) ? record4[key].filter((item) => typeof item === "string") : [];
13407
+ const failed = Array.isArray(record4.failed) ? record4.failed : [];
13267
13408
  const parts = [
13268
13409
  names("restored").length ? `Restored: ${names("restored").join(", ")}` : "",
13269
13410
  names("running").length ? `Already running: ${names("running").join(", ")}` : "",
@@ -13276,7 +13417,7 @@ function restoreSummary(data) {
13276
13417
  }
13277
13418
 
13278
13419
  // src/core/pc/pcSettings.ts
13279
- import { randomUUID as randomUUID2 } from "crypto";
13420
+ import { randomUUID as randomUUID3 } from "crypto";
13280
13421
  import { readFile as readFile10 } from "fs/promises";
13281
13422
  import { homedir as homedir3 } from "os";
13282
13423
  import { join as join7 } from "path";
@@ -13286,7 +13427,7 @@ function pcSettingsPath(home = homedir3()) {
13286
13427
  function accountKey(endpoint, userId) {
13287
13428
  return `${endpoint}#${userId}`;
13288
13429
  }
13289
- function normalizePcSettings(raw, hostName, newId = randomUUID2) {
13430
+ function normalizePcSettings(raw, hostName, newId = randomUUID3) {
13290
13431
  const fresh = { pcId: newId(), hostName, accounts: {} };
13291
13432
  if (!raw || typeof raw !== "object") {
13292
13433
  return fresh;
@@ -13298,9 +13439,9 @@ function normalizePcSettings(raw, hostName, newId = randomUUID2) {
13298
13439
  const accounts = {};
13299
13440
  if (value.accounts && typeof value.accounts === "object") {
13300
13441
  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 };
13442
+ const account2 = entry;
13443
+ if (account2 && typeof account2.consentedAt === "string" && typeof account2.remoteTerminal === "boolean") {
13444
+ accounts[key] = { consentedAt: account2.consentedAt, remoteTerminal: account2.remoteTerminal };
13304
13445
  }
13305
13446
  }
13306
13447
  }
@@ -13330,12 +13471,14 @@ function withConsent(settings, key, remoteTerminal, now) {
13330
13471
  return { ...settings, accounts: { ...settings.accounts, [key]: { consentedAt: now.toISOString(), remoteTerminal } } };
13331
13472
  }
13332
13473
  function withRemoteTerminal(settings, key, remoteTerminal) {
13333
- const account = settings.accounts[key];
13334
- return account ? { ...settings, accounts: { ...settings.accounts, [key]: { ...account, remoteTerminal } } } : void 0;
13474
+ const account2 = settings.accounts[key];
13475
+ return account2 ? { ...settings, accounts: { ...settings.accounts, [key]: { ...account2, remoteTerminal } } } : void 0;
13476
+ }
13477
+ function isEndpointAccount(key, endpoint) {
13478
+ return key.startsWith(`${endpoint}#`);
13335
13479
  }
13336
13480
  function withoutEndpoint(settings, endpoint) {
13337
- const prefix = `${endpoint}#`;
13338
- return { ...settings, accounts: Object.fromEntries(Object.entries(settings.accounts).filter(([key]) => !key.startsWith(prefix))) };
13481
+ return { ...settings, accounts: Object.fromEntries(Object.entries(settings.accounts).filter(([key]) => !isEndpointAccount(key, endpoint))) };
13339
13482
  }
13340
13483
 
13341
13484
  // src/core/async/sleep.ts
@@ -13387,7 +13530,7 @@ function agentEnv(env) {
13387
13530
  }
13388
13531
 
13389
13532
  // src/core/http/pcHttp.ts
13390
- import { randomUUID as randomUUID3 } from "crypto";
13533
+ import { randomUUID as randomUUID4 } from "crypto";
13391
13534
  var PcCallError = class extends Error {
13392
13535
  constructor(message2, op, status, code) {
13393
13536
  super(message2);
@@ -13437,7 +13580,7 @@ function createPcHttp(input) {
13437
13580
  sessionToken = token;
13438
13581
  },
13439
13582
  async call(op, body, options) {
13440
- const callId = randomUUID3();
13583
+ const callId = randomUUID4();
13441
13584
  const payload = JSON.stringify(body);
13442
13585
  const started = Date.now();
13443
13586
  log.write(input.logging.request({ callId, op, bytes: Buffer.byteLength(payload, "utf8") }, options));
@@ -13541,7 +13684,7 @@ function str(value) {
13541
13684
  // src/core/agent/reply.ts
13542
13685
  function replyForOutcome(outcome, limits, agentName) {
13543
13686
  const attached = attachedWork(outcome, limits);
13544
- const failed = (errorCode2, text2) => ({ status: "FAILED", errorCode: errorCode2, reply: clip(text2, limits.textMaxCharacters), ...attached });
13687
+ const failed = (errorCode3, text2) => ({ status: "FAILED", errorCode: errorCode3, reply: clip(text2, limits.textMaxCharacters), ...attached });
13545
13688
  switch (outcome.kind) {
13546
13689
  case "timeout":
13547
13690
  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 +13723,13 @@ function schemaAnswer(value, textMaxCharacters) {
13580
13723
  if (!isStringArray2(openDocumentUuids) || !isStringArray2(openCardUuids)) return void 0;
13581
13724
  return { reply, openDocumentUuids, openCardUuids };
13582
13725
  }
13583
- function attachedWork(outcome, limits, open2) {
13726
+ function attachedWork(outcome, limits, open3) {
13584
13727
  const facts = outcome.kind === "result" ? outcome.facts : void 0;
13585
13728
  const seen = (uuids) => (uuids ?? []).filter((uuid) => facts?.seen.includes(uuid));
13586
- const documentUuids = unique([...facts?.documents ?? [], ...seen(open2?.openDocumentUuids)]).slice(0, limits.documentsMax);
13729
+ const documentUuids = unique([...facts?.documents ?? [], ...seen(open3?.openDocumentUuids)]).slice(0, limits.documentsMax);
13587
13730
  const createdDocumentUuids = (facts?.createdDocuments ?? []).filter((uuid) => documentUuids.includes(uuid));
13588
13731
  const foundDocumentUuids = documentUuids.filter((uuid) => !facts?.documents.includes(uuid));
13589
- const cardUuids = unique([...facts?.cards ?? [], ...seen(open2?.openCardUuids)]).slice(0, limits.documentsMax);
13732
+ const cardUuids = unique([...facts?.cards ?? [], ...seen(open3?.openCardUuids)]).slice(0, limits.documentsMax);
13590
13733
  return {
13591
13734
  documentUuids,
13592
13735
  ...createdDocumentUuids.length > 0 ? { createdDocumentUuids } : {},
@@ -13609,7 +13752,7 @@ function clip(text2, max) {
13609
13752
  }
13610
13753
 
13611
13754
  // src/core/agent/tools.ts
13612
- import { randomUUID as randomUUID4 } from "crypto";
13755
+ import { randomUUID as randomUUID5 } from "crypto";
13613
13756
  var AgentToolError = class extends Error {
13614
13757
  constructor(message2, tool, code, retryable = false) {
13615
13758
  super(message2);
@@ -13635,7 +13778,7 @@ function createAgentTools(input) {
13635
13778
  return found;
13636
13779
  };
13637
13780
  async function logged(tool, bytes, run, as) {
13638
- const callId = randomUUID4();
13781
+ const callId = randomUUID5();
13639
13782
  const started = Date.now();
13640
13783
  input.log.write({ event: "agent_call", callId, op: "tool", tool, ...as ? { agent: as.agent, agentName: as.name } : {}, bytes });
13641
13784
  let outcome = { ok: false, error: "no response" };
@@ -14526,37 +14669,37 @@ function lastRecord(text2, accept) {
14526
14669
  for (let index = lines.length - 1; index >= 0; index -= 1) {
14527
14670
  const line = lines[index]?.trim();
14528
14671
  if (!line?.startsWith("{")) continue;
14529
- let record3;
14672
+ let record4;
14530
14673
  try {
14531
- record3 = JSON.parse(line);
14674
+ record4 = JSON.parse(line);
14532
14675
  } catch {
14533
14676
  continue;
14534
14677
  }
14535
- const accepted = accept(record3);
14678
+ const accepted = accept(record4);
14536
14679
  if (accepted !== void 0) return accepted;
14537
14680
  }
14538
14681
  return void 0;
14539
14682
  }
14540
14683
  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);
14684
+ 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
14685
  }
14543
14686
  var UPGRADE_RESULTS = { upgrade_done: "upgraded", upgrade_failed: "failed", upgrade_refused: "refused" };
14544
14687
  function lastUpgrade(text2) {
14545
- return lastRecord(text2, (record3) => {
14546
- const event = record3.event;
14688
+ return lastRecord(text2, (record4) => {
14689
+ const event = record4.event;
14547
14690
  if (event !== "upgrade_done" && event !== "upgrade_failed" && event !== "upgrade_refused") return void 0;
14548
14691
  const text3 = (value) => typeof value === "string" ? value : "";
14549
14692
  return {
14550
- at: text3(record3.ts),
14693
+ at: text3(record4.ts),
14551
14694
  result: UPGRADE_RESULTS[event],
14552
- from: text3(record3.from),
14553
- to: text3(record3.to),
14554
- ...typeof record3.reason === "string" ? { reason: record3.reason } : {}
14695
+ from: text3(record4.from),
14696
+ to: text3(record4.to),
14697
+ ...typeof record4.reason === "string" ? { reason: record4.reason } : {}
14555
14698
  };
14556
14699
  });
14557
14700
  }
14558
14701
  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;
14702
+ 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
14703
  }
14561
14704
 
14562
14705
  // src/core/term/remoteLimits.ts
@@ -14572,77 +14715,966 @@ function retryWait(attempt, random) {
14572
14715
  // src/core/term/remote.ts
14573
14716
  import { StringDecoder } from "string_decoder";
14574
14717
 
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
- }));
14585
- }
14586
- function sessionsKey(sessions) {
14587
- return JSON.stringify(sessions);
14588
- }
14718
+ // src/core/pc/pcKeys.ts
14719
+ import { readFile as readFile12 } from "fs/promises";
14720
+ import { homedir as homedir4 } from "os";
14721
+ import { join as join8 } from "path";
14589
14722
 
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;
14723
+ // src/core/fs/fileLock.ts
14724
+ import { randomUUID as randomUUID6 } from "crypto";
14725
+ import { link, open as open2, readFile as readFile11, unlink as unlink2 } from "fs/promises";
14726
+ import { dirname as dirname7 } from "path";
14727
+ var FileLockTimeoutError = class extends Error {
14728
+ constructor(lockPath, holderPid) {
14729
+ super(`${lockPath} is held by another ainecto${holderPid !== void 0 ? ` (pid ${holderPid})` : ""} \u2014 try again in a moment.`);
14730
+ this.lockPath = lockPath;
14731
+ this.holderPid = holderPid;
14732
+ }
14733
+ lockPath;
14734
+ holderPid;
14735
+ };
14736
+ var FileLockConflictError = class extends Error {
14737
+ constructor(lockPath, reason) {
14738
+ super(`${lockPath}: ${reason} \u2014 nothing was written.`);
14739
+ this.lockPath = lockPath;
14740
+ }
14741
+ lockPath;
14742
+ };
14743
+ async function withFileLock(lockPath, options, run) {
14744
+ const token = await acquire(lockPath, options);
14745
+ try {
14746
+ return await run();
14747
+ } finally {
14748
+ await release(lockPath, token);
14599
14749
  }
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
- }
14607
- function frameBudget(frameMaxBytes, body) {
14608
- return frameMaxBytes - Buffer.byteLength(JSON.stringify({ ...body, d: "" }), "utf8");
14609
14750
  }
14610
- function base64Length(bytes) {
14611
- return 4 * Math.ceil(bytes / 3);
14751
+ async function acquire(lockPath, options) {
14752
+ await ensurePrivateDir(dirname7(lockPath));
14753
+ const token = randomUUID6();
14754
+ const deadline = Date.now() + options.waitMs;
14755
+ for (; ; ) {
14756
+ if (await create(lockPath, token)) return token;
14757
+ const holder = await readLock(lockPath);
14758
+ if (holder.raw === void 0) continue;
14759
+ if (!holder.content) {
14760
+ 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");
14761
+ }
14762
+ if (isDead(holder.content, options)) {
14763
+ await options.testHooks?.beforeReclaim?.();
14764
+ if (await reclaim(lockPath, holder.raw, token, options)) continue;
14765
+ }
14766
+ if (Date.now() >= deadline) {
14767
+ throw new FileLockTimeoutError(lockPath, holder.content?.pid);
14768
+ }
14769
+ await new Promise((resolve4) => setTimeout(resolve4, options.pollMs));
14770
+ }
14612
14771
  }
14613
-
14614
- // src/core/term/remoteViewer.ts
14615
- var RemoteViewer = class {
14616
- constructor(deps) {
14617
- this.deps = deps;
14618
- this.size = deps.size;
14772
+ async function create(path, token) {
14773
+ const staging = `${path}.${token}.tmp`;
14774
+ const handle = await open2(staging, "wx", PRIVATE_FILE_MODE);
14775
+ try {
14776
+ try {
14777
+ await handle.writeFile(JSON.stringify({ pid: process.pid, token }));
14778
+ await handle.sync();
14779
+ } finally {
14780
+ await handle.close();
14781
+ }
14782
+ await link(staging, path);
14783
+ return true;
14784
+ } catch (error) {
14785
+ if (isNodeError(error, "EEXIST")) return false;
14786
+ throw error;
14787
+ } finally {
14788
+ await unlink2(staging);
14619
14789
  }
14620
- deps;
14621
- stopper = new AbortController();
14622
- dirty = true;
14623
- wakeUp;
14624
- size;
14625
- client;
14626
- get stopped() {
14627
- return this.stopper.signal.aborted;
14790
+ }
14791
+ async function readLock(path) {
14792
+ let raw;
14793
+ try {
14794
+ raw = await readFile11(path, "utf8");
14795
+ } catch (error) {
14796
+ if (isNodeError(error, "ENOENT")) return { raw: void 0, content: void 0 };
14797
+ throw error;
14628
14798
  }
14629
- stop() {
14630
- if (this.stopped) return;
14631
- this.stopper.abort();
14632
- this.nudge();
14633
- this.client?.close();
14799
+ try {
14800
+ const value = JSON.parse(raw);
14801
+ const content = value && Number.isSafeInteger(value.pid) && typeof value.token === "string" ? { pid: value.pid, token: value.token } : void 0;
14802
+ return { raw, content };
14803
+ } catch {
14804
+ return { raw, content: void 0 };
14634
14805
  }
14635
- /** 세션 크기가 바뀌었다(웹 패널 크기 → 데몬 set-size) — 다시 올린다. */
14636
- setSize(size) {
14637
- this.size = size;
14638
- this.refresh();
14806
+ }
14807
+ function isDead(holder, options) {
14808
+ return !(options.isAlive ?? processAlive)(holder.pid);
14809
+ }
14810
+ async function reclaim(lockPath, observed, token, options) {
14811
+ const guard = `${lockPath}.reclaim`;
14812
+ if (!await create(guard, token)) {
14813
+ const other = await readLock(guard);
14814
+ if (other.raw !== void 0 && (!other.content || isDead(other.content, options))) {
14815
+ 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`);
14816
+ }
14817
+ return other.raw === void 0;
14639
14818
  }
14640
- /** 다시 그려 보낸다(다시 열린 링크·목록을 올린 뒤). */
14641
- refresh() {
14642
- this.dirty = true;
14643
- this.nudge();
14819
+ try {
14820
+ await options.testHooks?.duringReclaim?.();
14821
+ const now = await readLock(lockPath);
14822
+ if (now.raw === observed && now.content && isDead(now.content, options)) {
14823
+ await unlink2(lockPath);
14824
+ }
14825
+ } finally {
14826
+ await unlink2(guard);
14644
14827
  }
14645
- async run() {
14828
+ return true;
14829
+ }
14830
+ async function release(lockPath, token) {
14831
+ if ((await readLock(lockPath)).content?.token !== token) return;
14832
+ try {
14833
+ await unlink2(lockPath);
14834
+ } catch (error) {
14835
+ if (!isNodeError(error, "ENOENT")) throw error;
14836
+ }
14837
+ }
14838
+
14839
+ // src/core/term/e2e.ts
14840
+ import { timingSafeEqual as timingSafeEqual2, webcrypto } from "crypto";
14841
+ var subtle = webcrypto.subtle;
14842
+ var VERSION = "ainecto-e2e-v1";
14843
+ var PAIR_LABEL = "ainecto-pair-v1";
14844
+ var PAIR_DONE_LABEL = "ainecto-pair-v1/done";
14845
+ var PAIR_CODE_INFO = { a: "ainecto-pair-code-A", b: "ainecto-pair-code-B" };
14846
+ var REGISTER_INFO = { browser: "ainecto-register-v1 browser", pc: "ainecto-register-v1 pc", account: "ainecto-register-v1 account" };
14847
+ var REGISTER_OFFER_LABEL = "ainecto-register-v1/offer";
14848
+ var REGISTER_REVEAL_LABEL = "ainecto-register-v1/reveal";
14849
+ var REGISTER_TAG_BYTES = 8;
14850
+ var KEY_INFO = { browserToPc: "ainecto-e2e-v1 b2p", pcToBrowser: "ainecto-e2e-v1 p2b", connId: "ainecto-e2e-v1 conn-id" };
14851
+ var PAIR_CODE_LIMIT = 4294e6;
14852
+ var MAX_MESSAGES_PER_KEY = 2 ** 32;
14853
+ var PUBLIC_KEY_BYTES = 65;
14854
+ var NONCE_SEED_BYTES = 32;
14855
+ var SIGNATURE_BYTES = 64;
14856
+ var CONN_ID_BYTES = 16;
14857
+ var PAIR_CODE_DIGITS = 6;
14858
+ var E2eError = class extends Error {
14859
+ constructor(code, message2) {
14860
+ super(message2);
14861
+ this.code = code;
14862
+ }
14863
+ code;
14864
+ };
14865
+ var utf8 = (text2) => new TextEncoder().encode(text2);
14866
+ function concatBytes(...parts) {
14867
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
14868
+ let offset = 0;
14869
+ for (const part of parts) {
14870
+ out.set(part, offset);
14871
+ offset += part.length;
14872
+ }
14873
+ return out;
14874
+ }
14875
+ function enc(...fields) {
14876
+ return concatBytes(...fields.map((field) => {
14877
+ const bytes = typeof field === "string" ? utf8(field) : field;
14878
+ if (bytes.length > 65535) {
14879
+ throw new E2eError("E2E_BAD_INPUT", `a field is ${bytes.length} bytes (max 65535).`);
14880
+ }
14881
+ const out = new Uint8Array(2 + bytes.length);
14882
+ new DataView(out.buffer).setUint16(0, bytes.length, false);
14883
+ out.set(bytes, 2);
14884
+ return out;
14885
+ }));
14886
+ }
14887
+ function u64be(value) {
14888
+ const out = new Uint8Array(8);
14889
+ new DataView(out.buffer).setBigUint64(0, BigInt(value), false);
14890
+ return out;
14891
+ }
14892
+ async function sha256(data) {
14893
+ return new Uint8Array(await subtle.digest("SHA-256", data));
14894
+ }
14895
+ function randomBytes3(length = NONCE_SEED_BYTES) {
14896
+ return webcrypto.getRandomValues(new Uint8Array(length));
14897
+ }
14898
+ function expectLength(name, bytes, length) {
14899
+ if (bytes.length !== length) {
14900
+ throw new E2eError("E2E_BAD_INPUT", `${name} must be ${length} bytes, got ${bytes.length}.`);
14901
+ }
14902
+ }
14903
+ var ECDSA = { name: "ECDSA", namedCurve: "P-256" };
14904
+ var ECDH = { name: "ECDH", namedCurve: "P-256" };
14905
+ var SIGN_PARAMS = { name: "ECDSA", hash: "SHA-256" };
14906
+ function base64url(bytes) {
14907
+ return Buffer.from(bytes).toString("base64url");
14908
+ }
14909
+ function fromBase64url(name, text2, length) {
14910
+ if (!/^[A-Za-z0-9_-]+$/.test(text2)) {
14911
+ throw new E2eError("E2E_BAD_INPUT", `${name} is not base64url.`);
14912
+ }
14913
+ const bytes = new Uint8Array(Buffer.from(text2, "base64url"));
14914
+ expectLength(name, bytes, length);
14915
+ return bytes;
14916
+ }
14917
+ function asPublicJwk(raw) {
14918
+ if (!raw || typeof raw !== "object") return void 0;
14919
+ const value = raw;
14920
+ if (value.kty !== "EC" || value.crv !== "P-256" || typeof value.x !== "string" || typeof value.y !== "string") return void 0;
14921
+ try {
14922
+ fromBase64url("x", value.x, 32);
14923
+ fromBase64url("y", value.y, 32);
14924
+ } catch {
14925
+ return void 0;
14926
+ }
14927
+ return { kty: "EC", crv: "P-256", x: value.x, y: value.y };
14928
+ }
14929
+ function asPrivateJwk(raw) {
14930
+ const pub = asPublicJwk(raw);
14931
+ const d = raw?.d;
14932
+ if (!pub || typeof d !== "string") return void 0;
14933
+ try {
14934
+ fromBase64url("d", d, 32);
14935
+ } catch {
14936
+ return void 0;
14937
+ }
14938
+ return { ...pub, d };
14939
+ }
14940
+ function publicRawFromJwk(jwk) {
14941
+ return concatBytes(Uint8Array.of(4), fromBase64url("x", jwk.x, 32), fromBase64url("y", jwk.y, 32));
14942
+ }
14943
+ function publicJwkFromRaw(raw) {
14944
+ expectLength("public key", raw, PUBLIC_KEY_BYTES);
14945
+ if (raw[0] !== 4) {
14946
+ throw new E2eError("E2E_BAD_INPUT", "public key must be an uncompressed P-256 point (0x04 \u2016 X \u2016 Y).");
14947
+ }
14948
+ return { kty: "EC", crv: "P-256", x: base64url(raw.subarray(1, 33)), y: base64url(raw.subarray(33, 65)) };
14949
+ }
14950
+ async function generateSigningJwk() {
14951
+ const pair2 = await subtle.generateKey(ECDSA, true, ["sign", "verify"]);
14952
+ const jwk = asPrivateJwk(await subtle.exportKey("jwk", pair2.privateKey));
14953
+ if (!jwk) {
14954
+ throw new Error("WebCrypto returned an unexpected P-256 JWK.");
14955
+ }
14956
+ return jwk;
14957
+ }
14958
+ async function importSigningKey(jwk) {
14959
+ return await subtle.importKey("jwk", { ...jwk }, ECDSA, false, ["sign"]);
14960
+ }
14961
+ async function assertSigningPublicKey(publicKey) {
14962
+ try {
14963
+ await subtle.importKey("jwk", { ...publicKey }, ECDSA, false, ["verify"]);
14964
+ } catch {
14965
+ throw new E2eError("E2E_BAD_INPUT", "public key is not a valid P-256 point.");
14966
+ }
14967
+ }
14968
+ async function signBytes(privateKey, data) {
14969
+ return new Uint8Array(await subtle.sign(SIGN_PARAMS, privateKey, data));
14970
+ }
14971
+ async function verifyBytes(publicKey, signature, data) {
14972
+ if (signature.length !== SIGNATURE_BYTES) return false;
14973
+ try {
14974
+ const key = await subtle.importKey("jwk", { ...publicKey }, ECDSA, false, ["verify"]);
14975
+ return await subtle.verify(SIGN_PARAMS, key, signature, data);
14976
+ } catch {
14977
+ return false;
14978
+ }
14979
+ }
14980
+ async function generateEphemeral() {
14981
+ const pair2 = await subtle.generateKey(ECDH, false, ["deriveBits"]);
14982
+ return { privateKey: pair2.privateKey, publicRaw: new Uint8Array(await subtle.exportKey("raw", pair2.publicKey)) };
14983
+ }
14984
+ var USER_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
14985
+ function transcriptUserId(raw) {
14986
+ const userId = raw.toLowerCase();
14987
+ expectUserId(userId);
14988
+ return userId;
14989
+ }
14990
+ function expectUserId(userId) {
14991
+ if (!USER_ID.test(userId)) {
14992
+ throw new E2eError("E2E_BAD_INPUT", "userId must be a lowercase 36-character UUID.");
14993
+ }
14994
+ }
14995
+ async function browserKeyIdOf(browserPublicRaw) {
14996
+ expectLength("browserPub", browserPublicRaw, PUBLIC_KEY_BYTES);
14997
+ return Buffer.from((await sha256(browserPublicRaw)).subarray(0, 16)).toString("hex");
14998
+ }
14999
+ function pairCodeInput(raw) {
15000
+ const trimmed = raw.trim();
15001
+ if (trimmed === "") return { kind: "empty" };
15002
+ return new RegExp(`^[0-9]{${PAIR_CODE_DIGITS}}$`).test(trimmed) ? { kind: "code", code: trimmed } : { kind: "invalid" };
15003
+ }
15004
+ async function pairCommitment(pcPublicRaw, nP) {
15005
+ expectLength("pcPub", pcPublicRaw, PUBLIC_KEY_BYTES);
15006
+ expectLength("nP", nP, NONCE_SEED_BYTES);
15007
+ return await sha256(concatBytes(pcPublicRaw, nP));
15008
+ }
15009
+ async function pairTranscript(input) {
15010
+ expectUserId(input.userId);
15011
+ expectLength("pcPub", input.pcPublicRaw, PUBLIC_KEY_BYTES);
15012
+ expectLength("browserPub", input.browserPublicRaw, PUBLIC_KEY_BYTES);
15013
+ expectLength("nP", input.nP, NONCE_SEED_BYTES);
15014
+ expectLength("nB", input.nB, NONCE_SEED_BYTES);
15015
+ return await sha256(enc(PAIR_LABEL, input.userId, input.pcId, input.pcPublicRaw, input.browserPublicRaw, input.nP, input.nB));
15016
+ }
15017
+ function pairCodeFromBlock(block) {
15018
+ expectLength("code block", block, 32);
15019
+ const view = new DataView(block.buffer, block.byteOffset, block.byteLength);
15020
+ for (let offset = 0; offset < 32; offset += 4) {
15021
+ const value = view.getUint32(offset, false);
15022
+ if (value < PAIR_CODE_LIMIT) {
15023
+ return String(value % 10 ** PAIR_CODE_DIGITS).padStart(PAIR_CODE_DIGITS, "0");
15024
+ }
15025
+ }
15026
+ return void 0;
15027
+ }
15028
+ async function pairCodes(transcript) {
15029
+ expectLength("transcript", transcript, 32);
15030
+ const prk = await subtle.importKey("raw", transcript, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
15031
+ const code = async (info) => {
15032
+ const block = new Uint8Array(await subtle.sign("HMAC", prk, concatBytes(utf8(info), Uint8Array.of(1))));
15033
+ const value = pairCodeFromBlock(block);
15034
+ if (value === void 0) {
15035
+ throw new E2eError("E2E_PAIR_CODE_UNAVAILABLE", "No usable registration code in this attempt \u2014 run `ainecto pair` again.");
15036
+ }
15037
+ return value;
15038
+ };
15039
+ return { a: await code(PAIR_CODE_INFO.a), b: await code(PAIR_CODE_INFO.b) };
15040
+ }
15041
+ function pairDoneInput(transcript) {
15042
+ expectLength("transcript", transcript, 32);
15043
+ return enc(PAIR_DONE_LABEL, transcript);
15044
+ }
15045
+ async function registerKeys(secret) {
15046
+ expectLength("register secret", secret, NONCE_SEED_BYTES);
15047
+ const ikm = await subtle.importKey("raw", secret, "HKDF", false, ["deriveBits"]);
15048
+ const derive = async (info) => new Uint8Array(await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: utf8(info) }, ikm, 256));
15049
+ return { browser: await derive(REGISTER_INFO.browser), pc: await derive(REGISTER_INFO.pc), account: await derive(REGISTER_INFO.account) };
15050
+ }
15051
+ async function hmac(key, data) {
15052
+ expectLength("mac key", key, 32);
15053
+ const imported = await subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
15054
+ return new Uint8Array(await subtle.sign("HMAC", imported, data));
15055
+ }
15056
+ async function registerOfferMac(browserKey, input) {
15057
+ expectLength("commit", input.commit, 32);
15058
+ expectLength("browserPub", input.browserPublicRaw, PUBLIC_KEY_BYTES);
15059
+ expectLength("nB", input.nB, NONCE_SEED_BYTES);
15060
+ return await hmac(browserKey, enc(
15061
+ REGISTER_OFFER_LABEL,
15062
+ input.userId,
15063
+ input.pcId,
15064
+ input.attemptId,
15065
+ input.commit,
15066
+ input.browserPublicRaw,
15067
+ input.keyId,
15068
+ input.nB,
15069
+ input.name
15070
+ ));
15071
+ }
15072
+ async function registerRevealMac(pcKey, input) {
15073
+ expectLength("transcript", input.transcript, 32);
15074
+ return await hmac(pcKey, enc(REGISTER_REVEAL_LABEL, input.transcript, input.attemptId));
15075
+ }
15076
+ async function registerTag(accountKey2, userId) {
15077
+ return base64url((await hmac(accountKey2, utf8(userId))).subarray(0, REGISTER_TAG_BYTES));
15078
+ }
15079
+ var REGISTER_PATH = "/api/v1/public/term-register";
15080
+ function registerFragment(input) {
15081
+ expectLength("register secret", input.secret, NONCE_SEED_BYTES);
15082
+ return `1.${input.pcId}.${input.tag}.${base64url(input.secret)}`;
15083
+ }
15084
+ function macEquals(a, b) {
15085
+ return a.length === b.length && timingSafeEqual2(a, b);
15086
+ }
15087
+ function assertHello(hello) {
15088
+ expectUserId(hello.userId);
15089
+ expectLength("eB", hello.eB, PUBLIC_KEY_BYTES);
15090
+ expectLength("nB", hello.nB, NONCE_SEED_BYTES);
15091
+ }
15092
+ function helloSignatureInput(hello) {
15093
+ assertHello(hello);
15094
+ return enc(VERSION, "browser", "hello", hello.userId, hello.pcId, hello.channel, hello.browserKeyId, hello.eB, hello.nB);
15095
+ }
15096
+ async function channelTranscript(input) {
15097
+ const { hello } = input;
15098
+ assertHello(hello);
15099
+ expectLength("pcPub", input.pcPublicRaw, PUBLIC_KEY_BYTES);
15100
+ expectLength("browserPub", input.browserPublicRaw, PUBLIC_KEY_BYTES);
15101
+ expectLength("eP", input.eP, PUBLIC_KEY_BYTES);
15102
+ expectLength("nP'", input.nP, NONCE_SEED_BYTES);
15103
+ return await sha256(enc(
15104
+ VERSION,
15105
+ hello.userId,
15106
+ hello.pcId,
15107
+ hello.channel,
15108
+ hello.browserKeyId,
15109
+ input.pcPublicRaw,
15110
+ input.browserPublicRaw,
15111
+ hello.eB,
15112
+ hello.nB,
15113
+ input.eP,
15114
+ input.nP
15115
+ ));
15116
+ }
15117
+ async function deriveChannelSecrets(input) {
15118
+ expectLength("peer ephemeral key", input.peerPublicRaw, PUBLIC_KEY_BYTES);
15119
+ expectLength("transcript", input.transcript, 32);
15120
+ let peer;
15121
+ try {
15122
+ peer = await subtle.importKey("raw", input.peerPublicRaw, ECDH, false, []);
15123
+ } catch {
15124
+ throw new E2eError("E2E_BAD_INPUT", "peer ephemeral key is not a valid P-256 point.");
15125
+ }
15126
+ const shared = new Uint8Array(await subtle.deriveBits({ name: "ECDH", public: peer }, input.own, 256));
15127
+ const ikm = await subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);
15128
+ const derive = async (info, bytes) => new Uint8Array(await subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: input.transcript, info: utf8(info) }, ikm, bytes * 8));
15129
+ return {
15130
+ browserToPc: await derive(KEY_INFO.browserToPc, 32),
15131
+ pcToBrowser: await derive(KEY_INFO.pcToBrowser, 32),
15132
+ connId: await derive(KEY_INFO.connId, CONN_ID_BYTES)
15133
+ };
15134
+ }
15135
+ async function importMessageKey(secret) {
15136
+ expectLength("message key", secret, 32);
15137
+ return await subtle.importKey("raw", secret, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
15138
+ }
15139
+ function assertCounter(counter) {
15140
+ if (!Number.isSafeInteger(counter) || counter < 0 || counter >= MAX_MESSAGES_PER_KEY) {
15141
+ throw new E2eError("E2E_COUNTER_REJECTED", `counter must be an integer from 0 to ${MAX_MESSAGES_PER_KEY - 1} (then start a new hello).`);
15142
+ }
15143
+ }
15144
+ function messageNonce(counter) {
15145
+ assertCounter(counter);
15146
+ return concatBytes(new Uint8Array(4), u64be(counter));
15147
+ }
15148
+ function messageAad(header) {
15149
+ assertCounter(header.counter);
15150
+ expectLength("connId", header.connId, CONN_ID_BYTES);
15151
+ return enc(VERSION, header.type, header.connId, header.pcId, header.session, header.operationId, header.projectUuid, u64be(header.counter));
15152
+ }
15153
+ async function sealMessage(key, header, plaintext) {
15154
+ return new Uint8Array(await subtle.encrypt(
15155
+ { name: "AES-GCM", iv: messageNonce(header.counter), additionalData: messageAad(header), tagLength: 128 },
15156
+ key,
15157
+ plaintext
15158
+ ));
15159
+ }
15160
+ async function openMessage(key, header, ciphertext, state) {
15161
+ assertCounter(header.counter);
15162
+ const inOrder = state.order === "exact" ? header.counter === state.next : header.counter >= state.next;
15163
+ if (!inOrder) {
15164
+ throw new E2eError(
15165
+ "E2E_COUNTER_REJECTED",
15166
+ `counter ${header.counter} rejected (${state.order === "exact" ? `expected exactly ${state.next}` : `expected ${state.next} or more`}).`
15167
+ );
15168
+ }
15169
+ let plaintext;
15170
+ try {
15171
+ plaintext = await subtle.decrypt(
15172
+ { name: "AES-GCM", iv: messageNonce(header.counter), additionalData: messageAad(header), tagLength: 128 },
15173
+ key,
15174
+ ciphertext
15175
+ );
15176
+ } catch {
15177
+ throw new E2eError("E2E_DECRYPT_FAILED", "message failed authentication (wrong key, header or ciphertext).");
15178
+ }
15179
+ return { plaintext: new Uint8Array(plaintext), state: { order: state.order, next: header.counter + 1 } };
15180
+ }
15181
+
15182
+ // src/core/pc/pcKeys.ts
15183
+ var BROWSER_NAME_MAX = 40;
15184
+ var DEFAULT_BROWSER_NAME = "Browser";
15185
+ function pcKeysPath(home = homedir4()) {
15186
+ return join8(home, ".ainecto", "pc-keys.json");
15187
+ }
15188
+ function normalizePcKeys(raw) {
15189
+ const accounts = {};
15190
+ const stored = raw && typeof raw === "object" ? raw.accounts : void 0;
15191
+ if (stored && typeof stored === "object") {
15192
+ for (const [key, entry] of Object.entries(stored)) {
15193
+ const value = entry && typeof entry === "object" ? entry : void 0;
15194
+ const pcKey = asPrivateJwk(value?.pcKey);
15195
+ if (!pcKey) continue;
15196
+ const browsers = Array.isArray(value?.browsers) ? value.browsers.flatMap((item) => {
15197
+ const browser = asPairedBrowser(item);
15198
+ return browser ? [browser] : [];
15199
+ }) : [];
15200
+ const pending = value?.pendingTurnOff;
15201
+ accounts[key] = typeof pending?.removedAt === "string" ? { pcKey, browsers, pendingTurnOff: {
15202
+ removedAt: pending.removedAt,
15203
+ groups: Array.isArray(pending.groups) ? pending.groups.flatMap(asPcGroup) : [],
15204
+ removals: Array.isArray(pending.removals) ? pending.removals.flatMap(asPendingRemoval) : []
15205
+ } } : { pcKey, browsers };
15206
+ }
15207
+ }
15208
+ return { accounts };
15209
+ }
15210
+ function asPcGroup(raw) {
15211
+ const value = raw && typeof raw === "object" ? raw : void 0;
15212
+ const positive = (n) => Number.isSafeInteger(n) && n > 0;
15213
+ return value && typeof value.session === "string" && positive(value.pid) && positive(value.pgid) ? [{ session: value.session, pid: value.pid, pgid: value.pgid }] : [];
15214
+ }
15215
+ function asPendingRemoval(raw) {
15216
+ const value = raw && typeof raw === "object" ? raw : void 0;
15217
+ if (!value || typeof value.keyId !== "string" || value.keyId === "" || typeof value.name !== "string") return [];
15218
+ const removalId = typeof value.removalId === "string" && value.removalId !== "" ? value.removalId : value.keyId;
15219
+ return [{ removalId, keyId: value.keyId, name: value.name }];
15220
+ }
15221
+ function asPairedBrowser(raw) {
15222
+ if (!raw || typeof raw !== "object") return void 0;
15223
+ const value = raw;
15224
+ const publicJwk = asPublicJwk(value.publicJwk);
15225
+ if (!publicJwk || typeof value.keyId !== "string" || value.keyId === "" || typeof value.name !== "string" || typeof value.pairedAt !== "string") {
15226
+ return void 0;
15227
+ }
15228
+ return { keyId: value.keyId, publicJwk, name: value.name, pairedAt: value.pairedAt };
15229
+ }
15230
+ async function loadPcKeys(path) {
15231
+ let raw;
15232
+ try {
15233
+ raw = await readFile12(path, "utf8");
15234
+ } catch (error) {
15235
+ if (isNodeError(error, "ENOENT")) {
15236
+ return { accounts: {} };
15237
+ }
15238
+ throw error;
15239
+ }
15240
+ try {
15241
+ return normalizePcKeys(JSON.parse(raw));
15242
+ } catch (error) {
15243
+ throw new Error(`${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}). Delete it and register your browsers again with \`ainecto pair\`.`);
15244
+ }
15245
+ }
15246
+ var PC_KEYS_LOCK = { waitMs: 5e3, pollMs: 50 };
15247
+ async function updatePcKeys(path, change, lock = PC_KEYS_LOCK) {
15248
+ return await withFileLock(`${path}.lock`, lock, async () => {
15249
+ const current = await loadPcKeys(path);
15250
+ const next = await change(current);
15251
+ if (next === void 0) return current;
15252
+ await writePrivateFileAtomic(path, `${JSON.stringify(next, null, 2)}
15253
+ `);
15254
+ return next;
15255
+ });
15256
+ }
15257
+ function browserNameOf(raw) {
15258
+ const cleaned = [...raw.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, "").trim()].slice(0, BROWSER_NAME_MAX).join("").trim();
15259
+ return cleaned === "" ? DEFAULT_BROWSER_NAME : cleaned;
15260
+ }
15261
+ function uniqueName(account2, wanted, keyId) {
15262
+ const named = [...account2.browsers, ...account2.pendingTurnOff?.removals ?? []];
15263
+ const taken = new Set(named.filter((item) => item.keyId !== keyId).map((item) => item.name));
15264
+ if (!taken.has(wanted)) return wanted;
15265
+ for (let n = 2; ; n += 1) {
15266
+ const candidate = `${wanted} (${n})`;
15267
+ if (!taken.has(candidate)) return candidate;
15268
+ }
15269
+ }
15270
+ function withBrowser(keys, account2, pcKey, browser) {
15271
+ const current = keys.accounts[account2] ?? { pcKey, browsers: [] };
15272
+ const others = current.browsers.filter((item) => item.keyId !== browser.keyId);
15273
+ const added = { ...browser, name: uniqueName(current, browser.name, browser.keyId) };
15274
+ return { accounts: { ...keys.accounts, [account2]: { ...current, browsers: [...others, added] } } };
15275
+ }
15276
+ function withoutBrowser(keys, account2, keyIdOrName) {
15277
+ const current = keys.accounts[account2];
15278
+ const removed = current?.browsers.find((item) => item.keyId === keyIdOrName) ?? current?.browsers.find((item) => item.name === keyIdOrName);
15279
+ if (!current || !removed) {
15280
+ return { keys, removed: void 0 };
15281
+ }
15282
+ return {
15283
+ keys: { accounts: { ...keys.accounts, [account2]: { ...current, browsers: current.browsers.filter((item) => item !== removed) } } },
15284
+ removed
15285
+ };
15286
+ }
15287
+ function withPendingTurnOff(keys, account2, add) {
15288
+ const current = keys.accounts[account2];
15289
+ if (!current) return keys;
15290
+ const { pendingTurnOff: previous, ...rest } = current;
15291
+ const known = previous?.groups ?? [];
15292
+ const fresh = add.groups.filter((group) => !known.some((item) => sameGroup(item, group)));
15293
+ const removals = previous?.removals ?? [];
15294
+ const removal = add.removal && !removals.some((item) => item.removalId === add.removal?.removalId) ? [add.removal] : [];
15295
+ if (previous && fresh.length === 0 && removal.length === 0) return keys;
15296
+ const pendingTurnOff = {
15297
+ removedAt: previous?.removedAt ?? add.at.toISOString(),
15298
+ groups: [...known, ...fresh],
15299
+ removals: [...removals, ...removal]
15300
+ };
15301
+ return { accounts: { ...keys.accounts, [account2]: { ...rest, pendingTurnOff } } };
15302
+ }
15303
+ function pendingRemovalOf(account2, keyIdOrName) {
15304
+ const removals = account2?.pendingTurnOff?.removals ?? [];
15305
+ return removals.find((item) => item.keyId === keyIdOrName) ?? removals.find((item) => item.name === keyIdOrName);
15306
+ }
15307
+ function withTurnOffConfirmed(keys, account2, done) {
15308
+ const current = keys.accounts[account2];
15309
+ if (!current?.pendingTurnOff) return keys;
15310
+ const { pendingTurnOff: previous, ...rest } = current;
15311
+ const groups = previous.groups.filter((group) => !done.groups.some((item) => sameGroup(item, group)));
15312
+ const removals = previous.removals.filter((item) => item.removalId !== done.removalId);
15313
+ if (groups.length === previous.groups.length && removals.length === previous.removals.length) return keys;
15314
+ const left = groups.length > 0 || removals.length > 0;
15315
+ return { accounts: { ...keys.accounts, [account2]: left ? { ...rest, pendingTurnOff: { ...previous, groups, removals } } : rest } };
15316
+ }
15317
+ function sameGroup(a, b) {
15318
+ return a.pid === b.pid && a.pgid === b.pgid;
15319
+ }
15320
+ function withoutEndpointKeys(keys, endpoint) {
15321
+ return { accounts: Object.fromEntries(Object.entries(keys.accounts).filter(([key]) => !isEndpointAccount(key, endpoint))) };
15322
+ }
15323
+
15324
+ // src/core/term/remoteChannel.ts
15325
+ import { createHash as createHash6 } from "crypto";
15326
+ var HANDSHAKE_TTL_MS = 3e4;
15327
+ var HANDSHAKE_MAX = 4;
15328
+ var ACTIVE_CHANNEL_MAX = 8;
15329
+ var ANSWER_CODES = ["TERM_NO_SESSION", "TERM_SESSION_EXISTS", "TERM_BAD_REQUEST", "SESSION_REPLACED", "REMOTE_OFF"];
15330
+ function answerCodeOf(code) {
15331
+ return ANSWER_CODES.includes(code) ? code : "TERM_FAILED";
15332
+ }
15333
+ var COMMAND_KINDS = ["confirm", "input", "key", "resize", "create", "kill", "label"];
15334
+ var ChannelSealError = class extends Error {
15335
+ constructor(reason, message2) {
15336
+ super(message2);
15337
+ this.reason = reason;
15338
+ }
15339
+ reason;
15340
+ };
15341
+ var ChannelBook = class {
15342
+ constructor(pcId, now = Date.now) {
15343
+ this.pcId = pcId;
15344
+ this.now = now;
15345
+ }
15346
+ pcId;
15347
+ now;
15348
+ channels = /* @__PURE__ */ new Map();
15349
+ /** 장부에 있나(미확정 포함). */
15350
+ has(channelId) {
15351
+ return this.channels.has(channelId);
15352
+ }
15353
+ isActive(channelId) {
15354
+ return this.channels.get(channelId)?.active === true;
15355
+ }
15356
+ activeIds() {
15357
+ return [...this.channels.values()].filter((channel) => channel.active).map((channel) => channel.channelId);
15358
+ }
15359
+ browserOf(channelId) {
15360
+ return this.channels.get(channelId)?.browser;
15361
+ }
15362
+ /** 활성 채널의 연속 실행 확인 지점 — 없으면 undefined. */
15363
+ executedThrough(channelId) {
15364
+ const channel = this.channels.get(channelId);
15365
+ return channel?.active ? channel.executedThrough : void 0;
15366
+ }
15367
+ /** 웹→PC n 번 실행이 확인됐다 — 연속일 때만 오른다(건너뛰지 않는다, §14-6 1). 올랐으면 true. */
15368
+ executed(channelId, n) {
15369
+ const channel = this.channels.get(channelId);
15370
+ if (!channel?.active || n !== channel.executedThrough + 1) return false;
15371
+ channel.executedThrough = n;
15372
+ return true;
15373
+ }
15374
+ /** 채널을 장부에서 지운다(닫힘·웹 닫음·키 폐기). 있었으면 true. */
15375
+ drop(channelId) {
15376
+ return this.channels.delete(channelId);
15377
+ }
15378
+ /** 모두 지운다(원격 끔·링크 다시 열기) — 지운 id 들. */
15379
+ dropAll() {
15380
+ const ids = [...this.channels.keys()];
15381
+ this.channels.clear();
15382
+ return ids;
15383
+ }
15384
+ /** 기한(C-E8)이 지난 미확정 handshake 를 지운다 — 지운 id 들(다리가 HANDSHAKE_EXPIRED 로 닫는다). */
15385
+ expired() {
15386
+ const now = this.now();
15387
+ const ids = [...this.channels.values()].filter((channel) => !channel.active && now >= channel.expiresAt).map((channel) => channel.channelId);
15388
+ for (const id of ids) this.channels.delete(id);
15389
+ return ids;
15390
+ }
15391
+ /** hello 하나(§11-2·§13-4·A4). 신뢰가 없으면(짝짓지 않음·계정 모름) PAIRING_REQUIRED. */
15392
+ async hello(channelId, raw, trust) {
15393
+ if (this.channels.has(channelId)) return { type: "ignored" };
15394
+ const hello = wireHello(raw);
15395
+ if (!trust || !hello) return { type: "refuse" };
15396
+ const browser = trust.browsers.find((item) => item.keyId === hello.browserKeyId);
15397
+ if (!browser) return { type: "refuse" };
15398
+ const fields = { userId: trust.userId, pcId: this.pcId, channel: hello.channel, browserKeyId: hello.browserKeyId, eB: hello.eB, nB: hello.nB };
15399
+ if (!await verifyBytes(browser.publicJwk, hello.sig, helloSignatureInput(fields))) return { type: "refuse" };
15400
+ const now = this.now();
15401
+ const pending = [...this.channels.values()].filter((channel) => !channel.active && now < channel.expiresAt).length;
15402
+ if (pending >= HANDSHAKE_MAX) return { type: "close", reason: "HANDSHAKE_LIMIT" };
15403
+ const ephemeral = await generateEphemeral();
15404
+ const nP = randomBytes3(NONCE_SEED_BYTES);
15405
+ const transcript = await channelTranscript({
15406
+ hello: fields,
15407
+ pcPublicRaw: publicRawFromJwk(trust.pcKey),
15408
+ browserPublicRaw: publicRawFromJwk(browser.publicJwk),
15409
+ eP: ephemeral.publicRaw,
15410
+ nP
15411
+ });
15412
+ let secrets;
15413
+ try {
15414
+ secrets = await deriveChannelSecrets({ own: ephemeral.privateKey, peerPublicRaw: hello.eB, transcript });
15415
+ } catch (error) {
15416
+ if (error instanceof E2eError) return { type: "refuse" };
15417
+ throw error;
15418
+ }
15419
+ const sig = await signBytes(await importSigningKey(trust.pcKey), transcript);
15420
+ const channelBrowser = { keyId: browser.keyId, name: browser.name };
15421
+ this.channels.set(channelId, {
15422
+ channelId,
15423
+ browser: channelBrowser,
15424
+ connId: secrets.connId,
15425
+ b2p: await importMessageKey(secrets.browserToPc),
15426
+ p2b: await importMessageKey(secrets.pcToBrowser),
15427
+ receive: { order: "exact", next: 0 },
15428
+ sendNext: 0,
15429
+ active: false,
15430
+ expiresAt: now + HANDSHAKE_TTL_MS,
15431
+ executedThrough: -1,
15432
+ last: void 0
15433
+ });
15434
+ return { type: "welcome", welcome: { eP: b64u(ephemeral.publicRaw), nP: b64u(nP), sig: b64u(sig) }, browser: channelBrowser };
15435
+ }
15436
+ /** 웹→PC 명령 하나(§14-3). 닫는 결과면 장부에서 이미 지웠다. */
15437
+ async receive(wire) {
15438
+ const channel = this.channels.get(wire.channelId);
15439
+ if (!channel) return { type: "unknown" };
15440
+ const close = (reason) => {
15441
+ this.channels.delete(wire.channelId);
15442
+ return { type: "close", reason };
15443
+ };
15444
+ if (!channel.active && this.now() >= channel.expiresAt) return close("HANDSHAKE_EXPIRED");
15445
+ const digest = createHash6("sha256").update(wire.c, "utf8").digest("hex");
15446
+ if (channel.last && wire.n === channel.last.n && digest === channel.last.digest) return { type: "duplicate" };
15447
+ if (wire.n >= MAX_MESSAGES_PER_KEY) return close("MESSAGE_LIMIT");
15448
+ if (wire.n !== channel.receive.next) return close("CHANNEL_OUT_OF_ORDER");
15449
+ if (wire.kind === "confirm" !== (wire.n === 0)) return close("CHANNEL_OUT_OF_ORDER");
15450
+ const ciphertext = fromB64u(wire.c);
15451
+ if (!ciphertext) return close("DECRYPT_FAILED");
15452
+ let opened;
15453
+ try {
15454
+ opened = await openMessage(channel.b2p, {
15455
+ type: wire.kind,
15456
+ connId: channel.connId,
15457
+ pcId: this.pcId,
15458
+ session: wire.session ?? "",
15459
+ operationId: wire.opId ?? "",
15460
+ projectUuid: wire.projectUuid ?? "",
15461
+ counter: wire.n
15462
+ }, ciphertext, channel.receive);
15463
+ } catch {
15464
+ return close("DECRYPT_FAILED");
15465
+ }
15466
+ const command = sealedCommand(wire, opened.plaintext);
15467
+ if (!command) return close("DECRYPT_FAILED");
15468
+ channel.receive = opened.state;
15469
+ channel.last = { n: wire.n, digest };
15470
+ if (command.kind !== "confirm") return { type: "command", command, browser: channel.browser };
15471
+ if (this.activeIds().length >= ACTIVE_CHANNEL_MAX) return close("CHANNEL_LIMIT");
15472
+ channel.active = true;
15473
+ channel.executedThrough = 0;
15474
+ return { type: "confirmed", browser: channel.browser };
15475
+ }
15476
+ /**
15477
+ * PC→웹 봉인(frame·answer — A3 AAD). 번호는 await 전에 배정한다. 활성 채널이 아니면 CHANNEL_GONE, 번호가 다 됐으면 MESSAGE_LIMIT.
15478
+ * c = base64url(AES-GCM 암호문 ‖ 태그).
15479
+ */
15480
+ async seal(channelId, header, body) {
15481
+ const channel = this.channels.get(channelId);
15482
+ if (!channel?.active) throw new ChannelSealError("CHANNEL_GONE", `channel ${channelId} is not open`);
15483
+ const n = channel.sendNext;
15484
+ if (n >= MAX_MESSAGES_PER_KEY) throw new ChannelSealError("MESSAGE_LIMIT", `channel ${channelId} used up its message numbers`);
15485
+ channel.sendNext = n + 1;
15486
+ const sealed = await sealMessage(channel.p2b, {
15487
+ type: header.kind,
15488
+ connId: channel.connId,
15489
+ pcId: this.pcId,
15490
+ session: header.session,
15491
+ operationId: header.opId ?? "",
15492
+ projectUuid: header.projectUuid ?? "",
15493
+ counter: n
15494
+ }, new TextEncoder().encode(JSON.stringify(body)));
15495
+ return { n, c: b64u(sealed) };
15496
+ }
15497
+ };
15498
+ function wireHello(raw) {
15499
+ const value = record2(raw);
15500
+ const channel = text(value?.channel);
15501
+ const browserKeyId = text(value?.browserKeyId);
15502
+ const eB = fromB64u(value?.eB, PUBLIC_KEY_BYTES);
15503
+ const nB = fromB64u(value?.nB, NONCE_SEED_BYTES);
15504
+ const sig = fromB64u(value?.sig, SIGNATURE_BYTES);
15505
+ return channel && browserKeyId && eB && nB && sig ? { channel, eB, nB, browserKeyId, sig } : void 0;
15506
+ }
15507
+ function wireCommand(raw) {
15508
+ const value = record2(raw);
15509
+ const channelId = text(value?.channelId);
15510
+ const n = value?.n;
15511
+ const c = text(value?.c);
15512
+ const kind = value?.kind;
15513
+ if (!value || !channelId || typeof n !== "number" || !Number.isSafeInteger(n) || n < 0 || !c || typeof kind !== "string" || !COMMAND_KINDS.includes(kind)) {
15514
+ return void 0;
15515
+ }
15516
+ const optional = (key) => {
15517
+ const item = text(value[key]);
15518
+ return item ? { [key]: item } : {};
15519
+ };
15520
+ return {
15521
+ channelId,
15522
+ n,
15523
+ c,
15524
+ kind,
15525
+ ...optional("session"),
15526
+ ...optional("opId"),
15527
+ ...optional("projectUuid"),
15528
+ ...optional("requestId")
15529
+ };
15530
+ }
15531
+ function sealedCommand(wire, plaintext) {
15532
+ let parsed;
15533
+ try {
15534
+ parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(plaintext));
15535
+ } catch {
15536
+ return void 0;
15537
+ }
15538
+ const body = record2(parsed);
15539
+ if (!body) return void 0;
15540
+ const session = text(body.session);
15541
+ const instance = text(body.instance);
15542
+ const opId = text(body.opId);
15543
+ 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;
15544
+ switch (wire.kind) {
15545
+ case "confirm":
15546
+ return wire.session === void 0 && wire.opId === void 0 && wire.projectUuid === void 0 ? { kind: "confirm" } : void 0;
15547
+ case "input": {
15548
+ const d = body.d;
15549
+ 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;
15550
+ }
15551
+ case "key": {
15552
+ const key = text(body.key);
15553
+ return targets(false) && key ? { kind: "key", session, instance, key } : void 0;
15554
+ }
15555
+ case "resize": {
15556
+ const { cols, rows } = body;
15557
+ return targets(false) && isSize(cols) && isSize(rows) ? { kind: "resize", session, instance, cols, rows } : void 0;
15558
+ }
15559
+ case "create": {
15560
+ const name = text(body.name);
15561
+ const projectUuid = text(body.projectUuid);
15562
+ const cwd = text(body.cwd);
15563
+ const command = body.command;
15564
+ if (!name || !opId || wire.session !== name || wire.opId !== opId || wire.projectUuid !== projectUuid) return void 0;
15565
+ if (command !== void 0 && typeof command !== "string") return void 0;
15566
+ return {
15567
+ kind: "create",
15568
+ opId,
15569
+ name,
15570
+ ...projectUuid ? { projectUuid } : {},
15571
+ ...cwd ? { cwd } : {},
15572
+ ...typeof command === "string" ? { command } : {}
15573
+ };
15574
+ }
15575
+ case "kill":
15576
+ return targets(true) ? { kind: "kill", opId, session, instance } : void 0;
15577
+ case "label": {
15578
+ const label = text(body.label);
15579
+ return targets(true) && label ? { kind: "label", opId, session, instance, label } : void 0;
15580
+ }
15581
+ }
15582
+ }
15583
+ function record2(value) {
15584
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
15585
+ }
15586
+ function text(value) {
15587
+ return typeof value === "string" && value !== "" ? value : void 0;
15588
+ }
15589
+ function isSize(value) {
15590
+ return typeof value === "number" && Number.isInteger(value) && value >= 1;
15591
+ }
15592
+ function b64u(bytes) {
15593
+ return Buffer.from(bytes).toString("base64url");
15594
+ }
15595
+ function fromB64u(value, length) {
15596
+ if (typeof value !== "string" || value === "" || !/^[A-Za-z0-9_-]+$/.test(value)) return void 0;
15597
+ const bytes = new Uint8Array(Buffer.from(value, "base64url"));
15598
+ return length === void 0 || bytes.length === length ? bytes : void 0;
15599
+ }
15600
+
15601
+ // src/core/term/remoteSessions.ts
15602
+ function wireSessions(listed3, exclude) {
15603
+ return listed3.filter((session) => !exclude.includes(session.name)).map((session) => ({
15604
+ name: session.name,
15605
+ ...session.label !== void 0 ? { label: session.label } : {},
15606
+ ...session.project !== void 0 ? { project: session.project } : {},
15607
+ cols: session.cols,
15608
+ rows: session.rows,
15609
+ ...session.lastOutputAt !== void 0 ? { lastOutputAt: session.lastOutputAt } : {},
15610
+ ...session.instance !== void 0 ? { instance: session.instance } : {}
15611
+ }));
15612
+ }
15613
+ function sessionsKey(sessions) {
15614
+ return JSON.stringify(sessions);
15615
+ }
15616
+
15617
+ // src/core/term/remoteFrame.ts
15618
+ import { createHash as createHash7 } from "crypto";
15619
+ function screenFrame(lines, maxD) {
15620
+ const sizes = lines.map((line) => Buffer.byteLength(line, "utf8"));
15621
+ let start = 0;
15622
+ let bytes = sizes.reduce((sum, size) => sum + size, 0) + Math.max(0, lines.length - 1) * 2;
15623
+ while (start < lines.length && base64Length(bytes) > maxD) {
15624
+ bytes -= (sizes[start] ?? 0) + (start < lines.length - 1 ? 2 : 0);
15625
+ start += 1;
15626
+ }
15627
+ const text2 = lines.slice(start).join("\r\n");
15628
+ return {
15629
+ d: Buffer.from(text2, "utf8").toString("base64"),
15630
+ hash: createHash7("sha256").update(text2, "utf8").digest("hex"),
15631
+ dropped: start
15632
+ };
15633
+ }
15634
+ var GCM_TAG_BYTES = 16;
15635
+ var MAX_COUNTER = 2 ** 32 - 1;
15636
+ function frameBudget(frameMaxBytes, outer, sealed) {
15637
+ const outside = Buffer.byteLength(JSON.stringify({ ...outer, n: MAX_COUNTER, c: "" }), "utf8");
15638
+ const cipherBytes = Math.floor((frameMaxBytes - outside) * 3 / 4);
15639
+ const inside = Buffer.byteLength(JSON.stringify({ ...sealed, d: "", executedThrough: MAX_COUNTER }), "utf8");
15640
+ return cipherBytes - GCM_TAG_BYTES - inside;
15641
+ }
15642
+ function base64Length(bytes) {
15643
+ return 4 * Math.ceil(bytes / 3);
15644
+ }
15645
+
15646
+ // src/core/term/remoteViewer.ts
15647
+ var RemoteViewer = class {
15648
+ constructor(deps) {
15649
+ this.deps = deps;
15650
+ this.size = deps.size;
15651
+ }
15652
+ deps;
15653
+ stopper = new AbortController();
15654
+ dirty = true;
15655
+ wakeUp;
15656
+ size;
15657
+ client;
15658
+ get stopped() {
15659
+ return this.stopper.signal.aborted;
15660
+ }
15661
+ stop() {
15662
+ if (this.stopped) return;
15663
+ this.stopper.abort();
15664
+ this.nudge();
15665
+ this.client?.close();
15666
+ }
15667
+ /** 세션 크기가 바뀌었다(웹 패널 크기 → 데몬 set-size) — 다시 올린다. */
15668
+ setSize(size) {
15669
+ this.size = size;
15670
+ this.refresh();
15671
+ }
15672
+ /** 다시 그려 보낸다(다시 열린 링크·목록을 올린 뒤·실행 확인 지점이 오른 뒤). */
15673
+ refresh() {
15674
+ this.dirty = true;
15675
+ this.nudge();
15676
+ }
15677
+ async run() {
14646
15678
  const name = this.deps.session;
14647
15679
  const client = await openTermClient(this.deps.paths, { start: false });
14648
15680
  if (!client || this.stopped) {
@@ -14703,6 +15735,12 @@ var RemoteViewer = class {
14703
15735
  this.dirty = false;
14704
15736
  lastRead = Date.now();
14705
15737
  const { cols, rows } = this.size;
15738
+ const executedThrough = this.deps.executedThrough();
15739
+ if (executedThrough === void 0) {
15740
+ this.stop();
15741
+ this.deps.onChannelEnded("CHANNEL_GONE");
15742
+ return;
15743
+ }
14706
15744
  let data;
14707
15745
  try {
14708
15746
  data = await client.request({ op: "read", name, scrollback: true, lines: FRAME_SCROLLBACK_LINES + rows });
@@ -14710,17 +15748,34 @@ var RemoteViewer = class {
14710
15748
  this.daemonFailed("read", error);
14711
15749
  return;
14712
15750
  }
15751
+ const instance = sessionInstance(data);
15752
+ if (instance === void 0) {
15753
+ this.daemonFailed("read", new TermError(
15754
+ "TERM_DAEMON_OUTDATED",
15755
+ "The term daemon is older than this CLI (no session instance) \u2014 restart it with `ainecto term kill-server`."
15756
+ ));
15757
+ return;
15758
+ }
14713
15759
  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));
15760
+ const outer = { linkId: target.linkId, channelId: this.deps.channelId, session: name, cols, rows };
15761
+ const sealed = { ...modes ? { modes } : {}, instance };
15762
+ const frame = screenFrame(readLines(data), frameBudget(target.frameMaxBytes, outer, sealed));
14716
15763
  if (frame.dropped !== dropped) {
14717
15764
  dropped = frame.dropped;
14718
- this.deps.log.write({ event: "remote_frame_trimmed", session: name, dropped });
15765
+ this.deps.log.write({ event: "remote_frame_trimmed", channelId: this.deps.channelId, session: name, dropped });
14719
15766
  }
14720
- const key = `${frame.hash}:${cols}x${rows}:${JSON.stringify(modes ?? null)}`;
15767
+ const key = `${frame.hash}:${cols}x${rows}:${JSON.stringify(modes ?? null)}:${instance}:${executedThrough}`;
14721
15768
  if (key === sentKey) continue;
15769
+ let box;
15770
+ try {
15771
+ box = await this.deps.seal({ d: frame.d, ...sealed, executedThrough });
15772
+ } catch (error) {
15773
+ this.stop();
15774
+ this.deps.onChannelEnded(error instanceof ChannelSealError ? error.reason : "CHANNEL_GONE");
15775
+ return;
15776
+ }
14722
15777
  try {
14723
- await this.deps.http.call("frame", { ...head, d: frame.d }, { signal: this.stopper.signal });
15778
+ await this.deps.http.call("frame", { ...outer, ...box }, { signal: this.stopper.signal });
14724
15779
  sentKey = key;
14725
15780
  attempt = 0;
14726
15781
  } catch (error) {
@@ -14732,10 +15787,13 @@ var RemoteViewer = class {
14732
15787
  }
14733
15788
  if (error instanceof PcCallError && error.status === 404 && error.code === "SESSION_NOT_FOUND") {
14734
15789
  this.deps.onUnknownSession();
14735
- } else if (!(error instanceof PcCallError) || !error.retryable) {
15790
+ } else if (error instanceof PcCallError && (error.status === 401 || error.status === 403)) {
14736
15791
  this.stop();
14737
15792
  this.deps.onRefused(error);
14738
15793
  return;
15794
+ } else if (!(error instanceof PcCallError) || !error.retryable) {
15795
+ this.stop();
15796
+ return;
14739
15797
  }
14740
15798
  await sleep(retryWait(attempt, Math.random()), this.stopper.signal);
14741
15799
  attempt += 1;
@@ -14773,8 +15831,8 @@ import { rmdir as rmdir2 } from "fs/promises";
14773
15831
  // src/core/pc/pcUpgrade.ts
14774
15832
  var STABLE = /^\d+\.\d+\.\d+$/;
14775
15833
  var NEXT = /^\d+\.\d+\.\d+-next\.\d+(\.\d+)*$/;
14776
- function releaseChannel(version, release) {
14777
- if (!release) return void 0;
15834
+ function releaseChannel(version, release2) {
15835
+ if (!release2) return void 0;
14778
15836
  if (NEXT.test(version)) return "next";
14779
15837
  if (STABLE.test(version)) return "latest";
14780
15838
  return void 0;
@@ -14807,10 +15865,10 @@ function auditPassed(exitCode2, output) {
14807
15865
  }
14808
15866
  function provenanceWorkflow(body, name, version) {
14809
15867
  const subject = `pkg:npm/${encodeURIComponent(name).replace("%2F", "/")}@${version}`;
14810
- const attestations = record2(body)?.attestations;
15868
+ const attestations = record3(body)?.attestations;
14811
15869
  if (!Array.isArray(attestations)) return void 0;
14812
15870
  for (const item of attestations) {
14813
- const payload = record2(record2(record2(item)?.bundle)?.dsseEnvelope)?.payload;
15871
+ const payload = record3(record3(record3(item)?.bundle)?.dsseEnvelope)?.payload;
14814
15872
  if (typeof payload !== "string") continue;
14815
15873
  let statement;
14816
15874
  try {
@@ -14818,11 +15876,11 @@ function provenanceWorkflow(body, name, version) {
14818
15876
  } catch {
14819
15877
  continue;
14820
15878
  }
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;
15879
+ const subjects = record3(statement)?.subject;
15880
+ const forThis = Array.isArray(subjects) && subjects.some((s) => record3(s)?.name === subject);
15881
+ const workflow = record3(record3(record3(record3(statement)?.predicate)?.buildDefinition)?.externalParameters)?.workflow;
15882
+ const repository = record3(workflow)?.repository;
15883
+ const path = record3(workflow)?.path;
14826
15884
  if (forThis && typeof repository === "string" && typeof path === "string") return { repository, path };
14827
15885
  }
14828
15886
  return void 0;
@@ -14830,7 +15888,7 @@ function provenanceWorkflow(body, name, version) {
14830
15888
  function sameWorkflow(a, b) {
14831
15889
  return a.repository === b.repository && a.path === b.path;
14832
15890
  }
14833
- function record2(value) {
15891
+ function record3(value) {
14834
15892
  return value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : void 0;
14835
15893
  }
14836
15894
 
@@ -14838,6 +15896,7 @@ function record2(value) {
14838
15896
  var REMOTE_STATE_PREFIX = "Remote terminal: ";
14839
15897
  var REMOTE_OFF_BY_WEB_LINE = `${REMOTE_STATE_PREFIX}turned off from the web.`;
14840
15898
  var REMOTE_NOT_FOUND = "REMOTE_NOT_FOUND";
15899
+ var E2E_VERSION = 1;
14841
15900
  function openRemoteLog(paths) {
14842
15901
  const log = new DaemonLog(paths.remoteLog, paths.previousRemoteLog);
14843
15902
  log.enableRotation();
@@ -14864,15 +15923,17 @@ function createRemoteHttp(input) {
14864
15923
  }
14865
15924
  });
14866
15925
  }
15926
+ var viewerKey = (watch) => `${watch.channelId}\0${watch.session}`;
14867
15927
  async function runRemoteBridge(deps) {
14868
15928
  let ending;
14869
15929
  const stopper = new AbortController();
14870
15930
  const viewers = /* @__PURE__ */ new Map();
15931
+ const book = new ChannelBook(deps.pcId);
14871
15932
  const end = (outcome) => {
14872
15933
  if (ending) return;
14873
15934
  ending = outcome;
14874
15935
  stopper.abort();
14875
- for (const viewer of viewers.values()) viewer.stop();
15936
+ for (const { viewer } of viewers.values()) viewer.stop();
14876
15937
  viewers.clear();
14877
15938
  };
14878
15939
  const onUserStop = () => end({ exitCode: 0, reason: "Stopped.", close: true });
@@ -14883,16 +15944,22 @@ async function runRemoteBridge(deps) {
14883
15944
  try {
14884
15945
  const first = await currentSessions(deps);
14885
15946
  if (ending) return { exitCode: ending.exitCode, reason: ending.reason };
14886
- let link = await openLink2(deps, 1, deps.remoteEnabled, deps.remoteEnabled ? first : [], void 0);
15947
+ let link2;
15948
+ try {
15949
+ link2 = await openLink2(deps, 1, deps.remoteEnabled, deps.remoteEnabled ? first : [], void 0);
15950
+ } catch (error) {
15951
+ return { exitCode: 1, reason: refused(error).reason };
15952
+ }
14887
15953
  let remote = startState(deps.remoteEnabled);
14888
15954
  let uploaded = deps.remoteEnabled ? sessionsKey(first) : void 0;
15955
+ let watchList = [];
14889
15956
  deps.log.write({
14890
15957
  event: "remote_opened",
14891
- linkId: link.linkId,
15958
+ linkId: link2.linkId,
14892
15959
  sessions: deps.remoteEnabled ? first.length : 0,
14893
15960
  remote,
14894
- pollHoldSeconds: link.pollHoldSeconds,
14895
- frameMaxBytes: link.frameMaxBytes
15961
+ pollHoldSeconds: link2.pollHoldSeconds,
15962
+ frameMaxBytes: link2.frameMaxBytes
14896
15963
  });
14897
15964
  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
15965
  let syncing = Promise.resolve();
@@ -14909,9 +15976,9 @@ async function runRemoteBridge(deps) {
14909
15976
  const key = sessionsKey(sessions);
14910
15977
  if (key === uploaded) return;
14911
15978
  try {
14912
- await deps.http.call("sessions", { linkId: link.linkId, sessions }, { signal: stopper.signal });
15979
+ await deps.http.call("sessions", { linkId: link2.linkId, sessions }, { signal: stopper.signal });
14913
15980
  uploaded = key;
14914
- for (const viewer of viewers.values()) viewer.refresh();
15981
+ for (const { viewer } of viewers.values()) viewer.refresh();
14915
15982
  } catch {
14916
15983
  }
14917
15984
  });
@@ -14928,51 +15995,93 @@ async function runRemoteBridge(deps) {
14928
15995
  daemonFailed(deps, "watch-sessions", void 0, error);
14929
15996
  }
14930
15997
  }
14931
- const viewerFor = (name, size) => {
15998
+ const stopViewers = (channelId) => {
15999
+ for (const [key, { watch, viewer }] of viewers) {
16000
+ if (watch.channelId !== channelId) continue;
16001
+ viewer.stop();
16002
+ viewers.delete(key);
16003
+ }
16004
+ };
16005
+ const refreshChannel = (channelId) => {
16006
+ for (const { watch, viewer } of viewers.values()) {
16007
+ if (watch.channelId === channelId) viewer.refresh();
16008
+ }
16009
+ };
16010
+ const closeChannel = async (channelId, reason, browser) => {
16011
+ book.drop(channelId);
16012
+ stopViewers(channelId);
16013
+ commands.forgetChannel(channelId);
16014
+ deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "pc", reason, ...browser ? { browserKeyId: browser.keyId } : {} });
16015
+ try {
16016
+ await deps.http.call("channel/close", { linkId: link2.linkId, channelId, reason }, { signal: stopper.signal });
16017
+ } catch {
16018
+ }
16019
+ };
16020
+ const closeAllChannels = async (reason) => {
16021
+ for (const channelId of book.dropAll()) {
16022
+ stopViewers(channelId);
16023
+ commands.forgetChannel(channelId);
16024
+ deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "pc", reason });
16025
+ try {
16026
+ await deps.http.call("channel/close", { linkId: link2.linkId, channelId, reason }, { signal: stopper.signal });
16027
+ } catch {
16028
+ }
16029
+ }
16030
+ };
16031
+ const viewerFor = (watch, size) => {
16032
+ const key = viewerKey(watch);
14932
16033
  const viewer = new RemoteViewer({
14933
16034
  paths: deps.paths,
14934
- session: name,
16035
+ session: watch.session,
16036
+ channelId: watch.channelId,
14935
16037
  http: deps.http,
14936
16038
  log: deps.log,
14937
- link: () => link,
16039
+ link: () => link2,
14938
16040
  size,
16041
+ seal: (body) => book.seal(watch.channelId, { kind: "frame", session: watch.session }, { ...body }),
16042
+ executedThrough: () => book.executedThrough(watch.channelId),
14939
16043
  onGone: () => {
14940
- viewers.delete(name);
16044
+ if (viewers.get(key)?.viewer === viewer) viewers.delete(key);
14941
16045
  void syncList();
14942
16046
  },
14943
16047
  onRefused: (error) => end(refused(error)),
14944
16048
  onUnknownSession: () => {
14945
16049
  uploaded = void 0;
14946
16050
  void syncList();
16051
+ },
16052
+ onChannelEnded: (reason) => {
16053
+ if (viewers.get(key)?.viewer === viewer) viewers.delete(key);
16054
+ if (reason !== "CHANNEL_GONE") void closeChannel(watch.channelId, reason);
14947
16055
  }
14948
16056
  });
14949
16057
  void viewer.run();
14950
16058
  return viewer;
14951
16059
  };
14952
- const setWatching = async (names) => {
14953
- const wanted = remote === "on" ? names : [];
16060
+ const applyWatching = async () => {
16061
+ const wanted = remote === "on" ? watchList.filter((watch) => book.isActive(watch.channelId)) : [];
16062
+ const wantedKeys = new Set(wanted.map(viewerKey));
14954
16063
  let changed = false;
14955
- for (const [name, viewer] of viewers) {
14956
- if (!wanted.includes(name)) {
16064
+ for (const [key, { viewer }] of viewers) {
16065
+ if (!wantedKeys.has(key)) {
14957
16066
  viewer.stop();
14958
- viewers.delete(name);
16067
+ viewers.delete(key);
14959
16068
  changed = true;
14960
16069
  }
14961
16070
  }
14962
- const missing = wanted.filter((name) => !viewers.has(name));
16071
+ const missing = wanted.filter((watch) => !viewers.has(viewerKey(watch)));
14963
16072
  if (missing.length > 0) {
14964
16073
  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));
16074
+ for (const watch of missing) {
16075
+ const size = sizes.get(watch.session);
16076
+ if (size && !viewers.has(viewerKey(watch))) {
16077
+ viewers.set(viewerKey(watch), { watch, viewer: viewerFor(watch, size) });
14969
16078
  changed = true;
14970
16079
  }
14971
16080
  }
14972
16081
  }
14973
- if (changed) deps.log.write({ event: "remote_watching", sessions: [...viewers.keys()] });
16082
+ if (changed) deps.log.write({ event: "remote_watching", watching: [...viewers.values()].map(({ watch }) => watch) });
14974
16083
  };
14975
- const applyRemote = (next) => {
16084
+ const applyRemote = async (next) => {
14976
16085
  if (next === remote) return;
14977
16086
  remote = next;
14978
16087
  deps.log.write({ event: "remote_state", remote });
@@ -14981,29 +16090,70 @@ async function runRemoteBridge(deps) {
14981
16090
  void syncList();
14982
16091
  deps.print(`${REMOTE_STATE_PREFIX}on.`);
14983
16092
  } else {
14984
- for (const viewer of viewers.values()) viewer.stop();
14985
- viewers.clear();
16093
+ await closeAllChannels("REMOTE_OFF");
14986
16094
  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
16095
  }
14988
16096
  };
14989
- const commands = new CommandRunner(deps, control, viewers, () => remote);
16097
+ const onHello = async (channelId, hello) => {
16098
+ if (remote !== "on") {
16099
+ deps.log.write({ event: "remote_hello", channelId, result: "closed", reason: "REMOTE_OFF" });
16100
+ await closeChannel(channelId, "REMOTE_OFF");
16101
+ return;
16102
+ }
16103
+ const outcome2 = await book.hello(channelId, hello, await loadTrust(deps));
16104
+ switch (outcome2.type) {
16105
+ case "ignored":
16106
+ deps.log.write({ event: "remote_hello", channelId, result: "ignored" });
16107
+ return;
16108
+ case "close":
16109
+ deps.log.write({ event: "remote_hello", channelId, result: "closed", reason: outcome2.reason });
16110
+ await closeChannel(channelId, outcome2.reason);
16111
+ return;
16112
+ case "refuse":
16113
+ deps.log.write({ event: "remote_hello", channelId, result: "refused", reason: "PAIRING_REQUIRED" });
16114
+ try {
16115
+ await deps.http.call("welcome", { linkId: link2.linkId, channelId, refuse: "PAIRING_REQUIRED" }, { signal: stopper.signal });
16116
+ } catch {
16117
+ }
16118
+ return;
16119
+ case "welcome":
16120
+ deps.log.write({ event: "remote_hello", channelId, result: "welcome", browserKeyId: outcome2.browser.keyId });
16121
+ try {
16122
+ await deps.http.call("welcome", { linkId: link2.linkId, channelId, welcome: outcome2.welcome }, { signal: stopper.signal });
16123
+ } catch {
16124
+ book.drop(channelId);
16125
+ deps.log.write({ event: "remote_channel", channelId, state: "closed", by: "local", reason: "welcome-not-delivered" });
16126
+ }
16127
+ return;
16128
+ }
16129
+ };
16130
+ const commands = new CommandRunner(deps, control, book, () => remote, () => link2.linkId, stopper.signal, {
16131
+ closeChannel,
16132
+ refreshChannel,
16133
+ resized: (session, size) => {
16134
+ for (const { watch, viewer } of viewers.values()) {
16135
+ if (watch.session === session) viewer.setSize(size);
16136
+ }
16137
+ },
16138
+ applyWatching
16139
+ });
14990
16140
  let reopens = 0;
14991
16141
  let attempt = 0;
14992
16142
  while (!ending) {
14993
16143
  let answer;
14994
16144
  try {
14995
- answer = await deps.http.call("poll", { linkId: link.linkId }, { holdMs: link.pollHoldSeconds * 1e3, signal: stopper.signal });
16145
+ answer = await deps.http.call("poll", { linkId: link2.linkId }, { holdMs: link2.pollHoldSeconds * 1e3, signal: stopper.signal });
14996
16146
  } catch (error) {
14997
16147
  if (ending) break;
14998
16148
  if (forgotten(error)) {
14999
16149
  if (reopens > 0) await sleep(retryWait(reopens - 1, Math.random()), stopper.signal);
15000
16150
  if (ending) break;
15001
16151
  reopens += 1;
15002
- const previous = link;
16152
+ const previous = link2;
15003
16153
  try {
15004
16154
  const enabled = deps.remoteEnabled && remote !== "off-by-web";
15005
16155
  const sessions = enabled ? await currentSessions(deps) : [];
15006
- link = await openLink2(deps, previous.generation + 1, enabled, sessions, stopper.signal);
16156
+ link2 = await openLink2(deps, previous.generation + 1, enabled, sessions, stopper.signal);
15007
16157
  if (enabled) remote = "on";
15008
16158
  uploaded = enabled ? sessionsKey(sessions) : void 0;
15009
16159
  } catch (reopenError) {
@@ -15012,9 +16162,20 @@ async function runRemoteBridge(deps) {
15012
16162
  end(refused(reopenError));
15013
16163
  break;
15014
16164
  }
15015
- deps.log.write({ event: "remote_reopened", reason: REMOTE_NOT_FOUND, previousLinkId: previous.linkId, linkId: link.linkId });
16165
+ const dropped = book.dropAll();
16166
+ for (const channelId of dropped) {
16167
+ stopViewers(channelId);
16168
+ commands.forgetChannel(channelId);
16169
+ }
16170
+ watchList = [];
16171
+ deps.log.write({
16172
+ event: "remote_reopened",
16173
+ reason: REMOTE_NOT_FOUND,
16174
+ previousLinkId: previous.linkId,
16175
+ linkId: link2.linkId,
16176
+ channelsDropped: dropped.length
16177
+ });
15016
16178
  deps.print("AiNecto lost the remote terminal (it may have restarted); opened it again.");
15017
- for (const viewer of viewers.values()) viewer.refresh();
15018
16179
  continue;
15019
16180
  }
15020
16181
  if (!(error instanceof PcCallError) || !error.retryable) {
@@ -15036,17 +16197,45 @@ async function runRemoteBridge(deps) {
15036
16197
  break;
15037
16198
  }
15038
16199
  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 });
16200
+ if (state) await applyRemote(state);
16201
+ for (const channelId of book.expired()) {
16202
+ await closeChannel(channelId, "HANDSHAKE_EXPIRED");
16203
+ }
16204
+ for (const item of pollItems(answer)) {
16205
+ if (ending) break;
16206
+ switch (item.type) {
16207
+ case "hello":
16208
+ await onHello(item.channelId, item.hello);
16209
+ break;
16210
+ case "cmd":
16211
+ await commands.run(item.command);
16212
+ break;
16213
+ case "bad-cmd":
16214
+ deps.log.write({ event: "remote_command_skipped", channelId: item.channelId, n: item.n, why: "malformed" });
16215
+ if (book.has(item.channelId)) await closeChannel(item.channelId, "DECRYPT_FAILED");
16216
+ break;
16217
+ case "watch":
16218
+ watchList = item.channels;
16219
+ break;
16220
+ case "channel-closed":
16221
+ if (book.drop(item.channelId)) {
16222
+ deps.log.write({ event: "remote_channel", channelId: item.channelId, state: "closed", by: "web" });
16223
+ }
16224
+ stopViewers(item.channelId);
16225
+ commands.forgetChannel(item.channelId);
16226
+ break;
16227
+ }
16228
+ }
16229
+ await applyWatching();
16230
+ deps.onAnswer?.({ tags: cliTagsOf(answer.cli), watching: viewers.size });
15043
16231
  await syncList();
15044
16232
  }
15045
16233
  const outcome = ending ?? { exitCode: 1, reason: "The remote terminal stopped.", close: true };
15046
16234
  await syncing;
16235
+ await deps.notifier.flush();
15047
16236
  if (outcome.close) {
15048
16237
  try {
15049
- await deps.http.call("close", { linkId: link.linkId });
16238
+ await deps.http.call("close", { linkId: link2.linkId });
15050
16239
  } catch (error) {
15051
16240
  deps.print(`Could not tell AiNecto that the remote terminal stopped: ${error instanceof Error ? error.message : String(error)}`);
15052
16241
  }
@@ -15054,7 +16243,7 @@ async function runRemoteBridge(deps) {
15054
16243
  return { exitCode: outcome.exitCode, reason: outcome.reason };
15055
16244
  } finally {
15056
16245
  stopper.abort();
15057
- for (const viewer of viewers.values()) viewer.stop();
16246
+ for (const { viewer } of viewers.values()) viewer.stop();
15058
16247
  deps.signal.removeEventListener("abort", onUserStop);
15059
16248
  listWatch?.close();
15060
16249
  control.close();
@@ -15069,7 +16258,8 @@ async function openLink2(deps, generation, remoteEnabled, sessions, signal) {
15069
16258
  hostName: deps.hostName,
15070
16259
  cliVersion: deps.cliVersion,
15071
16260
  remoteEnabled,
15072
- sessions
16261
+ sessions,
16262
+ e2e: E2E_VERSION
15073
16263
  }, signal ? { signal } : void 0);
15074
16264
  const limits = serverLimits2(opened.limits);
15075
16265
  if (typeof opened.linkId !== "string" || typeof opened.linkToken !== "string" || !limits) {
@@ -15082,19 +16272,37 @@ async function currentSessions(deps) {
15082
16272
  const result = await termRequest(deps.paths, { op: "ls" }, { start: false });
15083
16273
  return wireSessions(listedSessions(result.daemon ? result.data : void 0), deps.exclude);
15084
16274
  }
16275
+ async function loadTrust(deps) {
16276
+ if (!deps.trust) return void 0;
16277
+ try {
16278
+ const account2 = (await loadPcKeys(deps.trust.keysPath)).accounts[deps.trust.accountKey];
16279
+ return account2 ? { userId: transcriptUserId(deps.trust.userId), pcKey: account2.pcKey, browsers: account2.browsers } : void 0;
16280
+ } catch (error) {
16281
+ deps.log.write({ event: "remote_trust_error", code: errorCode2(error) });
16282
+ return void 0;
16283
+ }
16284
+ }
15085
16285
  function refused(error) {
16286
+ if (error instanceof PcCallError && error.op === "open" && error.status === 400 && error.code === "INVALID") {
16287
+ 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 };
16288
+ }
15086
16289
  const what = error instanceof PcCallError ? `${error.op}: ${error.status ?? "-"} ${error.code ?? ""} ${error.message}`.replace(/\s+/g, " ") : error instanceof Error ? error.message : String(error);
15087
16290
  return { exitCode: 1, reason: `AiNecto refused the remote terminal (${what}).`, close: true };
15088
16291
  }
15089
16292
  function forgotten(error) {
15090
16293
  return error instanceof PcCallError && error.status === 404 && error.code === REMOTE_NOT_FOUND;
15091
16294
  }
16295
+ function errorCode2(error) {
16296
+ if (error instanceof TermError) return error.code;
16297
+ if (error && typeof error === "object" && "code" in error && typeof error.code === "string") return error.code;
16298
+ return "UNKNOWN";
16299
+ }
15092
16300
  function daemonFailed(deps, op, session, error) {
15093
16301
  deps.log.write({
15094
16302
  event: "remote_daemon_error",
15095
16303
  op,
15096
16304
  ...session ? { session } : {},
15097
- code: error instanceof TermError ? error.code : "UNKNOWN",
16305
+ code: errorCode2(error),
15098
16306
  message: error instanceof Error ? error.message : String(error)
15099
16307
  });
15100
16308
  }
@@ -15121,114 +16329,188 @@ var DaemonControl = class {
15121
16329
  }
15122
16330
  };
15123
16331
  var CommandRunner = class {
15124
- constructor(deps, control, viewers, remote) {
16332
+ constructor(deps, control, book, remote, linkId, stopSignal, hooks) {
15125
16333
  this.deps = deps;
15126
16334
  this.control = control;
15127
- this.viewers = viewers;
16335
+ this.book = book;
15128
16336
  this.remote = remote;
16337
+ this.linkId = linkId;
16338
+ this.stopSignal = stopSignal;
16339
+ this.hooks = hooks;
15129
16340
  }
15130
16341
  deps;
15131
16342
  control;
15132
- viewers;
16343
+ book;
15133
16344
  remote;
15134
- /** 여러 바이트 글자가 poll 경계에서 갈려도 잇는다 — 세션마다(바이트는 그대로, 글자로 바꾸는 곳만 한 곳). */
16345
+ linkId;
16346
+ stopSignal;
16347
+ hooks;
16348
+ /** 여러 바이트 글자가 메시지 경계에서 갈려도 잇는다 — (채널, 세션)마다(바이트는 그대로, 글자로 바꾸는 곳만 한 곳). */
15135
16349
  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 };
16350
+ forgetChannel(channelId) {
16351
+ for (const key of this.decoders.keys()) {
16352
+ if (key.startsWith(`${channelId}\0`)) this.decoders.delete(key);
16353
+ }
15145
16354
  }
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)
15157
- });
16355
+ /** cmd 하나 — 목록 올리기는 poll 한 바퀴 끝에 다리가 한다(바뀐 때만 올라간다). */
16356
+ async run(wire) {
16357
+ const outcome = await this.book.receive(wire);
16358
+ switch (outcome.type) {
16359
+ case "unknown":
16360
+ this.deps.log.write({ event: "remote_command_skipped", channelId: wire.channelId, n: wire.n, why: "unknown-channel" });
16361
+ return;
16362
+ case "duplicate":
16363
+ this.deps.log.write({ event: "remote_command_skipped", channelId: wire.channelId, n: wire.n, why: "duplicate" });
16364
+ return;
16365
+ case "close":
16366
+ await this.hooks.closeChannel(wire.channelId, outcome.reason);
16367
+ return;
16368
+ case "confirmed":
16369
+ this.deps.log.write({ event: "remote_channel", channelId: wire.channelId, state: "active", browserKeyId: outcome.browser.keyId });
16370
+ void this.deps.notifier.notify({ kind: "session", keyId: outcome.browser.keyId, browserName: outcome.browser.name });
16371
+ await this.hooks.applyWatching();
16372
+ return;
16373
+ case "command":
16374
+ await this.execute(wire, outcome.command, outcome.browser);
16375
+ return;
15158
16376
  }
15159
16377
  }
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
- }
16378
+ async execute(wire, command, browser) {
16379
+ const session = command.kind === "create" ? command.name : command.session;
16380
+ const opId = "opId" in command ? command.opId : void 0;
16381
+ this.deps.log.write({
16382
+ event: "remote_command",
16383
+ type: command.kind,
16384
+ channelId: wire.channelId,
16385
+ n: wire.n,
16386
+ session,
16387
+ ...opId ? { opId } : {},
16388
+ ...wire.requestId ? { requestId: wire.requestId } : {},
16389
+ ...command.kind === "input" ? { bytes: command.bytes.length } : {}
16390
+ });
16391
+ let failure2;
16392
+ let applied = {};
16393
+ if (this.remote() !== "on") {
16394
+ failure2 = { code: "REMOTE_OFF", message: "Terminals from the web are turned off on this PC." };
16395
+ } else if (this.deps.exclude.includes(session)) {
16396
+ failure2 = { code: "TERM_NO_SESSION", message: `No session named "${session}".` };
16397
+ } else {
16398
+ try {
16399
+ applied = await this.apply(wire.channelId, command);
16400
+ } catch (error) {
16401
+ failure2 = { code: errorCode2(error), message: error instanceof Error ? error.message : String(error) };
16402
+ this.deps.log.write({ event: "remote_daemon_error", op: command.kind, session, code: failure2.code });
15184
16403
  }
15185
- this.deps.log.write({
15186
- event: "remote_command_result",
15187
- type: command.type,
15188
- ...session ? { session } : {},
15189
- ...requestId ? { requestId } : {},
16404
+ }
16405
+ const crud = command.kind === "create" || command.kind === "kill" || command.kind === "label";
16406
+ if (!crud && failure2) {
16407
+ this.logResult(wire, command.kind, session, false, failure2.code);
16408
+ await this.hooks.closeChannel(wire.channelId, failure2.code === "SESSION_REPLACED" ? "SESSION_REPLACED" : failure2.code === "REMOTE_OFF" ? "REMOTE_OFF" : "COMMAND_FAILED", browser);
16409
+ return;
16410
+ }
16411
+ if (command.kind === "create" && !failure2) {
16412
+ void this.deps.notifier.notify({
16413
+ kind: command.command !== void 0 && command.command.trim() !== "" ? "command" : "shell",
16414
+ keyId: browser.keyId,
16415
+ browserName: browser.name
16416
+ });
16417
+ }
16418
+ if (crud && !await this.answer(wire, command, applied, failure2)) return;
16419
+ const raised = this.book.executed(wire.channelId, wire.n);
16420
+ this.logResult(wire, command.kind, session, failure2 === void 0, failure2?.code, raised ? wire.n : void 0);
16421
+ if (raised) this.hooks.refreshChannel(wire.channelId);
16422
+ }
16423
+ /** CRUD 답 — 봉인 본문 {opId, kind, session?, instance?, ok, detail?} · 바깥 code 는 허용 목록만(A7). 봉인을 못 하면 채널을 닫고 false. */
16424
+ async answer(wire, command, applied, failure2) {
16425
+ const session = command.kind === "create" ? command.name : command.session;
16426
+ const projectUuid = command.kind === "create" ? command.projectUuid : void 0;
16427
+ let box;
16428
+ try {
16429
+ box = await this.book.seal(wire.channelId, { kind: "answer", session, opId: command.opId, ...projectUuid ? { projectUuid } : {} }, {
16430
+ opId: command.opId,
16431
+ kind: command.kind,
16432
+ session,
16433
+ ...applied.instance ? { instance: applied.instance } : {},
15190
16434
  ok: failure2 === void 0,
15191
- ...failure2 ? { code: failure2.code } : {}
16435
+ ...failure2 ? { detail: `${failure2.code}: ${failure2.message}` } : {}
15192
16436
  });
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
- }
16437
+ } catch (error) {
16438
+ const reason = error instanceof ChannelSealError && error.reason !== "CHANNEL_GONE" ? error.reason : "COMMAND_FAILED";
16439
+ this.logResult(wire, command.kind, session, false, failure2?.code ?? reason);
16440
+ await this.hooks.closeChannel(wire.channelId, reason);
16441
+ return false;
16442
+ }
16443
+ if (!wire.requestId) return true;
16444
+ try {
16445
+ await this.deps.http.call("answer", {
16446
+ linkId: this.linkId(),
16447
+ requestId: wire.requestId,
16448
+ channelId: wire.channelId,
16449
+ ...box,
16450
+ ok: failure2 === void 0,
16451
+ ...failure2 ? { code: answerCodeOf(failure2.code) } : {}
16452
+ }, { signal: this.stopSignal });
16453
+ } catch {
15203
16454
  }
15204
- if (listChanged) await ctx.syncList();
16455
+ return true;
16456
+ }
16457
+ logResult(wire, type, session, ok, code, executedThrough) {
16458
+ this.deps.log.write({
16459
+ event: "remote_command_result",
16460
+ type,
16461
+ channelId: wire.channelId,
16462
+ n: wire.n,
16463
+ session,
16464
+ ...wire.requestId ? { requestId: wire.requestId } : {},
16465
+ ok,
16466
+ ...code ? { code } : {},
16467
+ ...executedThrough !== void 0 ? { executedThrough } : {}
16468
+ });
15205
16469
  }
15206
- /** 명령 하나를 데몬에 — 목록이 바뀌었으면 true. */
15207
- async apply(command) {
15208
- switch (command.type) {
16470
+ /**
16471
+ * 명령 하나를 데몬에 — ★세션을 겨누는 명령은 인스턴스를 싣는다. 비교는 데몬이 적용하는 자리에서(§14-6 4 — 여기서 미리 보지 않는다).
16472
+ * 데몬 응답에 인스턴스가 없으면 옛 데몬이다(검사를 하지 않았다) — 실패로 친다.
16473
+ */
16474
+ async apply(channelId, command) {
16475
+ switch (command.kind) {
15209
16476
  case "input": {
15210
- let decoder = this.decoders.get(command.session);
16477
+ const key = `${channelId}\0${command.session}`;
16478
+ let decoder = this.decoders.get(key);
15211
16479
  if (!decoder) {
15212
16480
  decoder = new StringDecoder("utf8");
15213
- this.decoders.set(command.session, decoder);
16481
+ this.decoders.set(key, decoder);
15214
16482
  }
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;
16483
+ const text2 = decoder.write(command.bytes);
16484
+ if (text2 === "") return {};
16485
+ return { ...checked(await this.control.request({
16486
+ op: "send",
16487
+ name: command.session,
16488
+ text: text2,
16489
+ paste: false,
16490
+ instance: command.instance
16491
+ })) };
15218
16492
  }
15219
16493
  case "key":
15220
- await this.control.request({ op: "key", name: command.session, key: command.key });
15221
- return false;
16494
+ return { ...checked(await this.control.request({
16495
+ op: "key",
16496
+ name: command.session,
16497
+ key: command.key,
16498
+ instance: command.instance
16499
+ })) };
15222
16500
  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;
16501
+ const result = await termRequest(this.deps.paths, {
16502
+ op: "set-size",
16503
+ name: command.session,
16504
+ cols: command.cols,
16505
+ rows: command.rows,
16506
+ instance: command.instance
16507
+ }, { start: false });
16508
+ if (!result.daemon) throw new TermError("TERM_DAEMON_GONE", "No term daemon is running.");
16509
+ const applied = appliedSize(result.data);
15229
16510
  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;
16511
+ const instance = checked(result.data);
16512
+ this.hooks.resized(command.session, applied);
16513
+ return instance;
15232
16514
  }
15233
16515
  case "create": {
15234
16516
  const project = command.projectUuid;
@@ -15238,7 +16520,7 @@ var CommandRunner = class {
15238
16520
  let cwd = command.cwd;
15239
16521
  let made;
15240
16522
  if (cwd === void 0) {
15241
- const fresh = await this.sessionFolder(project, command.requestId);
16523
+ const fresh = await this.sessionFolder(project, command.opId);
15242
16524
  cwd = fresh.folder;
15243
16525
  if (fresh.made) made = fresh.folder;
15244
16526
  }
@@ -15253,26 +16535,62 @@ var CommandRunner = class {
15253
16535
  ...project !== void 0 ? { project } : {}
15254
16536
  });
15255
16537
  } catch (error) {
15256
- if (made) await this.dropSessionFolder(command.requestId, made);
16538
+ if (made) await this.dropSessionFolder(command.opId, made);
15257
16539
  throw error;
15258
16540
  }
15259
16541
  if (project !== void 0 && createdProject(created) !== project) {
15260
- this.deps.log.write({ event: "remote_create_project_dropped", requestId: command.requestId, session: command.name });
16542
+ this.deps.log.write({ event: "remote_create_project_dropped", opId: command.opId, session: command.name });
15261
16543
  }
15262
- return true;
16544
+ const instance = sessionInstance(created);
16545
+ return instance ? { instance } : {};
16546
+ }
16547
+ case "kill": {
16548
+ const instance = checked(await this.control.request({ op: "kill", name: command.session, instance: command.instance }));
16549
+ this.forgetSession(command.session);
16550
+ return instance;
15263
16551
  }
15264
- case "kill":
15265
- await this.control.request({ op: "kill", name: command.session });
15266
- this.decoders.delete(command.session);
15267
- return true;
15268
16552
  case "label": {
15269
- const result = await termRequest(this.deps.paths, { op: "label", name: command.session, label: command.label }, { start: false });
16553
+ const result = await termRequest(
16554
+ this.deps.paths,
16555
+ { op: "label", name: command.session, label: command.label, instance: command.instance },
16556
+ { start: false }
16557
+ );
15270
16558
  if (!result.daemon) throw new TermError("TERM_DAEMON_GONE", "No term daemon is running.");
15271
- return true;
16559
+ return checked(result.data);
15272
16560
  }
15273
16561
  }
15274
16562
  }
16563
+ forgetSession(session) {
16564
+ for (const key of this.decoders.keys()) {
16565
+ if (key.endsWith(`\0${session}`)) this.decoders.delete(key);
16566
+ }
16567
+ }
16568
+ /**
16569
+ * 웹이 폴더를 비운 만들기 — {@link webSessionFolder}(꼬리표가 있으면 프로젝트 아래)를 만든다. 폴더 이름은 브라우저가 봉인 전에 정한
16570
+ * 연산 ID(UUID — 만들기마다 새 값, §12-2)라 세션마다 새 폴더가 되고, remote_command 로그 줄(같은 opId)로 어느 만들기의 폴더인지 잇는다.
16571
+ */
16572
+ async sessionFolder(projectUuid, opId) {
16573
+ const folder = webSessionFolder(this.deps.appHome, projectUuid, opId);
16574
+ const made = !existsSync(folder);
16575
+ await ensurePrivateDir(folder);
16576
+ return { folder, made };
16577
+ }
16578
+ /** 거절된 만들기 — 방금 만든 세션 폴더를 비어 있을 때만 지운다(rmdir, 재귀 아님). 못 지우면 한 줄 남기고 넘어간다. */
16579
+ async dropSessionFolder(opId, folder) {
16580
+ try {
16581
+ await rmdir2(folder);
16582
+ } catch (error) {
16583
+ this.deps.log.write({ event: "remote_session_folder_kept", opId, code: errorCode2(error) });
16584
+ }
16585
+ }
15275
16586
  };
16587
+ function checked(data) {
16588
+ const instance = sessionInstance(data);
16589
+ if (!instance) {
16590
+ 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`.");
16591
+ }
16592
+ return { instance };
16593
+ }
15276
16594
  function answerSummary(body) {
15277
16595
  return {
15278
16596
  ...typeof body.state === "string" ? { state: body.state } : {},
@@ -15294,62 +16612,33 @@ function serverLimits2(value) {
15294
16612
  function remoteStateOf(value) {
15295
16613
  return value === "on" || value === "off-by-pc" || value === "off-by-web" ? value : void 0;
15296
16614
  }
15297
- function watchingOf(answer) {
15298
- return Array.isArray(answer.watching) ? answer.watching.filter((name) => typeof name === "string" && name !== "") : [];
15299
- }
15300
- function remoteCommands(answer) {
16615
+ function pollItems(answer) {
15301
16616
  if (!Array.isArray(answer.commands)) return [];
15302
16617
  return answer.commands.flatMap((raw) => {
15303
16618
  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 }] : [];
16619
+ const item = raw;
16620
+ const channelId = typeof item.channelId === "string" && item.channelId !== "" ? item.channelId : void 0;
16621
+ switch (item.type) {
16622
+ case "hello":
16623
+ return channelId ? [{ type: "hello", channelId, hello: item.hello }] : [];
16624
+ case "cmd": {
16625
+ const command = wireCommand(item);
16626
+ if (command) return [{ type: "cmd", command }];
16627
+ return channelId ? [{ type: "bad-cmd", channelId, n: typeof item.n === "number" ? item.n : -1 }] : [];
15341
16628
  }
16629
+ case "watch":
16630
+ return [{ type: "watch", channels: Array.isArray(item.channels) ? item.channels.flatMap((entry) => {
16631
+ if (!entry || typeof entry !== "object") return [];
16632
+ const watch = entry;
16633
+ return typeof watch.channelId === "string" && watch.channelId !== "" && typeof watch.session === "string" && watch.session !== "" ? [{ channelId: watch.channelId, session: watch.session }] : [];
16634
+ }) : [] }];
16635
+ case "channel-closed":
16636
+ return channelId ? [{ type: "channel-closed", channelId }] : [];
15342
16637
  default:
15343
16638
  return [];
15344
16639
  }
15345
16640
  });
15346
16641
  }
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
16642
 
15354
16643
  // src/core/pc/pcSession.ts
15355
16644
  var PC_SESSION_NAME = "ainecto-pc";
@@ -15454,8 +16743,212 @@ function pcOutcome(lines) {
15454
16743
  return failed === void 0 ? void 0 : { kind: "failed", line: failed };
15455
16744
  }
15456
16745
 
16746
+ // src/core/pc/pcPairing.ts
16747
+ var PAIR_WAIT_MS = 5 * 6e4;
16748
+ async function runPairing(input) {
16749
+ const deadline = new AbortController();
16750
+ const timer = setTimeout(() => deadline.abort(), input.waitMs);
16751
+ let cancelled = false;
16752
+ const onCancel = () => {
16753
+ cancelled = true;
16754
+ deadline.abort();
16755
+ };
16756
+ input.cancel?.addEventListener("abort", onCancel, { once: true });
16757
+ if (input.cancel?.aborted) onCancel();
16758
+ const { signal } = deadline;
16759
+ const relayed = async (step) => {
16760
+ try {
16761
+ return await step();
16762
+ } catch (error) {
16763
+ if (signal.aborted) return "timeout";
16764
+ throw error;
16765
+ }
16766
+ };
16767
+ let outcome;
16768
+ try {
16769
+ outcome = await pairOnce();
16770
+ if (cancelled && outcome.kind === "timeout") outcome = { kind: "cancelled" };
16771
+ return outcome;
16772
+ } finally {
16773
+ clearTimeout(timer);
16774
+ input.cancel?.removeEventListener("abort", onCancel);
16775
+ if (outcome?.kind !== "paired") await input.transport.abort(outcome?.kind ?? "error");
16776
+ }
16777
+ async function pairOnce() {
16778
+ const pcPublicRaw = publicRawFromJwk(input.pcKey);
16779
+ const nP = (input.random ?? (() => randomBytes3(NONCE_SEED_BYTES)))();
16780
+ const commit = await pairCommitment(pcPublicRaw, nP);
16781
+ const { check } = input;
16782
+ if (check.kind === "codes") {
16783
+ check.prompt.show(`Waiting up to ${Math.round(input.waitMs / 6e4)} min for a browser \u2014 in AiNecto on the web, open Terminal, pick this PC and start the browser registration there.`);
16784
+ }
16785
+ const offer = await relayed(() => input.transport.offer(commit, signal));
16786
+ if (offer === "timeout") return { kind: "timeout" };
16787
+ const publicJwk = publicJwkFromRaw(offer.publicRaw);
16788
+ await assertSigningPublicKey(publicJwk);
16789
+ if (offer.keyId !== await browserKeyIdOf(offer.publicRaw)) {
16790
+ throw new E2eError("E2E_BAD_INPUT", "The browser's key id is not the fingerprint of its key \u2014 browser registration aborted.");
16791
+ }
16792
+ const browser = { keyId: offer.keyId, publicJwk, name: browserNameOf(offer.name) };
16793
+ const transcript = () => pairTranscript({ userId: input.userId, pcId: input.pcId, pcPublicRaw, browserPublicRaw: offer.publicRaw, nP, nB: offer.nB });
16794
+ if (check.kind === "secret") {
16795
+ const keys = await registerKeys(check.secret);
16796
+ const expected = await registerOfferMac(keys.browser, {
16797
+ userId: input.userId,
16798
+ pcId: input.pcId,
16799
+ attemptId: offer.attemptId,
16800
+ commit,
16801
+ browserPublicRaw: offer.publicRaw,
16802
+ keyId: offer.keyId,
16803
+ nB: offer.nB,
16804
+ name: offer.name
16805
+ });
16806
+ if (!offer.macB || !macEquals(offer.macB, expected)) return { kind: "code-mismatch" };
16807
+ const t2 = await transcript();
16808
+ await input.pin(browser);
16809
+ const macP = await registerRevealMac(keys.pc, { transcript: t2, attemptId: offer.attemptId });
16810
+ return await finish(browser, t2, () => input.transport.reveal(pcPublicRaw, nP, signal, macP));
16811
+ }
16812
+ if (await relayed(() => input.transport.reveal(pcPublicRaw, nP, signal)) === "timeout") return { kind: "timeout" };
16813
+ const t = await transcript();
16814
+ const codes = await pairCodes(t);
16815
+ check.prompt.show(`A browser asked to be registered: ${browser.name}`);
16816
+ check.prompt.show(`Type this code in the browser: ${codes.a}`);
16817
+ const answer = await check.prompt.ask("Then type the code the browser shows (one try): ", signal);
16818
+ if (signal.aborted) return { kind: "timeout" };
16819
+ const typed = pairCodeInput(answer);
16820
+ if (typed.kind === "empty") return { kind: "cancelled" };
16821
+ if (typed.kind !== "code" || typed.code !== codes.b) return { kind: "code-mismatch" };
16822
+ await input.pin(browser);
16823
+ return await finish(browser, t);
16824
+ }
16825
+ async function finish(browser, transcript, before) {
16826
+ const signature = await signBytes(await importSigningKey(input.pcKey), pairDoneInput(transcript));
16827
+ let doneError;
16828
+ try {
16829
+ await before?.();
16830
+ await input.transport.done(signature, signal);
16831
+ } catch (error) {
16832
+ doneError = signal.aborted ? "timed out" : error instanceof Error ? error.message : String(error);
16833
+ }
16834
+ return { kind: "paired", browser, doneError };
16835
+ }
16836
+ }
16837
+
15457
16838
  // src/adapters/cli/pcCommand.ts
15458
- import { readFile as readFile11 } from "fs/promises";
16839
+ import { readFile as readFile13 } from "fs/promises";
16840
+
16841
+ // src/adapters/cli/pairCommand.ts
16842
+ import { randomUUID as randomUUID7 } from "crypto";
16843
+ import { closeSync as closeSync3, openSync as openSync3 } from "fs";
16844
+ import { ReadStream, WriteStream } from "tty";
16845
+
16846
+ // src/core/pc/pcPairRelay.ts
16847
+ var PairRelayError = class extends Error {
16848
+ constructor(code, message2) {
16849
+ super(message2);
16850
+ this.code = code;
16851
+ }
16852
+ code;
16853
+ };
16854
+ function createPairRelay(input) {
16855
+ const http = createPcHttp({
16856
+ endpoint: input.endpoint,
16857
+ path: "term/pc",
16858
+ tokenProvider: input.tokenProvider,
16859
+ timeoutMs: CALL_TIMEOUT_MS,
16860
+ sessionHeader: "X-Remote-Token",
16861
+ fetchImpl: input.fetchImpl,
16862
+ logging: {
16863
+ log: input.log,
16864
+ request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
16865
+ response: ({ callId, op, ms }, outcome) => ({
16866
+ event: "remote_call_response",
16867
+ callId,
16868
+ op,
16869
+ ...outcome.ok ? {
16870
+ ok: true,
16871
+ status: outcome.status,
16872
+ ...Array.isArray(outcome.body.msgs) ? { commands: outcome.body.msgs.length } : {},
16873
+ ...outcome.body.closed === true ? { state: "CLOSED" } : {}
16874
+ } : outcome,
16875
+ ms
16876
+ })
16877
+ }
16878
+ });
16879
+ let attemptId;
16880
+ let finished = false;
16881
+ const send = async (msg, signal) => {
16882
+ if (!attemptId) throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "The browser registration was not opened.");
16883
+ await http.call("pair/send", { attemptId, msg }, signal ? { signal } : void 0);
16884
+ };
16885
+ return {
16886
+ async offer(commit, signal) {
16887
+ const opened = await http.call("pair/open", { pcId: input.pcId }, { signal });
16888
+ if (typeof opened.attemptId !== "string" || opened.attemptId === "") {
16889
+ throw new PairRelayError("PAIR_RELAY_BAD_RESPONSE", "AiNecto answered pair/open without an attemptId.");
16890
+ }
16891
+ attemptId = opened.attemptId;
16892
+ await send({ type: "commit", commit: b64u2(commit) }, signal);
16893
+ for (; ; ) {
16894
+ const answer = await http.call("pair/poll", { attemptId }, { holdMs: input.holdMs, signal });
16895
+ if (answer.closed === true) {
16896
+ finished = true;
16897
+ throw new PairRelayError("PAIR_CLOSED", "The browser registration ended on AiNecto (the browser cancelled it, or it expired).");
16898
+ }
16899
+ const offer = offerOf(Array.isArray(answer.msgs) ? answer.msgs : []);
16900
+ if (offer === "abort") {
16901
+ finished = true;
16902
+ throw new PairRelayError("PAIR_CLOSED", "The browser cancelled the registration.");
16903
+ }
16904
+ if (offer) return { ...offer, attemptId };
16905
+ }
16906
+ },
16907
+ async reveal(pcPublicRaw, nP, signal, macP) {
16908
+ await send({ type: "reveal", publicKey: b64u2(pcPublicRaw), nP: b64u2(nP), ...macP ? { macP: b64u2(macP) } : {} }, signal);
16909
+ },
16910
+ async done(signature, signal) {
16911
+ await send({ type: "done", signature: b64u2(signature) }, signal);
16912
+ finished = true;
16913
+ },
16914
+ async abort(reason) {
16915
+ if (!attemptId || finished) return;
16916
+ finished = true;
16917
+ try {
16918
+ await send({ type: "abort", reason });
16919
+ } catch {
16920
+ }
16921
+ }
16922
+ };
16923
+ }
16924
+ function offerOf(msgs) {
16925
+ if (msgs.length === 0) return void 0;
16926
+ const items = msgs.map((msg) => msg && typeof msg === "object" ? msg : {});
16927
+ if (items.some((item2) => item2.type === "abort")) return "abort";
16928
+ if (items.length > 1) {
16929
+ throw new PairRelayError("PAIR_DUPLICATE", "More than one browser registration request arrived \u2014 this try was ended. Run `ainecto pair` again.");
16930
+ }
16931
+ const [item] = items;
16932
+ const publicRaw = fromB64u2(item?.publicKey, PUBLIC_KEY_BYTES);
16933
+ const nB = fromB64u2(item?.nB, NONCE_SEED_BYTES);
16934
+ const macB = item?.macB === void 0 ? void 0 : fromB64u2(
16935
+ item.macB,
16936
+ 32
16937
+ /* HMAC-SHA256 */
16938
+ );
16939
+ if (item?.type !== "offer" || !publicRaw || !nB || typeof item.keyId !== "string" || typeof item.name !== "string" || item.macB !== void 0 && !macB) {
16940
+ throw new PairRelayError("PAIR_BAD_MESSAGE", "AiNecto relayed a browser registration message this CLI does not understand \u2014 this try was ended.");
16941
+ }
16942
+ return { keyId: item.keyId, publicRaw, nB, name: item.name, ...macB ? { macB } : {} };
16943
+ }
16944
+ function b64u2(bytes) {
16945
+ return Buffer.from(bytes).toString("base64url");
16946
+ }
16947
+ function fromB64u2(value, length) {
16948
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]+$/.test(value)) return void 0;
16949
+ const bytes = new Uint8Array(Buffer.from(value, "base64url"));
16950
+ return bytes.length === length ? bytes : void 0;
16951
+ }
15459
16952
 
15460
16953
  // src/adapters/cli/pcStartText.ts
15461
16954
  var DOCTOR_ONLY = /* @__PURE__ */ new Set(["AiNecto job title"]);
@@ -15488,11 +16981,209 @@ function pcResultText(result) {
15488
16981
  const use = result.agentMissing ? "From AiNecto on the web you can open a terminal on this PC and run commands. No Claude Code or Codex was found, so AiNecto agent work cannot run here yet \u2014 install one, then run `ainecto` again." : "From AiNecto on the web you can open a terminal on this PC and run commands, and your AiNecto agent can run work here (Claude Code or Codex).";
15489
16982
  return `This PC is now connected to AiNecto. ${use} It keeps running after you close this window. ${STOP} Log: ${result.log}`;
15490
16983
  }
16984
+ function pcNotApprovedText(hostName, then) {
16985
+ return `This PC (${hostName}) is not connected to AiNecto yet. Run \`npx -y ainecto@latest\` in a terminal on this PC first and approve the connection${then ? `, then ${then}` : ""}.`;
16986
+ }
15491
16987
  function listed(labels) {
15492
16988
  if (labels.length <= 2) return labels.join(" and ");
15493
16989
  return `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
15494
16990
  }
15495
16991
 
16992
+ // src/adapters/cli/pairCommand.ts
16993
+ var USAGE = "Usage: ainecto pair [--list | --remove <keyId|name>]";
16994
+ function openDevTty() {
16995
+ const terminal = controllingTerminal();
16996
+ let inFd;
16997
+ try {
16998
+ inFd = openSync3(terminal.input, terminal.inputFlags);
16999
+ const outFd = openSync3(terminal.output, terminal.outputFlags);
17000
+ const stdin = new ReadStream(inFd);
17001
+ const stderr = new WriteStream(outFd);
17002
+ return { stdin, stderr, close: () => {
17003
+ stdin.destroy();
17004
+ stderr.destroy();
17005
+ } };
17006
+ } catch (error) {
17007
+ if (inFd !== void 0) closeSync3(inFd);
17008
+ throw new CliCommandError("PAIR_NO_TTY", `\`ainecto pair\` needs this PC's terminal (${terminal.input}): ${error instanceof Error ? error.message : String(error)}`);
17009
+ }
17010
+ }
17011
+ async function executePair(deps, argv) {
17012
+ const [first, ...rest] = argv;
17013
+ if (first === "--list" && rest.length === 0) {
17014
+ return await listBrowsers(deps);
17015
+ }
17016
+ if (first === "--remove" && rest.length === 1 && rest[0] !== void 0 && rest[0] !== "") {
17017
+ return await removeBrowser(deps, rest[0]);
17018
+ }
17019
+ if (first !== void 0) {
17020
+ throw new CliCommandError("USAGE", USAGE);
17021
+ }
17022
+ return await pair(deps);
17023
+ }
17024
+ async function pair(deps) {
17025
+ const interactive = deps.interactive && !deps.json;
17026
+ if (interactive && deps.insideTermSession) {
17027
+ throw new CliCommandError(
17028
+ "PAIR_IN_TERM_SESSION",
17029
+ "`ainecto pair` does not run inside an AiNecto terminal session (its screen can be shown on the web). Run it in a regular terminal on this PC."
17030
+ );
17031
+ }
17032
+ let approved = await approvedAccount(deps, { strict: !interactive });
17033
+ if (!approved && interactive) {
17034
+ const code = await deps.connectPc();
17035
+ if (code !== 0) return code;
17036
+ approved = await approvedAccount(deps, { strict: false });
17037
+ if (approved) deps.io.stderr.write("\nNext: register this browser with this PC.\n");
17038
+ }
17039
+ if (!approved) {
17040
+ throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName, "run `npx -y ainecto@latest pair` to register this browser"));
17041
+ }
17042
+ if (!interactive) {
17043
+ throw new CliCommandError(
17044
+ "PAIR_INTERACTIVE_ONLY",
17045
+ "`ainecto pair` shows a code and asks you to type the code the browser shows \u2014 run it yourself in a terminal (not with --json or a pipe)."
17046
+ );
17047
+ }
17048
+ const { key, userId, settings } = approved;
17049
+ const pcKey = (await loadPcKeys(deps.keysPath)).accounts[key]?.pcKey ?? await generateSigningJwk();
17050
+ const transport = await deps.transport(settings.pcId);
17051
+ const tty = deps.openTty();
17052
+ let outcome;
17053
+ try {
17054
+ outcome = await relayErrors(() => runPairing({
17055
+ userId: transcriptUserId(userId),
17056
+ pcId: settings.pcId,
17057
+ pcKey,
17058
+ transport,
17059
+ check: { kind: "codes", prompt: { show: (line) => {
17060
+ tty.stderr.write(`${line}
17061
+ `);
17062
+ }, ask: (question, signal) => promptLine(tty, question, signal) } },
17063
+ pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key, pcKey, browser: browser2, now: deps.now() }),
17064
+ waitMs: deps.waitMs
17065
+ }));
17066
+ } finally {
17067
+ tty.close();
17068
+ }
17069
+ if (outcome.kind === "timeout") {
17070
+ throw new CliCommandError("PAIR_TIMEOUT", "Browser registration did not finish in time. Nothing was saved \u2014 run `ainecto pair` again.");
17071
+ }
17072
+ if (outcome.kind === "cancelled") {
17073
+ throw new CliCommandError("PAIR_CANCELLED", "Browser registration cancelled. Nothing was saved \u2014 run `ainecto pair` again.");
17074
+ }
17075
+ if (outcome.kind === "code-mismatch") {
17076
+ throw new CliCommandError(
17077
+ "PAIR_CODE_MISMATCH",
17078
+ "That code does not match. Nothing was saved \u2014 start again with `ainecto pair` (if you typed it right, someone may be in the middle)."
17079
+ );
17080
+ }
17081
+ const { browser, doneError } = outcome;
17082
+ if (doneError !== void 0) {
17083
+ throw new CliCommandError("PAIR_DONE_FAILED", `Saved "${browser.name}" on this PC, but the browser did not get the confirmation (${doneError}), so it will not trust this PC yet. Remove it with \`ainecto pair --remove ${browser.keyId}\` and run \`ainecto pair\` again.`);
17084
+ }
17085
+ await deps.notifyPaired({ keyId: browser.keyId, name: browser.name });
17086
+ const lines = [`Registered the browser "${browser.name}" with this PC. Remove it later with \`ainecto pair --remove ${browser.keyId}\`.`];
17087
+ if (settings.accounts[key]?.remoteTerminal !== true) {
17088
+ lines.push("Terminals from the web are blocked on this PC \u2014 `ainecto remote on` allows them.");
17089
+ }
17090
+ deps.io.stdout.write(`${lines.join("\n")}
17091
+ `);
17092
+ return 0;
17093
+ }
17094
+ async function pinBrowser(input) {
17095
+ const { key, pcKey, browser } = input;
17096
+ await updatePcKeys(input.keysPath, (latest) => {
17097
+ const stored = latest.accounts[key]?.pcKey;
17098
+ if (stored && stored.d !== pcKey.d) {
17099
+ throw new CliCommandError("PAIR_CONFLICT", "This PC's key changed during browser registration (another `ainecto pair`?). Nothing was saved \u2014 run `ainecto pair` again.");
17100
+ }
17101
+ if (latest.accounts[key]?.pendingTurnOff?.removals.some((item) => item.keyId === browser.keyId)) {
17102
+ throw new CliCommandError("PAIR_REMOVE_PENDING", `This browser's earlier removal has not finished. Nothing was saved \u2014 run \`ainecto pair --remove ${browser.keyId}\` first, then \`ainecto pair\` again.`);
17103
+ }
17104
+ return withBrowser(latest, key, pcKey, { ...browser, pairedAt: input.now.toISOString() });
17105
+ });
17106
+ }
17107
+ async function listBrowsers(deps) {
17108
+ const browsers = (await loadPcKeys(deps.keysPath)).accounts[(await account(deps)).key]?.browsers ?? [];
17109
+ const data = { browsers: browsers.map((item) => ({ keyId: item.keyId, name: item.name, pairedAt: item.pairedAt })) };
17110
+ const human = browsers.length === 0 ? "No browsers are registered with this PC. Run `ainecto pair` to register one." : ["Browsers registered with this PC:", ...browsers.map((item) => ` ${item.keyId} ${item.name} (registered ${item.pairedAt})`)].join("\n");
17111
+ deps.io.stdout.write(deps.json ? renderSuccess(data, { json: true }) : `${human}
17112
+ `);
17113
+ return 0;
17114
+ }
17115
+ async function removeBrowser(deps, keyIdOrName) {
17116
+ const { key } = await account(deps);
17117
+ let removed;
17118
+ let target;
17119
+ await updatePcKeys(deps.keysPath, (keys) => {
17120
+ const result = withoutBrowser(keys, key, keyIdOrName);
17121
+ removed = result.removed;
17122
+ if (!removed) {
17123
+ target = pendingRemovalOf(keys.accounts[key], keyIdOrName);
17124
+ return void 0;
17125
+ }
17126
+ target = { removalId: randomUUID7(), keyId: removed.keyId, name: removed.name };
17127
+ return withPendingTurnOff(result.keys, key, { at: deps.now(), groups: [], removal: target });
17128
+ });
17129
+ if (!target) {
17130
+ throw new CliCommandError("PAIR_NOT_FOUND", `No registered browser with key id or name "${keyIdOrName}" \u2014 \`ainecto pair --list\` shows them.`);
17131
+ }
17132
+ const { keyId: finished, removalId } = target;
17133
+ let groups;
17134
+ try {
17135
+ const found = await deps.findPcs();
17136
+ const saved = await updatePcKeys(deps.keysPath, (keys) => {
17137
+ const next = withPendingTurnOff(keys, key, { at: deps.now(), groups: found });
17138
+ return next === keys ? void 0 : next;
17139
+ });
17140
+ groups = saved.accounts[key]?.pendingTurnOff?.groups ?? found;
17141
+ await deps.turnOffPcs(groups);
17142
+ } catch (error) {
17143
+ throw new CliCommandError("PAIR_REMOVE_STOP_FAILED", `${removed ? `Removed "${removed.name}" (${removed.keyId}), but t` : "T"}urning off the PC connection was not confirmed (${error instanceof Error ? error.message : String(error)}). Run \`ainecto pair --remove ${finished}\` again to finish.`);
17144
+ }
17145
+ await updatePcKeys(deps.keysPath, (keys) => {
17146
+ const next = withTurnOffConfirmed(keys, key, { groups, removalId });
17147
+ return next === keys ? void 0 : next;
17148
+ });
17149
+ const lines = [removed ? `Removed "${removed.name}" (${removed.keyId}). It can no longer open terminals on this PC.` : "Finished the earlier removal."];
17150
+ lines.push(groups.length > 0 ? "Turned off the PC connection. Run `ainecto` to turn it back on." : "The PC connection is not running.");
17151
+ deps.io.stdout.write(deps.json ? renderSuccess({ removed: removed ? { keyId: removed.keyId, name: removed.name } : null, turnedOff: groups }, { json: true }) : `${lines.join("\n")}
17152
+ `);
17153
+ return 0;
17154
+ }
17155
+ async function relayErrors(run) {
17156
+ try {
17157
+ return await run();
17158
+ } catch (error) {
17159
+ if (error instanceof PairRelayError) {
17160
+ throw new CliCommandError(error.code, `${error.message} Nothing was saved \u2014 run \`ainecto pair\` again.`);
17161
+ }
17162
+ if (error instanceof PcCallError) {
17163
+ throw new CliCommandError("PAIR_RELAY_FAILED", `Could not reach AiNecto for browser registration (${error.op}: ${error.status ?? "-"} ${error.code ?? ""} ` + `${error.message}`.replace(/\s+/g, " ").trim() + "). Nothing was saved \u2014 run `ainecto pair` again.");
17164
+ }
17165
+ throw error;
17166
+ }
17167
+ }
17168
+ async function approvedAccount(deps, options) {
17169
+ const userId = (await deps.account()).userId;
17170
+ if (!userId) {
17171
+ if (options.strict) throw accountUnknown();
17172
+ return void 0;
17173
+ }
17174
+ const key = accountKey(deps.endpoint, userId);
17175
+ const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
17176
+ return settings.accounts[key] ? { key, userId, settings } : void 0;
17177
+ }
17178
+ async function account(deps) {
17179
+ const userId = (await deps.account()).userId;
17180
+ if (!userId) throw accountUnknown();
17181
+ return { key: accountKey(deps.endpoint, userId), userId };
17182
+ }
17183
+ function accountUnknown() {
17184
+ return new CliCommandError("PC_ACCOUNT_UNKNOWN", "Could not read your AiNecto account \u2014 run `ainecto doctor` to see why.");
17185
+ }
17186
+
15496
17187
  // src/adapters/cli/pcCommand.ts
15497
17188
  async function executePcStart(deps) {
15498
17189
  assertTerm(deps);
@@ -15527,7 +17218,7 @@ async function executePcStart(deps) {
15527
17218
  let settings = await loadPcSettings(deps.settingsPath, deps.hostName);
15528
17219
  if (!settings.accounts[key]) {
15529
17220
  if (!deps.interactive) {
15530
- throw new CliCommandError("PC_NOT_APPROVED", "This PC is not connected yet \u2014 run `ainecto` in a terminal once to approve.");
17221
+ throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName));
15531
17222
  }
15532
17223
  note("");
15533
17224
  note(`This connects this PC to AiNecto as ${status.account?.displayName ?? "your account"} (${deps.endpoint}).`);
@@ -15545,15 +17236,15 @@ async function executePcStart(deps) {
15545
17236
  const action = pcAction(runningPcs(await listed2(deps)), deps.cliVersion);
15546
17237
  if (action.kind === "already") {
15547
17238
  if (!remoteOffByWeb(await screenLines2(deps, action.pc.session))) {
15548
- return withNotes(deps, later, print2(
17239
+ return await withRegistration(deps, key, userId, withNotes(deps, later, print2(
15549
17240
  deps,
15550
17241
  { connected: true, already: true, ...pcView(deps, action.pc) },
15551
17242
  pcResultText({ kind: "already", folder: action.pc.cwd, version: pcVersionLabel(action.pc), log: deps.agentLog })
15552
- ));
17243
+ )));
15553
17244
  }
15554
17245
  note("The remote terminal was turned off from the web \u2014 reconnecting this PC to turn it back on\u2026");
15555
17246
  await stopPc(deps, action.pc);
15556
- return withNotes(deps, later, await launchPc(deps));
17247
+ return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
15557
17248
  }
15558
17249
  await prepare(deps);
15559
17250
  if (action.kind === "replace") {
@@ -15562,8 +17253,80 @@ async function executePcStart(deps) {
15562
17253
  await stopPc(deps, pc);
15563
17254
  }
15564
17255
  }
15565
- return withNotes(deps, later, await launchPc(deps));
17256
+ return await withRegistration(deps, key, userId, withNotes(deps, later, await launchPc(deps)));
17257
+ }
17258
+ async function withRegistration(deps, key, userId, code) {
17259
+ if (code === 0) await registerBrowserIfNone(deps, { key, userId });
17260
+ return code;
17261
+ }
17262
+ async function registerBrowserIfNone(deps, account2) {
17263
+ const register = deps.register;
17264
+ if (!register || !deps.interactive || deps.json || register.insideTermSession) return;
17265
+ const settings = await loadPcSettings(deps.settingsPath, deps.hostName);
17266
+ if (settings.accounts[account2.key]?.remoteTerminal !== true) return;
17267
+ const stored = (await loadPcKeys(deps.keysPath)).accounts[account2.key];
17268
+ if ((stored?.browsers.length ?? 0) > 0) return;
17269
+ const note = (line) => {
17270
+ deps.io.stderr.write(`${line}
17271
+ `);
17272
+ };
17273
+ const noBrowser = "This PC can't open a browser here. To register this browser, run `npx -y ainecto@latest pair` in this PC's terminal.";
17274
+ if (register.overSsh) {
17275
+ note(noBrowser);
17276
+ return;
17277
+ }
17278
+ const userId = transcriptUserId(account2.userId);
17279
+ const secret = randomBytes3(NONCE_SEED_BYTES);
17280
+ const interrupt = register.interrupt();
17281
+ let outcome;
17282
+ try {
17283
+ const tag = await registerTag((await registerKeys(secret)).account, userId);
17284
+ const url = `${new URL(deps.endpoint).origin}${REGISTER_PATH}#${registerFragment({ pcId: settings.pcId, tag, secret })}`;
17285
+ try {
17286
+ await register.openBrowser(url);
17287
+ } catch {
17288
+ note(noBrowser);
17289
+ return;
17290
+ }
17291
+ note("");
17292
+ note(`Finish in the browser that just opened (up to ${Math.round(register.waitMs / 6e4)} min \xB7 Ctrl+C to skip)`);
17293
+ const pcKey = stored?.pcKey ?? await generateSigningJwk();
17294
+ outcome = await runPairing({
17295
+ userId,
17296
+ pcId: settings.pcId,
17297
+ pcKey,
17298
+ transport: await register.transport(settings.pcId),
17299
+ check: { kind: "secret", secret },
17300
+ pin: (browser2) => pinBrowser({ keysPath: deps.keysPath, key: account2.key, pcKey, browser: browser2, now: register.now() }),
17301
+ waitMs: register.waitMs,
17302
+ cancel: interrupt.signal
17303
+ });
17304
+ } catch (error) {
17305
+ note(`Browser registration did not finish (${error instanceof Error ? error.message : String(error)}). ${REGISTER_AGAIN}`);
17306
+ return;
17307
+ } finally {
17308
+ interrupt.dispose();
17309
+ secret.fill(0);
17310
+ }
17311
+ if (outcome.kind !== "paired") {
17312
+ const why = outcome.kind === "timeout" ? "timed out" : outcome.kind === "cancelled" ? "skipped" : "the browser could not be verified";
17313
+ note(`Browser registration did not finish (${why}). Nothing was saved. ${REGISTER_AGAIN}`);
17314
+ return;
17315
+ }
17316
+ const { browser, doneError } = outcome;
17317
+ if (doneError !== void 0) {
17318
+ await updatePcKeys(deps.keysPath, (keys) => {
17319
+ const result = withoutBrowser(keys, account2.key, browser.keyId);
17320
+ return result.removed ? result.keys : void 0;
17321
+ });
17322
+ note(`The browser "${browser.name}" did not get the confirmation (${doneError}), so nothing was kept. ${REGISTER_AGAIN}`);
17323
+ return;
17324
+ }
17325
+ await register.notifyPaired({ keyId: browser.keyId, name: browser.name });
17326
+ deps.io.stdout.write(`Registered "${browser.name}" with this PC. Remove it later with \`ainecto pair --remove ${browser.keyId}\`.
17327
+ `);
15566
17328
  }
17329
+ var REGISTER_AGAIN = "Try again: `npx -y ainecto@latest` \xB7 or register this browser with `npx -y ainecto@latest pair`.";
15567
17330
  function withNotes(deps, notes, code) {
15568
17331
  for (const line of notes) deps.io.stderr.write(`${line}
15569
17332
  `);
@@ -15633,7 +17396,7 @@ function reportOutcome(deps, outcome) {
15633
17396
  async function lastLogLineSince(path, since) {
15634
17397
  let text2;
15635
17398
  try {
15636
- text2 = await readFile11(path, "utf8");
17399
+ text2 = await readFile13(path, "utf8");
15637
17400
  } catch (error) {
15638
17401
  if (isNodeError(error, "ENOENT")) return void 0;
15639
17402
  throw error;
@@ -15664,6 +17427,15 @@ async function executePcStop(deps, argv) {
15664
17427
  if (forget) {
15665
17428
  await savePcSettings(deps.settingsPath, withoutEndpoint(await loadPcSettings(deps.settingsPath, deps.hostName), deps.endpoint));
15666
17429
  lines.push(`Removed your approval for ${deps.endpoint} on this PC; \`ainecto\` asks again next time.`);
17430
+ let removedKeys = false;
17431
+ await updatePcKeys(deps.keysPath, (keys) => {
17432
+ const kept = withoutEndpointKeys(keys, deps.endpoint);
17433
+ removedKeys = Object.keys(kept.accounts).length !== Object.keys(keys.accounts).length;
17434
+ return removedKeys ? kept : void 0;
17435
+ });
17436
+ if (removedKeys) {
17437
+ lines.push("Also removed this PC's terminal key and registered browsers for that server \u2014 register them again with `ainecto pair`.");
17438
+ }
15667
17439
  }
15668
17440
  return print2(deps, { stopped: running.map((pc) => pc.session), forgot: forget }, lines.join("\n"));
15669
17441
  }
@@ -15678,13 +17450,14 @@ async function executeRemoteSetting(deps, argv) {
15678
17450
  }
15679
17451
  const next = withRemoteTerminal(await loadPcSettings(deps.settingsPath, deps.hostName), accountKey(deps.endpoint, userId), value === "on");
15680
17452
  if (!next) {
15681
- throw new CliCommandError("PC_NOT_APPROVED", "This PC is not connected yet \u2014 run `ainecto` in a terminal once to approve.");
17453
+ throw new CliCommandError("PC_NOT_APPROVED", pcNotApprovedText(deps.hostName));
15682
17454
  }
15683
17455
  await savePcSettings(deps.settingsPath, next);
15684
17456
  const said = value === "on" ? "Terminals from AiNecto on the web are allowed on this PC." : "Terminals from AiNecto on the web are blocked on this PC.";
15685
17457
  const running = deps.termProblem === void 0 ? runningPcs(await listed2(deps)) : [];
17458
+ const key = accountKey(deps.endpoint, userId);
15686
17459
  if (running.length === 0) {
15687
- return print2(deps, { remoteTerminal: value === "on" }, said);
17460
+ return await withRegistration(deps, key, userId, print2(deps, { remoteTerminal: value === "on" }, said));
15688
17461
  }
15689
17462
  if (!deps.json) deps.io.stdout.write(`${said}
15690
17463
  `);
@@ -15692,7 +17465,47 @@ async function executeRemoteSetting(deps, argv) {
15692
17465
  for (const pc of running) {
15693
17466
  await stopPc(deps, pc);
15694
17467
  }
15695
- return await launchPc(deps);
17468
+ return await withRegistration(deps, key, userId, await launchPc(deps));
17469
+ }
17470
+ async function runningPcGroups(deps) {
17471
+ assertQueryable(deps);
17472
+ const groups = [];
17473
+ for (const session of (await listedToTurnOff(deps)).filter((item) => runningPcs([item]).length > 0)) {
17474
+ const pgid = await processGroupOf(session.pid);
17475
+ if (pgid === void 0) {
17476
+ throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not read the process group of the PC connection (session ${session.name}, pid ${session.pid}), so its end cannot be confirmed.${processGroupUnavailableHint()}`);
17477
+ }
17478
+ groups.push({ session: session.name, pid: session.pid, pgid });
17479
+ }
17480
+ return groups;
17481
+ }
17482
+ async function turnOffPcs(deps, groups) {
17483
+ assertQueryable(deps);
17484
+ for (const group of groups) {
17485
+ const session = (await listedToTurnOff(deps)).find((item) => item.name === group.session && item.pid === group.pid);
17486
+ const [pc] = session ? runningPcs([session]) : [];
17487
+ if (pc) await stopPc(deps, pc);
17488
+ await confirmEnded(deps, group);
17489
+ }
17490
+ }
17491
+ function assertQueryable(deps) {
17492
+ if (deps.termProblem !== void 0) {
17493
+ throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not check the PC connection (ainecto term: ${deps.termProblem}).`);
17494
+ }
17495
+ }
17496
+ var STOP_CONFIRM_POLL_MS = 100;
17497
+ async function confirmEnded(deps, group) {
17498
+ const deadline = Date.now() + deps.stopDeadlineMs;
17499
+ for (; ; ) {
17500
+ const stillListed = (await listedToTurnOff(deps)).some((session) => session.name === group.session && session.pid === group.pid);
17501
+ const alive = processGroupAlive(group.pgid);
17502
+ if (!stillListed && !alive) return;
17503
+ if (Date.now() >= deadline) {
17504
+ const what = stillListed ? "the session is still running" : `a process in its group ${group.pgid} is still alive`;
17505
+ throw new CliCommandError("PC_STOP_UNCONFIRMED", `Could not confirm that the PC connection (session ${group.session}, pid ${group.pid}) ended within ${deps.stopDeadlineMs / 1e3} s (${what}). See ${deps.agentLog}.`);
17506
+ }
17507
+ await new Promise((resolve4) => setTimeout(resolve4, STOP_CONFIRM_POLL_MS));
17508
+ }
15696
17509
  }
15697
17510
  async function stopPc(deps, pc) {
15698
17511
  const client = await openTermClient(deps.paths, { start: false });
@@ -15754,10 +17567,13 @@ async function prepare(deps) {
15754
17567
  throw new CliCommandError("PC_PREPARE_FAILED", `\`${[command, ...args].join(" ")}\` failed${result.missing ? ` (${command} is not on PATH)` : ""}: ${lastLine(result.stderr) ?? lastLine(result.stdout) ?? `exit ${result.exitCode}`}`);
15755
17568
  }
15756
17569
  }
15757
- async function listed2(deps) {
15758
- const result = await termRequest(deps.paths, { op: "ls" }, { start: false });
17570
+ async function listed2(deps, connect2 = { start: false }) {
17571
+ const result = await termRequest(deps.paths, { op: "ls" }, connect2);
15759
17572
  return listedSessions(result.daemon ? result.data : void 0);
15760
17573
  }
17574
+ async function listedToTurnOff(deps) {
17575
+ return await listed2(deps, { start: false, resetFails: true });
17576
+ }
15761
17577
  function assertTerm(deps) {
15762
17578
  if (deps.termProblem !== void 0) {
15763
17579
  throw new CliCommandError("PC_UNSUPPORTED", `Connecting this PC needs ainecto term: ${deps.termProblem}`);
@@ -15776,10 +17592,115 @@ function print2(deps, data, human) {
15776
17592
  return 0;
15777
17593
  }
15778
17594
 
17595
+ // src/core/pc/pcNotify.ts
17596
+ var NOTIFY_BATCH_MS = 6e4;
17597
+ var WHAT = {
17598
+ paired: "was registered with this PC",
17599
+ session: "opened a terminal connection to this PC",
17600
+ shell: "started a new shell on this PC",
17601
+ command: "started a command in a new terminal on this PC"
17602
+ };
17603
+ function notificationText(event, more) {
17604
+ const time = `${String(event.at.getHours()).padStart(2, "0")}:${String(event.at.getMinutes()).padStart(2, "0")}`;
17605
+ return {
17606
+ title: "AiNecto",
17607
+ body: `${event.browserName} ${WHAT[event.kind]} \u2014 ${time}${more > 0 ? ` (+${more} more)` : ""}. Not you? Run \`ainecto remote off\`.`
17608
+ };
17609
+ }
17610
+ var systemClock = {
17611
+ now: () => Date.now(),
17612
+ setTimer: (run, ms) => {
17613
+ const timer = setTimeout(run, ms);
17614
+ timer.unref?.();
17615
+ return timer;
17616
+ },
17617
+ clearTimer: (timer) => clearTimeout(timer)
17618
+ };
17619
+ var NotifyBatcher = class {
17620
+ constructor(show, clock = systemClock) {
17621
+ this.show = show;
17622
+ this.clock = clock;
17623
+ }
17624
+ show;
17625
+ clock;
17626
+ slots = /* @__PURE__ */ new Map();
17627
+ add(event) {
17628
+ const key = `${event.keyId}\0${event.kind}`;
17629
+ const now = this.clock.now();
17630
+ const slot = this.slots.get(key);
17631
+ if (!slot || now >= slot.endsAt) {
17632
+ this.show(event, 0);
17633
+ this.slots.set(key, { endsAt: now + NOTIFY_BATCH_MS, pending: void 0, timer: void 0 });
17634
+ return;
17635
+ }
17636
+ slot.pending = { event, count: (slot.pending?.count ?? 0) + 1 };
17637
+ slot.timer ??= this.clock.setTimer(() => this.close(key), slot.endsAt - now);
17638
+ }
17639
+ flush() {
17640
+ for (const [key, slot] of this.slots) {
17641
+ if (slot.timer !== void 0) this.clock.clearTimer(slot.timer);
17642
+ if (slot.pending) this.show(slot.pending.event, slot.pending.count - 1);
17643
+ this.slots.delete(key);
17644
+ }
17645
+ }
17646
+ close(key) {
17647
+ const slot = this.slots.get(key);
17648
+ if (!slot) return;
17649
+ slot.timer = void 0;
17650
+ if (!slot.pending) return;
17651
+ const { event, count } = slot.pending;
17652
+ slot.pending = void 0;
17653
+ slot.endsAt = this.clock.now() + NOTIFY_BATCH_MS;
17654
+ this.show(event, count - 1);
17655
+ }
17656
+ };
17657
+ function notifyFailureReason(error) {
17658
+ if (error && typeof error === "object") {
17659
+ const value = error;
17660
+ if (value.code === "ENOENT") return "not-found";
17661
+ if (value.code === "EACCES") return "no-permission";
17662
+ if (typeof value.signal === "string" && value.signal !== "") return "signal";
17663
+ if (typeof value.code === "number") return `exit-${value.code}`;
17664
+ }
17665
+ return "failed";
17666
+ }
17667
+ function createPcNotifier(input) {
17668
+ const tool = notifyTool(input.platform);
17669
+ const run = input.run ?? runQuiet;
17670
+ const clock = input.clock ?? systemClock;
17671
+ let last = Promise.resolve();
17672
+ const show = (event, more) => {
17673
+ input.log.write({ event: "pc_notify", kind: event.kind, browserKeyId: event.keyId, more, tool: tool?.name ?? "none" });
17674
+ if (!tool) {
17675
+ input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: "none", reason: "no-tool-on-this-os" });
17676
+ last = Promise.resolve();
17677
+ return;
17678
+ }
17679
+ const { title, body } = notificationText(event, more);
17680
+ last = run(tool.file, tool.args(title, body)).then(
17681
+ () => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: true, tool: tool.name }),
17682
+ (error) => input.log.write({ event: "pc_notify_result", kind: event.kind, ok: false, tool: tool.name, reason: notifyFailureReason(error) })
17683
+ );
17684
+ };
17685
+ const batcher = new NotifyBatcher(show, clock);
17686
+ return {
17687
+ async notify(event) {
17688
+ const before = last;
17689
+ batcher.add({ ...event, at: new Date(clock.now()) });
17690
+ if (last !== before) await last;
17691
+ },
17692
+ async flush() {
17693
+ const before = last;
17694
+ batcher.flush();
17695
+ if (last !== before) await last;
17696
+ }
17697
+ };
17698
+ }
17699
+
15779
17700
  // src/adapters/cli/pcSwap.ts
15780
- import { randomUUID as randomUUID5 } from "crypto";
17701
+ import { randomUUID as randomUUID8 } from "crypto";
15781
17702
  import { writeFile as writeFile7 } from "fs/promises";
15782
- import { join as join8 } from "path";
17703
+ import { join as join9 } from "path";
15783
17704
  var Refused = class extends Error {
15784
17705
  constructor(reason, detail) {
15785
17706
  super(detail);
@@ -15853,7 +17774,7 @@ async function checkRuns(deps) {
15853
17774
  async function checkProvenance(deps) {
15854
17775
  const dir = await deps.makeTempDir();
15855
17776
  try {
15856
- await writeFile7(join8(dir, "package.json"), `${JSON.stringify({ name: "ainecto-upgrade-check", private: true })}
17777
+ await writeFile7(join9(dir, "package.json"), `${JSON.stringify({ name: "ainecto-upgrade-check", private: true })}
15857
17778
  `);
15858
17779
  const run = deps.runner(dir);
15859
17780
  const spec = `${deps.packageName}@${deps.to}`;
@@ -15879,7 +17800,7 @@ async function workflowOf(deps, run, version) {
15879
17800
  const view = await call(deps, "verify", run, "npm", ["view", `${deps.packageName}@${version}`, "dist.attestations.url"]);
15880
17801
  const url = view.exitCode === 0 ? view.stdout.trim() : "";
15881
17802
  if (url === "") return void 0;
15882
- const callId = randomUUID5();
17803
+ const callId = randomUUID8();
15883
17804
  const started = Date.now();
15884
17805
  deps.log.write({ event: "upgrade_call", callId, step: "verify", command: `GET ${url}` });
15885
17806
  let ok = false;
@@ -15897,7 +17818,7 @@ async function workflowOf(deps, run, version) {
15897
17818
  }
15898
17819
  }
15899
17820
  async function call(deps, step, run, command, args) {
15900
- const callId = randomUUID5();
17821
+ const callId = randomUUID8();
15901
17822
  const started = Date.now();
15902
17823
  deps.log.write({ event: "upgrade_call", callId, step, command: [command, ...args].join(" ") });
15903
17824
  let result = { exitCode: null, stdout: "", stderr: "no result", missing: false };
@@ -15973,24 +17894,24 @@ function swapArgsOf(argv) {
15973
17894
 
15974
17895
  // src/adapters/cli/ainectoCli.ts
15975
17896
  import { mkdtemp, rm as rm3 } from "fs/promises";
15976
- import { join as join10 } from "path";
17897
+ import { join as join11 } from "path";
15977
17898
 
15978
17899
  // src/adapters/cli/pcStatus.ts
15979
- import { readFile as readFile12 } from "fs/promises";
17900
+ import { readFile as readFile14 } from "fs/promises";
15980
17901
  import { hostname } from "os";
15981
17902
 
15982
17903
  // 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");
17904
+ import { homedir as homedir5 } from "os";
17905
+ import { join as join10 } from "path";
17906
+ function agentPaths(home = homedir5()) {
17907
+ const dir = join10(home, ".ainecto", "agent");
15987
17908
  return {
15988
17909
  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")
17910
+ work: join10(dir, "work"),
17911
+ sessions: join10(dir, "sessions.json"),
17912
+ runs: join10(dir, "runs.json"),
17913
+ log: join10(dir, "agent.log"),
17914
+ previousLog: join10(dir, "agent.log.1")
15994
17915
  };
15995
17916
  }
15996
17917
 
@@ -16001,7 +17922,7 @@ async function pcStatus(status, endpoint) {
16001
17922
  const userId = status.account?.userId;
16002
17923
  const settings = await loadPcSettings(pcSettingsPath(), hostname());
16003
17924
  const agentLog = agentPaths().log;
16004
- const logText = await readFile12(agentLog, "utf8").catch((error) => {
17925
+ const logText = await readFile14(agentLog, "utf8").catch((error) => {
16005
17926
  if (isNodeError(error, "ENOENT")) return "";
16006
17927
  throw error;
16007
17928
  });
@@ -16021,19 +17942,6 @@ async function pcStatus(status, endpoint) {
16021
17942
  // src/adapters/cli/agentCommand.ts
16022
17943
  import { hostname as hostname3 } from "os";
16023
17944
 
16024
- // src/core/async/stopSignals.ts
16025
- var STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
16026
- function onStopSignals(handler) {
16027
- for (const signal of STOP_SIGNALS) {
16028
- process.on(signal, handler);
16029
- }
16030
- return () => {
16031
- for (const signal of STOP_SIGNALS) {
16032
- process.off(signal, handler);
16033
- }
16034
- };
16035
- }
16036
-
16037
17945
  // src/core/agent/child.ts
16038
17946
  import { createInterface as createInterface3 } from "readline";
16039
17947
  var spawnAgent = (command, args, options) => spawnPiped([command, ...args], options);
@@ -16537,10 +18445,10 @@ function codexServerRequestAnswer(method) {
16537
18445
  }
16538
18446
  }
16539
18447
  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 };
18448
+ const account2 = result.account && typeof result.account === "object" ? result.account : void 0;
18449
+ const method = typeof account2?.type === "string" ? account2.type : void 0;
18450
+ const plan = typeof account2?.planType === "string" ? account2.planType : void 0;
18451
+ if (account2) return { ready: true, mode: method === "apiKey" ? "apiKey" : "subscription", method, plan };
16544
18452
  if (result.requiresOpenaiAuth === false) return { ready: true, method: "none-required" };
16545
18453
  return { ready: false, detail: "not signed in with an API key or ChatGPT (run `codex login`, or `codex login --with-api-key`)" };
16546
18454
  }
@@ -16862,7 +18770,7 @@ function toError(error) {
16862
18770
  }
16863
18771
 
16864
18772
  // src/core/agent/runs.ts
16865
- import { readFile as readFile13, rename as rename7, writeFile as writeFile8 } from "fs/promises";
18773
+ import { readFile as readFile15, rename as rename7, writeFile as writeFile8 } from "fs/promises";
16866
18774
  var AgentRunLog = class {
16867
18775
  constructor(path, log) {
16868
18776
  this.path = path;
@@ -16876,7 +18784,7 @@ var AgentRunLog = class {
16876
18784
  let reason;
16877
18785
  const runs = /* @__PURE__ */ new Map();
16878
18786
  try {
16879
- const parsed = JSON.parse(await readFile13(this.path, "utf8"));
18787
+ const parsed = JSON.parse(await readFile15(this.path, "utf8"));
16880
18788
  for (const value of Array.isArray(parsed.runs) ? parsed.runs : []) {
16881
18789
  const e = value ?? {};
16882
18790
  if (typeof e.cardUuid === "string" && typeof e.startedAt === "string") {
@@ -16921,7 +18829,7 @@ var AgentRunLog = class {
16921
18829
  };
16922
18830
 
16923
18831
  // src/core/agent/readiness.ts
16924
- import { randomUUID as randomUUID6 } from "crypto";
18832
+ import { randomUUID as randomUUID9 } from "crypto";
16925
18833
  async function checkAgents(adapters, log) {
16926
18834
  return await Promise.all(adapters.map(async (adapter) => {
16927
18835
  const detected = await probe(
@@ -16955,7 +18863,7 @@ function openAgents(checks) {
16955
18863
  return checks.filter((check) => check.installed).map((check) => ({ id: check.id, ready: check.ready, ...check.auth ? { auth: check.auth } : {} }));
16956
18864
  }
16957
18865
  async function probe(log, agent, kind, work, summary2) {
16958
- const callId = randomUUID6();
18866
+ const callId = randomUUID9();
16959
18867
  const started = Date.now();
16960
18868
  log.write({ event: "agent_probe", callId, agent, probe: kind });
16961
18869
  try {
@@ -16977,7 +18885,7 @@ async function probe(log, agent, kind, work, summary2) {
16977
18885
  }
16978
18886
 
16979
18887
  // src/core/agent/sessions.ts
16980
- import { readFile as readFile14, rename as rename8, writeFile as writeFile9 } from "fs/promises";
18888
+ import { readFile as readFile16, rename as rename8, writeFile as writeFile9 } from "fs/promises";
16981
18889
  var AgentSessionMap = class {
16982
18890
  constructor(path) {
16983
18891
  this.path = path;
@@ -16986,7 +18894,7 @@ var AgentSessionMap = class {
16986
18894
  map = emptyMap();
16987
18895
  async load() {
16988
18896
  try {
16989
- const parsed = JSON.parse(await readFile14(this.path, "utf8"));
18897
+ const parsed = JSON.parse(await readFile16(this.path, "utf8"));
16990
18898
  const map = emptyMap();
16991
18899
  map[DEFAULT_AGENT] = entries(parsed.conversations);
16992
18900
  const byAgent = parsed.byAgent && typeof parsed.byAgent === "object" ? parsed.byAgent : {};
@@ -17085,6 +18993,7 @@ async function pcRemoteSetup(input) {
17085
18993
  pcId: settings.pcId,
17086
18994
  hostName,
17087
18995
  remoteEnabled: userId !== void 0 && settings.accounts[accountKey(input.endpoint, userId)]?.remoteTerminal === true,
18996
+ trust: userId !== void 0 ? { keysPath: input.keysPath ?? pcKeysPath(), accountKey: accountKey(input.endpoint, userId), userId } : void 0,
17088
18997
  appHome: input.appHome ?? appHome(),
17089
18998
  env: input.env ?? stringEnv()
17090
18999
  };
@@ -17110,6 +19019,8 @@ async function runPcRemote(setup, signal, onAnswer) {
17110
19019
  hostName: setup.hostName,
17111
19020
  cliVersion: CLI_VERSION_LABEL,
17112
19021
  remoteEnabled: setup.remoteEnabled,
19022
+ trust: setup.trust,
19023
+ notifier: createPcNotifier({ log }),
17113
19024
  exclude: [PC_SESSION_NAME],
17114
19025
  sessionEnv: setup.env,
17115
19026
  appHome: setup.appHome,
@@ -17137,8 +19048,9 @@ async function runPcRemote(setup, signal, onAnswer) {
17137
19048
  var AGENT_HELP_LINES = [
17138
19049
  " ainecto in a terminal, with no arguments: check sign-in, ask once, then connect this PC in the background (same as ainecto start)",
17139
19050
  " ainecto start [--env prod|dev] connect this PC in the background \u2014 keeps running after you close the window (log: ~/.ainecto/agent/agent.log)",
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"
19051
+ " ainecto stop [--forget] disconnect this PC now (--forget also removes your approval and registered browsers on this PC)",
19052
+ " ainecto remote on|off allow or block terminals from AiNecto on the web on this PC",
19053
+ " ainecto pair [--list | --remove <keyId|name>] register a web browser with this PC by typing codes shown on both (once per browser)"
17142
19054
  ];
17143
19055
  function isPcRunCommand(domain, action) {
17144
19056
  return domain === "pc" && action === "run";
@@ -17247,7 +19159,7 @@ async function executeAgentServe(input) {
17247
19159
  }
17248
19160
 
17249
19161
  // src/adapters/cli/ainectoCli.ts
17250
- import { homedir as homedir5, hostname as hostname4, tmpdir } from "os";
19162
+ import { homedir as homedir6, hostname as hostname4, tmpdir } from "os";
17251
19163
  async function runAinectoCli(argv, io) {
17252
19164
  let parsed = { json: argv.includes("--json"), help: false, version: false, positionals: [] };
17253
19165
  try {
@@ -17336,8 +19248,8 @@ async function runAinectoCli(argv, io) {
17336
19248
  auth,
17337
19249
  client: client2,
17338
19250
  // ★외부 CLI 는 홈 폴더에서 돈다 — 지금 저장소의 local·project 범위 항목이 사용자 범위 판정에 끼지 않게.
17339
- runner: systemCommandRunner({ cwd: homedir5() }),
17340
- home: homedir5(),
19251
+ runner: systemCommandRunner({ cwd: homedir6() }),
19252
+ home: homedir6(),
17341
19253
  json: parsed.json,
17342
19254
  io
17343
19255
  });
@@ -17351,19 +19263,31 @@ async function runAinectoCli(argv, io) {
17351
19263
  tokenStore,
17352
19264
  auth,
17353
19265
  client: client2,
17354
- runner: systemCommandRunner({ cwd: homedir5() }),
19266
+ runner: systemCommandRunner({ cwd: homedir6() }),
17355
19267
  hereRunner: systemCommandRunner({ cwd: process.cwd() }),
17356
- home: homedir5(),
19268
+ home: homedir6(),
17357
19269
  cwd: process.cwd(),
17358
19270
  envVars: process.env
17359
19271
  };
17360
19272
  };
19273
+ const insideTermSession = process.env[SESSION_ENV] !== void 0;
19274
+ const pairTransport = async (pcId) => {
19275
+ const paths = termPaths();
19276
+ await ensurePrivateDir(paths.dir);
19277
+ return createPairRelay({ endpoint: resolved.endpoint, tokenProvider: connect2().auth, log: openRemoteLog(paths), pcId, holdMs: PAIR_WAIT_MS });
19278
+ };
19279
+ const notifyPaired = async (browser) => {
19280
+ const paths = termPaths();
19281
+ await ensurePrivateDir(paths.dir);
19282
+ await createPcNotifier({ log: openRemoteLog(paths) }).notify({ kind: "paired", keyId: browser.keyId, browserName: browser.name });
19283
+ };
17361
19284
  const pcDeps = () => ({
17362
19285
  io,
17363
19286
  json: parsed.json,
17364
19287
  interactive,
17365
19288
  paths: termPaths(),
17366
19289
  settingsPath: pcSettingsPath(),
19290
+ keysPath: pcKeysPath(),
17367
19291
  hostName: hostname4(),
17368
19292
  endpoint: resolved.endpoint,
17369
19293
  cwd: process.cwd(),
@@ -17378,7 +19302,21 @@ async function runAinectoCli(argv, io) {
17378
19302
  readyDeadlineMs: pcReadyDeadlineMs(),
17379
19303
  machine: () => collectStatus(collectInput()),
17380
19304
  account: () => readAccount(connect2().client),
17381
- setup: () => runSetup([])
19305
+ setup: () => runSetup([]),
19306
+ register: {
19307
+ insideTermSession,
19308
+ overSsh: process.env.SSH_CONNECTION !== void 0 || process.env.SSH_TTY !== void 0,
19309
+ openBrowser: (url) => launchBrowser(url),
19310
+ transport: pairTransport,
19311
+ notifyPaired,
19312
+ waitMs: PAIR_WAIT_MS,
19313
+ interrupt: () => {
19314
+ const controller = new AbortController();
19315
+ const off = onStopSignals(() => controller.abort());
19316
+ return { signal: controller.signal, dispose: off };
19317
+ },
19318
+ now: () => /* @__PURE__ */ new Date()
19319
+ }
17382
19320
  });
17383
19321
  if (domain === void 0 || domain === "start") {
17384
19322
  if (rest.length > 0 || domain === "start" && action !== void 0) {
@@ -17392,6 +19330,28 @@ async function runAinectoCli(argv, io) {
17392
19330
  if (domain === "remote") {
17393
19331
  return await executeRemoteSetting(pcDeps(), parsed.positionals.slice(1));
17394
19332
  }
19333
+ if (domain === "pair") {
19334
+ return await executePair({
19335
+ io,
19336
+ json: parsed.json,
19337
+ interactive,
19338
+ insideTermSession,
19339
+ openTty: openDevTty,
19340
+ settingsPath: pcSettingsPath(),
19341
+ keysPath: pcKeysPath(),
19342
+ hostName: hostname4(),
19343
+ endpoint: resolved.endpoint,
19344
+ account: () => readAccount(connect2().client),
19345
+ transport: pairTransport,
19346
+ notifyPaired,
19347
+ findPcs: () => runningPcGroups(pcDeps()),
19348
+ turnOffPcs: (groups) => turnOffPcs(pcDeps(), groups),
19349
+ // 연결 승인 전 대화형 — `ainecto`(인자 없음)와 같은 흐름 그대로(KAN-1348). 자동 등록은 빼고 이어서 코드로 등록한다.
19350
+ connectPc: () => executePcStart({ ...pcDeps(), register: void 0 }),
19351
+ waitMs: PAIR_WAIT_MS,
19352
+ now: () => /* @__PURE__ */ new Date()
19353
+ }, parsed.positionals.slice(1));
19354
+ }
17395
19355
  if (domain === "init") {
17396
19356
  return await runInit(parsed.positionals.slice(1));
17397
19357
  }
@@ -17441,9 +19401,9 @@ async function runAinectoCli(argv, io) {
17441
19401
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
17442
19402
  return await response.json();
17443
19403
  },
17444
- makeTempDir: () => mkdtemp(join10(tmpdir(), "ainecto-upgrade-")),
19404
+ makeTempDir: () => mkdtemp(join11(tmpdir(), "ainecto-upgrade-")),
17445
19405
  removeDir: (path) => rm3(path, { recursive: true, force: true }),
17446
- home: homedir5(),
19406
+ home: homedir6(),
17447
19407
  log: openAgentLog(swapPaths)
17448
19408
  });
17449
19409
  }