@ainecto/cli 0.14.0-next.6 → 0.14.0-next.7

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.
@@ -5585,8 +5585,8 @@ function assertLoopbackRedirectUrl(value) {
5585
5585
  }
5586
5586
  throw new Error("OAuth redirect URI must be an http localhost loopback URL.");
5587
5587
  }
5588
- function isLoopbackHostname(hostname2) {
5589
- return hostname2 === "localhost" || hostname2 === "127.0.0.1" || hostname2 === "::1" || hostname2 === "[::1]";
5588
+ function isLoopbackHostname(hostname3) {
5589
+ return hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "::1" || hostname3 === "[::1]";
5590
5590
  }
5591
5591
  function assertEnv(value) {
5592
5592
  if (value === void 0) {
@@ -5678,7 +5678,16 @@ function legacyRoleInput(flag, envVars = process.env) {
5678
5678
 
5679
5679
  // src/core/version.ts
5680
5680
  var UNBUNDLED_VERSION = "dev";
5681
- var CLI_VERSION = true ? "0.14.0-next.6" : UNBUNDLED_VERSION;
5681
+ var CLI_VERSION = true ? "0.14.0-next.7" : UNBUNDLED_VERSION;
5682
+ var CLI_BUILD = true ? "f1e73b8" : void 0;
5683
+ function cliVersionLabel(version, build, release) {
5684
+ return release || build === void 0 ? version : `${version}-dev+${build}`;
5685
+ }
5686
+ var CLI_VERSION_LABEL = cliVersionLabel(
5687
+ CLI_VERSION,
5688
+ CLI_BUILD,
5689
+ true
5690
+ );
5682
5691
  var PACKAGE_NAME = "@ainecto/mcp";
5683
5692
  var CLI_USER_AGENT = `${PACKAGE_NAME} ${CLI_VERSION}`;
5684
5693
  function bridgePackageSpec(version = CLI_VERSION) {
@@ -10472,6 +10481,7 @@ function assertNoArgs(command, argv) {
10472
10481
 
10473
10482
  // src/adapters/cli/termCommand.ts
10474
10483
  import { closeSync as closeSync2, writeSync } from "fs";
10484
+ import { hostname } from "os";
10475
10485
  import { resolve as resolve3 } from "path";
10476
10486
 
10477
10487
  // src/core/term/client.ts
@@ -10493,6 +10503,9 @@ var TermError = class extends Error {
10493
10503
  }
10494
10504
  code;
10495
10505
  };
10506
+ function noSession(name) {
10507
+ return new TermError("TERM_NO_SESSION", `No session named "${name}" (no term sessions are running).`);
10508
+ }
10496
10509
 
10497
10510
  // src/core/term/daemonLock.ts
10498
10511
  var LINUX_ABSTRACT_SOCKET_NODE = [20, 8, 0];
@@ -10674,6 +10687,25 @@ function parseDaemonMessage(line) {
10674
10687
  const error = asRecord(record2.error);
10675
10688
  return { id, ok: false, error: { code: stringField(error, "code"), message: stringField(error, "message") } };
10676
10689
  }
10690
+ function listedSessions(data) {
10691
+ if (data && typeof data === "object" && "sessions" in data && Array.isArray(data.sessions)) {
10692
+ return data.sessions.filter(isListedSession);
10693
+ }
10694
+ return [];
10695
+ }
10696
+ function isListedSession(value) {
10697
+ if (!value || typeof value !== "object") {
10698
+ return false;
10699
+ }
10700
+ const session = value;
10701
+ return typeof session.name === "string" && typeof session.pid === "number" && typeof session.cwd === "string" && typeof session.cols === "number" && typeof session.rows === "number";
10702
+ }
10703
+ function readLines(data) {
10704
+ if (data && typeof data === "object" && "lines" in data && Array.isArray(data.lines)) {
10705
+ return data.lines.filter((line) => typeof line === "string");
10706
+ }
10707
+ throw new TermError("TERM_BAD_RESPONSE", "The term daemon answered read without lines.");
10708
+ }
10677
10709
  function asRecord(value) {
10678
10710
  if (!value || typeof value !== "object" || Array.isArray(value)) {
10679
10711
  throw new TermProtocolError("Expected a JSON object.");
@@ -12149,7 +12181,9 @@ function termPaths(home = homedir2()) {
12149
12181
  daemonInfo: join6(dir, "daemon.json"),
12150
12182
  manifest: join6(dir, "sessions.json"),
12151
12183
  log: join6(dir, "daemon.log"),
12152
- previousLog: join6(dir, "daemon.log.1")
12184
+ previousLog: join6(dir, "daemon.log.1"),
12185
+ remoteLog: join6(dir, "remote.log"),
12186
+ previousRemoteLog: join6(dir, "remote.log.1")
12153
12187
  };
12154
12188
  }
12155
12189
 
@@ -12157,7 +12191,7 @@ function termPaths(home = homedir2()) {
12157
12191
  async function waitForMatch(paths, name, pattern, range, timeoutMs) {
12158
12192
  const client = await openTermClient(paths, { start: false });
12159
12193
  if (!client) {
12160
- throw new TermError("TERM_NO_SESSION", `No session named "${name}" (no term sessions are running).`);
12194
+ throw noSession(name);
12161
12195
  }
12162
12196
  let dirty = false;
12163
12197
  let ended;
@@ -12194,7 +12228,7 @@ async function waitForMatch(paths, name, pattern, range, timeoutMs) {
12194
12228
  }
12195
12229
  throw error;
12196
12230
  }
12197
- const lines = linesOf(data);
12231
+ const lines = readLines(data);
12198
12232
  for (const line of lines) {
12199
12233
  const found = pattern.exec(line);
12200
12234
  if (found) {
@@ -12221,11 +12255,363 @@ async function waitForMatch(paths, name, pattern, range, timeoutMs) {
12221
12255
  client.close();
12222
12256
  }
12223
12257
  }
12224
- function linesOf(data) {
12225
- if (data && typeof data === "object" && "lines" in data && Array.isArray(data.lines)) {
12226
- return data.lines.filter((line) => typeof line === "string");
12258
+
12259
+ // src/core/term/remote.ts
12260
+ import { StringDecoder } from "string_decoder";
12261
+
12262
+ // src/core/async/sleep.ts
12263
+ function sleep(ms, signal) {
12264
+ return new Promise((resolve4) => {
12265
+ if (signal.aborted) {
12266
+ resolve4();
12267
+ return;
12268
+ }
12269
+ const timer = setTimeout(done, ms);
12270
+ signal.addEventListener("abort", done, { once: true });
12271
+ function done() {
12272
+ clearTimeout(timer);
12273
+ signal.removeEventListener("abort", done);
12274
+ resolve4();
12275
+ }
12276
+ });
12277
+ }
12278
+
12279
+ // src/core/http/pcHttp.ts
12280
+ import { randomUUID as randomUUID2 } from "crypto";
12281
+ var PcCallError = class extends Error {
12282
+ constructor(message, op, status, code) {
12283
+ super(message);
12284
+ this.op = op;
12285
+ this.status = status;
12286
+ this.code = code;
12287
+ this.name = "PcCallError";
12227
12288
  }
12228
- throw new TermError("TERM_BAD_RESPONSE", "The term daemon answered read without lines.");
12289
+ op;
12290
+ status;
12291
+ code;
12292
+ /** 다시 해 볼 만한가 — 네트워크·기한·5xx·429. */
12293
+ get retryable() {
12294
+ return this.status === void 0 || this.status >= 500 || this.status === 429;
12295
+ }
12296
+ };
12297
+ function createPcHttp(input) {
12298
+ const fetchImpl = input.fetchImpl ?? fetch;
12299
+ const base = `${input.endpoint.replace(/\/+$/, "")}/${input.path}/`;
12300
+ const fail = input.error ?? ((message, op, status, code) => new PcCallError(message, op, status, code));
12301
+ const { log } = input.logging;
12302
+ let sessionToken;
12303
+ async function send(op, payload, token, options = {}) {
12304
+ const controller = new AbortController();
12305
+ const timer = setTimeout(
12306
+ () => controller.abort(new DOMException("timed out", "TimeoutError")),
12307
+ (options.holdMs ?? 0) + input.timeoutMs
12308
+ );
12309
+ const onStop = () => controller.abort(new DOMException("stopped", "AbortError"));
12310
+ options.signal?.addEventListener("abort", onStop, { once: true });
12311
+ const headers = { "Content-Type": "application/json", Accept: "application/json" };
12312
+ if (token) headers.Authorization = `Bearer ${token}`;
12313
+ if (sessionToken && op !== "open") headers[input.sessionHeader] = sessionToken;
12314
+ try {
12315
+ const response = await fetchImpl(base + op, { method: "POST", headers, body: payload, signal: controller.signal });
12316
+ await response.clone().arrayBuffer();
12317
+ return response;
12318
+ } catch (error) {
12319
+ throw controller.signal.aborted && controller.signal.reason instanceof Error ? controller.signal.reason : error;
12320
+ } finally {
12321
+ clearTimeout(timer);
12322
+ options.signal?.removeEventListener("abort", onStop);
12323
+ }
12324
+ }
12325
+ return {
12326
+ useSessionToken(token) {
12327
+ sessionToken = token;
12328
+ },
12329
+ async call(op, body, options) {
12330
+ const callId = randomUUID2();
12331
+ const payload = JSON.stringify(body);
12332
+ const started = Date.now();
12333
+ log.write(input.logging.request({ callId, op, bytes: Buffer.byteLength(payload, "utf8") }, options));
12334
+ let outcome = { ok: false, error: "no response" };
12335
+ try {
12336
+ let response = await send(op, payload, await input.tokenProvider.getAccessToken(), options);
12337
+ if (response.status === 401) {
12338
+ response = await send(op, payload, await input.tokenProvider.refreshAfterUnauthorized(), options);
12339
+ }
12340
+ const text = await response.text();
12341
+ const parsed = parseJson2(text);
12342
+ if (!response.ok) {
12343
+ const code = typeof parsed?.code === "string" ? parsed.code : void 0;
12344
+ outcome = { ok: false, status: response.status, code };
12345
+ throw fail(typeof parsed?.detail === "string" ? parsed.detail : `HTTP ${response.status}`, op, response.status, code);
12346
+ }
12347
+ outcome = { ok: true, status: response.status, body: parsed ?? {} };
12348
+ return parsed ?? {};
12349
+ } catch (error) {
12350
+ if (error instanceof PcCallError) throw error;
12351
+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
12352
+ const reason = timedOut ? error.name : error instanceof Error ? error.message : String(error);
12353
+ outcome = { ok: false, error: reason };
12354
+ throw fail(timedOut ? `${op} timed out` : `${op} failed: ${reason}`, op);
12355
+ } finally {
12356
+ log.write(input.logging.response({ callId, op, ms: Date.now() - started }, outcome));
12357
+ }
12358
+ }
12359
+ };
12360
+ }
12361
+ function parseJson2(text) {
12362
+ if (!text) return void 0;
12363
+ try {
12364
+ const value = JSON.parse(text);
12365
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
12366
+ } catch {
12367
+ return void 0;
12368
+ }
12369
+ }
12370
+
12371
+ // src/core/term/remoteFrame.ts
12372
+ import { createHash as createHash6 } from "crypto";
12373
+ function screenFrame(lines, maxD) {
12374
+ const sizes = lines.map((line) => Buffer.byteLength(line, "utf8"));
12375
+ let start = 0;
12376
+ let bytes = sizes.reduce((sum, size) => sum + size, 0) + Math.max(0, lines.length - 1) * 2;
12377
+ while (start < lines.length && base64Length(bytes) > maxD) {
12378
+ bytes -= (sizes[start] ?? 0) + (start < lines.length - 1 ? 2 : 0);
12379
+ start += 1;
12380
+ }
12381
+ const text = lines.slice(start).join("\r\n");
12382
+ return {
12383
+ d: Buffer.from(text, "utf8").toString("base64"),
12384
+ hash: createHash6("sha256").update(text, "utf8").digest("hex"),
12385
+ dropped: start
12386
+ };
12387
+ }
12388
+ function frameBudget(frameMaxBytes, body) {
12389
+ return frameMaxBytes - Buffer.byteLength(JSON.stringify({ ...body, d: "" }), "utf8");
12390
+ }
12391
+ function base64Length(bytes) {
12392
+ return 4 * Math.ceil(bytes / 3);
12393
+ }
12394
+
12395
+ // src/core/term/remoteLimits.ts
12396
+ var CALL_TIMEOUT_MS = 1e4;
12397
+ var FRAME_MIN_INTERVAL_MS = 150;
12398
+ var FRAME_SCROLLBACK_LINES = 200;
12399
+ var RETRY_MIN_MS = 500;
12400
+ var RETRY_MAX_MS = 1e4;
12401
+ function retryWait(attempt, random) {
12402
+ return Math.min(RETRY_MIN_MS * 2 ** attempt, RETRY_MAX_MS) + Math.floor(random * RETRY_MIN_MS);
12403
+ }
12404
+
12405
+ // src/core/term/remote.ts
12406
+ function openRemoteLog(paths) {
12407
+ const log = new DaemonLog(paths.remoteLog, paths.previousRemoteLog);
12408
+ log.enableRotation();
12409
+ return log;
12410
+ }
12411
+ function createRemoteHttp(input) {
12412
+ return createPcHttp({
12413
+ endpoint: input.endpoint,
12414
+ path: "term/pc",
12415
+ tokenProvider: input.tokenProvider,
12416
+ timeoutMs: CALL_TIMEOUT_MS,
12417
+ sessionHeader: "X-Remote-Token",
12418
+ fetchImpl: input.fetchImpl,
12419
+ logging: {
12420
+ log: input.log,
12421
+ request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
12422
+ response: ({ callId, op, ms }, outcome) => ({
12423
+ event: "remote_call_response",
12424
+ callId,
12425
+ op,
12426
+ ...outcome.ok ? { ok: true, status: outcome.status, ...answerSummary(outcome.body) } : outcome,
12427
+ ms
12428
+ })
12429
+ }
12430
+ });
12431
+ }
12432
+ async function runRemote(deps) {
12433
+ const name = deps.session;
12434
+ const client = await openTermClient(deps.paths, { start: false });
12435
+ if (!client) {
12436
+ throw noSession(name);
12437
+ }
12438
+ let ending;
12439
+ const stopper = new AbortController();
12440
+ let dirty = true;
12441
+ let wakeFrame;
12442
+ const nudge = () => {
12443
+ const wake = wakeFrame;
12444
+ wakeFrame = void 0;
12445
+ wake?.();
12446
+ };
12447
+ const end = (outcome) => {
12448
+ if (ending) return;
12449
+ ending = outcome;
12450
+ stopper.abort();
12451
+ nudge();
12452
+ };
12453
+ const daemonFailed = (op, error) => {
12454
+ const code = error instanceof TermError ? error.code : "UNKNOWN";
12455
+ const message = error instanceof Error ? error.message : String(error);
12456
+ deps.log.write({ event: "remote_daemon_error", op, code, message });
12457
+ end(code === "TERM_NO_SESSION" ? { exitCode: 0, reason: `Session ${name} ended.`, close: true } : { exitCode: 1, reason: `The term daemon failed ${op} (${code}): ${message}`, close: true });
12458
+ };
12459
+ const onUserStop = () => end({ exitCode: 0, reason: "Stopped.", close: true });
12460
+ if (deps.signal.aborted) onUserStop();
12461
+ deps.signal.addEventListener("abort", onUserStop, { once: true });
12462
+ client.onEvent((event) => {
12463
+ if (event.event === "changed") {
12464
+ dirty = true;
12465
+ nudge();
12466
+ } else if (event.event === "exit") {
12467
+ end({ exitCode: 0, reason: `Session ${name} exited (${event.signal ? `signal ${event.signal}` : `code ${event.exitCode}`}).`, close: true });
12468
+ }
12469
+ });
12470
+ client.onClose(() => end({ exitCode: 1, reason: "Lost the connection to the term daemon.", close: true }));
12471
+ let remoteId;
12472
+ try {
12473
+ await client.request({ op: "watch", name });
12474
+ const listed = listedSessions(await client.request({ op: "ls" })).find((session) => session.name === name);
12475
+ if (!listed) {
12476
+ throw noSession(name);
12477
+ }
12478
+ const { cols, rows } = listed;
12479
+ if (ending) {
12480
+ return { exitCode: ending.exitCode, reason: ending.reason };
12481
+ }
12482
+ const opened = await deps.http.call("open", { session: name, hostName: deps.hostName, cliVersion: deps.cliVersion, cols, rows });
12483
+ const limits = serverLimits(opened.limits);
12484
+ if (typeof opened.remoteId !== "string" || typeof opened.remoteToken !== "string" || !limits) {
12485
+ throw new TermError("TERM_REMOTE_BAD_RESPONSE", "AiNecto answered open without remoteId, remoteToken or limits.");
12486
+ }
12487
+ const id = opened.remoteId;
12488
+ remoteId = id;
12489
+ deps.http.useSessionToken(opened.remoteToken);
12490
+ deps.log.write({ event: "remote_opened", remoteId: id, cols, rows, ...limits });
12491
+ deps.print(`Sharing ${name} (${cols}x${rows}) on AiNecto from ${deps.hostName}. Open the remote terminal in AiNecto to watch and type. Press Ctrl+C to stop.`);
12492
+ const refused = (error) => {
12493
+ if (error instanceof PcCallError && error.status === 404) {
12494
+ return { exitCode: 0, reason: `AiNecto no longer has this remote terminal open (${error.code ?? "404"}).`, close: false };
12495
+ }
12496
+ const what = error instanceof PcCallError ? `${error.op}: ${error.status ?? "-"} ${error.code ?? ""} ${error.message}`.replace(/\s+/g, " ") : error instanceof Error ? error.message : String(error);
12497
+ return { exitCode: 1, reason: `AiNecto refused the remote terminal (${what}).`, close: true };
12498
+ };
12499
+ const decoder = new StringDecoder("utf8");
12500
+ const pollLoop = async () => {
12501
+ let attempt = 0;
12502
+ while (!ending) {
12503
+ let answer;
12504
+ try {
12505
+ answer = await deps.http.call("poll", { remoteId: id }, { holdMs: limits.pollHoldSeconds * 1e3, signal: stopper.signal });
12506
+ } catch (error) {
12507
+ if (ending) return;
12508
+ if (!(error instanceof PcCallError) || !error.retryable) {
12509
+ end(refused(error));
12510
+ return;
12511
+ }
12512
+ await sleep(retryWait(attempt, Math.random()), stopper.signal);
12513
+ attempt += 1;
12514
+ continue;
12515
+ }
12516
+ attempt = 0;
12517
+ if (answer.state === "CLOSED") {
12518
+ end({ exitCode: 0, reason: `AiNecto closed this remote terminal (${typeof answer.reason === "string" ? answer.reason : "CLOSED"}).`, close: false });
12519
+ return;
12520
+ }
12521
+ for (const d of inputsIn(answer)) {
12522
+ const text = decoder.write(Buffer.from(d, "base64"));
12523
+ if (text === "") continue;
12524
+ try {
12525
+ await client.request({ op: "send", name, text, paste: false });
12526
+ } catch (error) {
12527
+ daemonFailed("send", error);
12528
+ return;
12529
+ }
12530
+ }
12531
+ }
12532
+ };
12533
+ const frameLoop = async () => {
12534
+ const budget = frameBudget(limits.frameMaxBytes, { remoteId: id, cols, rows });
12535
+ let sentHash;
12536
+ let lastRead = 0;
12537
+ let dropped = 0;
12538
+ let attempt = 0;
12539
+ while (!ending) {
12540
+ if (!dirty) {
12541
+ await new Promise((resolve4) => {
12542
+ wakeFrame = resolve4;
12543
+ });
12544
+ continue;
12545
+ }
12546
+ const gap = lastRead + FRAME_MIN_INTERVAL_MS - Date.now();
12547
+ if (gap > 0) {
12548
+ await sleep(gap, stopper.signal);
12549
+ continue;
12550
+ }
12551
+ dirty = false;
12552
+ lastRead = Date.now();
12553
+ let lines;
12554
+ try {
12555
+ lines = readLines(await client.request({ op: "read", name, scrollback: true, lines: FRAME_SCROLLBACK_LINES + rows }));
12556
+ } catch (error) {
12557
+ daemonFailed("read", error);
12558
+ return;
12559
+ }
12560
+ const frame = screenFrame(lines, budget);
12561
+ if (frame.dropped !== dropped) {
12562
+ dropped = frame.dropped;
12563
+ deps.log.write({ event: "remote_frame_trimmed", dropped });
12564
+ }
12565
+ if (frame.hash === sentHash) continue;
12566
+ try {
12567
+ await deps.http.call("frame", { remoteId: id, cols, rows, d: frame.d }, { signal: stopper.signal });
12568
+ sentHash = frame.hash;
12569
+ attempt = 0;
12570
+ } catch (error) {
12571
+ if (ending) return;
12572
+ if (!(error instanceof PcCallError) || !error.retryable) {
12573
+ end(refused(error));
12574
+ return;
12575
+ }
12576
+ await sleep(retryWait(attempt, Math.random()), stopper.signal);
12577
+ attempt += 1;
12578
+ dirty = true;
12579
+ }
12580
+ }
12581
+ };
12582
+ await Promise.all([pollLoop(), frameLoop()]);
12583
+ const outcome = ending ?? { exitCode: 1, reason: "The remote terminal stopped.", close: true };
12584
+ if (outcome.close) {
12585
+ try {
12586
+ await deps.http.call("close", { remoteId: id });
12587
+ } catch (error) {
12588
+ deps.print(`Could not tell AiNecto that sharing stopped: ${error instanceof Error ? error.message : String(error)}`);
12589
+ }
12590
+ }
12591
+ return { exitCode: outcome.exitCode, reason: outcome.reason };
12592
+ } finally {
12593
+ if (!remoteId) stopper.abort();
12594
+ deps.signal.removeEventListener("abort", onUserStop);
12595
+ client.close();
12596
+ }
12597
+ }
12598
+ function answerSummary(body) {
12599
+ return {
12600
+ ...typeof body.state === "string" ? { state: body.state } : {},
12601
+ ...typeof body.reason === "string" ? { reason: body.reason } : {},
12602
+ ...Array.isArray(body.commands) ? { commands: body.commands.length } : {},
12603
+ ...typeof body.version === "number" ? { version: body.version } : {}
12604
+ };
12605
+ }
12606
+ function serverLimits(value) {
12607
+ if (!value || typeof value !== "object") return void 0;
12608
+ const pollHoldSeconds = "pollHoldSeconds" in value ? value.pollHoldSeconds : void 0;
12609
+ const frameMaxBytes = "frameMaxBytes" in value ? value.frameMaxBytes : void 0;
12610
+ return typeof pollHoldSeconds === "number" && pollHoldSeconds >= 0 && typeof frameMaxBytes === "number" && frameMaxBytes > 0 ? { pollHoldSeconds, frameMaxBytes } : void 0;
12611
+ }
12612
+ function inputsIn(answer) {
12613
+ if (!Array.isArray(answer.commands)) return [];
12614
+ return answer.commands.flatMap((command) => command && typeof command === "object" && "type" in command && command.type === "input" && "d" in command && typeof command.d === "string" ? [command.d] : []);
12229
12615
  }
12230
12616
 
12231
12617
  // src/adapters/cli/termCommand.ts
@@ -12238,7 +12624,8 @@ var TERM_HELP_LINES = [
12238
12624
  " ainecto term wait <name> --match REGEX [--timeout SECONDS] [--lines N] [--scrollback] until a screen line matches",
12239
12625
  ` ainecto term attach <name> watch and type in your terminal; detach with ${DETACH_HINT}`,
12240
12626
  " ainecto term kill <name> \xB7 ainecto term kill-server",
12241
- " ainecto term restore [--json] start again the sessions that were running when the daemon or the machine stopped"
12627
+ " ainecto term restore [--json] start again the sessions that were running when the daemon or the machine stopped",
12628
+ " ainecto term remote <name> show the session in AiNecto on the web (plain text) and type there (signed in; Ctrl+C to stop; log: ~/.ainecto/term/remote.log)"
12242
12629
  ];
12243
12630
  async function executeTermCommand(input) {
12244
12631
  const [action, ...rest] = input.argv;
@@ -12294,9 +12681,46 @@ async function executeTermCommand(input) {
12294
12681
  case "daemon":
12295
12682
  return await daemonCommand(paths, rest);
12296
12683
  default:
12297
- throw usage(`term new|ls|send|key|read|wait|attach|kill|kill-server|restore \u2014 see ainecto --help`);
12684
+ throw usage(`term new|ls|send|key|read|wait|attach|kill|kill-server|restore|remote \u2014 see ainecto --help`);
12298
12685
  }
12299
12686
  }
12687
+ async function executeTermRemote(input) {
12688
+ const name = singleName(parseArgs(input.argv, {}).positionals, "term remote <name>");
12689
+ const paths = termPaths();
12690
+ await ensurePrivateDir(paths.dir);
12691
+ const log = openRemoteLog(paths);
12692
+ const host = hostname();
12693
+ log.write({ event: "remote_start", pid: process.pid, version: CLI_VERSION_LABEL, endpoint: input.endpoint, host, session: name });
12694
+ const controller = new AbortController();
12695
+ const onSignal = () => controller.abort();
12696
+ process.once("SIGINT", onSignal);
12697
+ process.once("SIGTERM", onSignal);
12698
+ let result;
12699
+ try {
12700
+ result = await runRemote({
12701
+ paths,
12702
+ session: name,
12703
+ http: createRemoteHttp({ endpoint: input.endpoint, tokenProvider: input.auth, log }),
12704
+ log,
12705
+ hostName: host,
12706
+ cliVersion: CLI_VERSION_LABEL,
12707
+ signal: controller.signal,
12708
+ print: (line) => input.io.stderr.write(`${line}
12709
+ `)
12710
+ });
12711
+ } catch (error) {
12712
+ log.write({ event: "remote_stop", pid: process.pid, reason: `error: ${error instanceof Error ? error.message : String(error)}` });
12713
+ throw error;
12714
+ } finally {
12715
+ process.off("SIGINT", onSignal);
12716
+ process.off("SIGTERM", onSignal);
12717
+ }
12718
+ log.write({ event: "remote_stop", pid: process.pid, reason: result.reason, exitCode: result.exitCode });
12719
+ if (result.exitCode !== 0) {
12720
+ throw new TermError("TERM_REMOTE_FAILED", result.reason);
12721
+ }
12722
+ return print(input, result, result.reason);
12723
+ }
12300
12724
  async function newSession(paths, argv, input) {
12301
12725
  const args = parseArgs(argv, { cwd: "string" });
12302
12726
  const name = singleName(args.positionals, "term new <name> [--cwd DIR] [-- command args\u2026]");
@@ -12316,7 +12740,7 @@ async function listSessions(paths, argv, input) {
12316
12740
  parseArgs(argv, {});
12317
12741
  const result = await termRequest(paths, { op: "ls" }, { start: false });
12318
12742
  const data = result.daemon ? result.data : { sessions: [] };
12319
- const sessions = sessionsField(data);
12743
+ const sessions = listedSessions(data);
12320
12744
  const human = sessions.length === 0 ? "No term sessions." : renderTable(sessions.map((session) => ({
12321
12745
  name: session.name,
12322
12746
  pid: session.pid,
@@ -12463,9 +12887,6 @@ function print(input, data, human) {
12463
12887
  `);
12464
12888
  return 0;
12465
12889
  }
12466
- function noSession(name) {
12467
- return new TermError("TERM_NO_SESSION", `No session named "${name}" (no term sessions are running).`);
12468
- }
12469
12890
  function usage(text) {
12470
12891
  return new TermError("TERM_USAGE", `Usage: ainecto ${text}`);
12471
12892
  }
@@ -12525,19 +12946,6 @@ function singleName(positionals, usageText) {
12525
12946
  function countFlag(value) {
12526
12947
  return typeof value === "number" ? value : void 0;
12527
12948
  }
12528
- function sessionsField(data) {
12529
- if (data && typeof data === "object" && "sessions" in data && Array.isArray(data.sessions)) {
12530
- return data.sessions.filter(isListedSession);
12531
- }
12532
- return [];
12533
- }
12534
- function isListedSession(value) {
12535
- if (!value || typeof value !== "object") {
12536
- return false;
12537
- }
12538
- const session = value;
12539
- return typeof session.name === "string" && typeof session.pid === "number" && typeof session.cwd === "string";
12540
- }
12541
12949
  function linesField(data) {
12542
12950
  if (data && typeof data === "object" && "lines" in data && Array.isArray(data.lines)) {
12543
12951
  return data.lines.filter((line) => typeof line === "string");
@@ -12563,7 +12971,7 @@ function restoreSummary(data) {
12563
12971
  }
12564
12972
 
12565
12973
  // src/adapters/cli/agentCommand.ts
12566
- import { hostname } from "os";
12974
+ import { hostname as hostname2 } from "os";
12567
12975
 
12568
12976
  // src/core/agent/agents.ts
12569
12977
  var AGENT_IDS = ["claude-code", "codex"];
@@ -13386,101 +13794,34 @@ function toError(error) {
13386
13794
  }
13387
13795
 
13388
13796
  // src/core/agent/http.ts
13389
- import { randomUUID as randomUUID2 } from "crypto";
13390
- var AgentCallError = class extends Error {
13797
+ var AgentCallError = class extends PcCallError {
13391
13798
  constructor(message, op, status, code) {
13392
- super(message);
13393
- this.op = op;
13394
- this.status = status;
13395
- this.code = code;
13799
+ super(message, op, status, code);
13396
13800
  this.name = "AgentCallError";
13397
13801
  }
13398
- op;
13399
- status;
13400
- code;
13401
- /** 다시 해 볼 만한가 — 네트워크·기한·5xx·429. */
13402
- get retryable() {
13403
- return this.status === void 0 || this.status >= 500 || this.status === 429;
13404
- }
13405
13802
  };
13406
13803
  function createAgentHttp(input) {
13407
- const fetchImpl = input.fetchImpl ?? fetch;
13408
- const base = `${input.endpoint.replace(/\/+$/, "")}/agent/pc/`;
13409
- let linkToken;
13410
- async function send(op, payload, token, options) {
13411
- const controller = new AbortController();
13412
- const timer = setTimeout(
13413
- () => controller.abort(new DOMException("timed out", "TimeoutError")),
13414
- (options.holdMs ?? 0) + AGENT_CALL_TIMEOUT_MS
13415
- );
13416
- const onStop = () => controller.abort(new DOMException("stopped", "AbortError"));
13417
- options.signal?.addEventListener("abort", onStop, { once: true });
13418
- const headers = { "Content-Type": "application/json", Accept: "application/json" };
13419
- if (token) headers.Authorization = `Bearer ${token}`;
13420
- if (linkToken && op !== "open") headers["X-Link-Token"] = linkToken;
13421
- try {
13422
- const response = await fetchImpl(base + op, { method: "POST", headers, body: payload, signal: controller.signal });
13423
- await response.clone().arrayBuffer();
13424
- return response;
13425
- } catch (error) {
13426
- throw controller.signal.aborted && controller.signal.reason instanceof Error ? controller.signal.reason : error;
13427
- } finally {
13428
- clearTimeout(timer);
13429
- options.signal?.removeEventListener("abort", onStop);
13430
- }
13431
- }
13432
- return {
13433
- useLinkToken(token) {
13434
- linkToken = token;
13435
- },
13436
- async call(op, body, options = {}) {
13437
- const callId = randomUUID2();
13438
- const payload = JSON.stringify(body);
13439
- const started = Date.now();
13440
- input.log.write({ event: "agent_call", callId, op, turnUuid: options.turnUuid, bytes: Buffer.byteLength(payload, "utf8") });
13441
- let outcome = {
13442
- ok: false,
13443
- error: "no response"
13444
- };
13445
- try {
13446
- let response = await send(op, payload, await input.tokenProvider.getAccessToken(), options);
13447
- if (response.status === 401) {
13448
- response = await send(op, payload, await input.tokenProvider.refreshAfterUnauthorized(), options);
13449
- }
13450
- const text = await response.text();
13451
- const parsed = parseJson2(text);
13452
- if (!response.ok) {
13453
- const code = typeof parsed?.code === "string" ? parsed.code : void 0;
13454
- outcome = { ok: false, status: response.status, code };
13455
- throw new AgentCallError(
13456
- typeof parsed?.detail === "string" ? parsed.detail : `HTTP ${response.status}`,
13457
- op,
13458
- response.status,
13459
- code
13460
- );
13461
- }
13462
- const offers = Array.isArray(parsed?.offers) ? parsed.offers.length : void 0;
13463
- outcome = { ok: true, status: response.status, offers };
13464
- return parsed ?? {};
13465
- } catch (error) {
13466
- if (error instanceof AgentCallError) throw error;
13467
- const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
13468
- outcome = { ok: false, error: timedOut ? error.name : error instanceof Error ? error.message : String(error) };
13469
- throw new AgentCallError(timedOut ? `${op} timed out` : `${op} failed: ${outcome.error}`, op);
13470
- } finally {
13471
- input.log.write({ event: "agent_call_response", callId, op, ...outcome, ms: Date.now() - started });
13472
- }
13804
+ const http = createPcHttp({
13805
+ endpoint: input.endpoint,
13806
+ path: "agent/pc",
13807
+ tokenProvider: input.tokenProvider,
13808
+ timeoutMs: AGENT_CALL_TIMEOUT_MS,
13809
+ sessionHeader: "X-Link-Token",
13810
+ error: (message, op, status, code) => new AgentCallError(message, op, status, code),
13811
+ fetchImpl: input.fetchImpl,
13812
+ logging: {
13813
+ log: input.log,
13814
+ request: ({ callId, op, bytes }, options) => ({ event: "agent_call", callId, op, turnUuid: options?.turnUuid, bytes }),
13815
+ response: ({ callId, op, ms }, outcome) => ({
13816
+ event: "agent_call_response",
13817
+ callId,
13818
+ op,
13819
+ ...outcome.ok ? { ok: true, status: outcome.status, offers: Array.isArray(outcome.body.offers) ? outcome.body.offers.length : void 0 } : outcome,
13820
+ ms
13821
+ })
13473
13822
  }
13474
- };
13475
- }
13476
- function parseJson2(text) {
13477
- if (!text) return void 0;
13478
- try {
13479
- const value = JSON.parse(text);
13480
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
13481
- } catch {
13482
- return void 0;
13483
- }
13823
+ });
13824
+ return { call: http.call, useLinkToken: http.useSessionToken };
13484
13825
  }
13485
13826
 
13486
13827
  // src/core/agent/tools.ts
@@ -14139,7 +14480,7 @@ async function runAgentServe(deps) {
14139
14480
  }
14140
14481
  const linkId = String(opened.linkId);
14141
14482
  deps.http.useLinkToken(String(opened.linkToken));
14142
- const limits = serverLimits(opened.limits);
14483
+ const limits = serverLimits2(opened.limits);
14143
14484
  const displayName = (id) => deps.adapters.get(id)?.displayName ?? id;
14144
14485
  const names = deps.agents.map((a) => displayName(a.id)).join(" / ");
14145
14486
  deps.print(`Connected to AiNecto as ${deps.hostName}. Requests to \xABMy agent\xBB in AiNecto Chat now run in ${names} on this machine. Press Ctrl+C to stop.`);
@@ -14469,7 +14810,7 @@ async function runAgentServe(deps) {
14469
14810
  function jobKey(job) {
14470
14811
  return job.kind === "chat" ? job.offer.turnUuid : todoKey(job.todo.todoId);
14471
14812
  }
14472
- function serverLimits(value) {
14813
+ function serverLimits2(value) {
14473
14814
  const v = value ?? {};
14474
14815
  const num = (key) => {
14475
14816
  const n = v[key];
@@ -14487,7 +14828,8 @@ async function openLink(deps, agents) {
14487
14828
  const features = pcFeatures(deps.todos !== void 0);
14488
14829
  const older = features.filter((f) => f !== "todos");
14489
14830
  const attempts = [
14490
- { body: { ...base, agents, features } },
14831
+ ...deps.cliBuild ? [{ body: { ...base, cliBuild: deps.cliBuild, agents, features } }] : [],
14832
+ { body: { ...base, agents, features }, ...deps.cliBuild ? { dropped: "cliBuild" } : {} },
14491
14833
  ...older.length < features.length ? [{ body: { ...base, agents, features: older }, dropped: "features.todos" }] : [],
14492
14834
  ...named ? [{ body: { ...base, agents: unnamed, features: older }, dropped: "agents.name" }] : [],
14493
14835
  { body: { ...base, agents: unnamed }, dropped: "features" }
@@ -14540,21 +14882,6 @@ function offersIn(res) {
14540
14882
  }] : [];
14541
14883
  });
14542
14884
  }
14543
- function sleep(ms, signal) {
14544
- return new Promise((resolve4) => {
14545
- if (signal.aborted) {
14546
- resolve4();
14547
- return;
14548
- }
14549
- const timer = setTimeout(done, ms);
14550
- signal.addEventListener("abort", done, { once: true });
14551
- function done() {
14552
- clearTimeout(timer);
14553
- signal.removeEventListener("abort", done);
14554
- resolve4();
14555
- }
14556
- });
14557
- }
14558
14885
 
14559
14886
  // src/core/agent/sessions.ts
14560
14887
  import { readFile as readFile10, rename as rename7, writeFile as writeFile7 } from "fs/promises";
@@ -14630,7 +14957,7 @@ async function executeAgentServe(input) {
14630
14957
  await ensurePrivateDir(paths.dir);
14631
14958
  await ensurePrivateDir(paths.work);
14632
14959
  const log = openAgentLog(paths);
14633
- const host = hostname();
14960
+ const host = hostname2();
14634
14961
  const client = (agentName) => new McpRpcClient({ endpoint: input.endpoint, tokenProvider: input.auth, channel: "cli", ...agentName ? { agentName } : {} });
14635
14962
  const tools = createAgentTools({
14636
14963
  client: client(),
@@ -14654,7 +14981,7 @@ async function executeAgentServe(input) {
14654
14981
  log.write({
14655
14982
  event: "serve_start",
14656
14983
  pid: process.pid,
14657
- version: CLI_VERSION,
14984
+ version: CLI_VERSION_LABEL,
14658
14985
  endpoint: input.endpoint,
14659
14986
  host,
14660
14987
  agents: checks.map(({ id, installed, ready, auth, version }) => ({ id, installed, ready, ...auth ? { auth } : {}, ...version ? { version } : {} }))
@@ -14690,7 +15017,8 @@ async function executeAgentServe(input) {
14690
15017
  adapters,
14691
15018
  agents,
14692
15019
  hostName: host,
14693
- cliVersion: CLI_VERSION,
15020
+ cliVersion: CLI_VERSION_LABEL,
15021
+ ...CLI_BUILD ? { cliBuild: CLI_BUILD } : {},
14694
15022
  print: (line) => input.io.stderr.write(`${line}
14695
15023
  `),
14696
15024
  signal: controller.signal,
@@ -14721,7 +15049,7 @@ async function runAinectoCli(argv, io) {
14721
15049
  io.stdout.write(helpText());
14722
15050
  return 0;
14723
15051
  }
14724
- if (parsed.positionals[0] === "term") {
15052
+ if (parsed.positionals[0] === "term" && parsed.positionals[1] !== "remote") {
14725
15053
  return await executeTermCommand({ argv: parsed.positionals.slice(1), json: parsed.json, io });
14726
15054
  }
14727
15055
  const resolved = resolveEndpoint({ env: parsed.env, endpoint: parsed.endpoint });
@@ -14823,6 +15151,9 @@ async function runAinectoCli(argv, io) {
14823
15151
  io
14824
15152
  });
14825
15153
  }
15154
+ if (domain === "term") {
15155
+ return await executeTermRemote({ argv: rest, json: parsed.json, io, endpoint: resolved.endpoint, auth: connect2().auth });
15156
+ }
14826
15157
  if (isAgentCommand(domain, action)) {
14827
15158
  return await executeAgentServe({ endpoint: resolved.endpoint, env: resolved.env, auth: connect2().auth, io, agentName });
14828
15159
  }