@ainecto/cli 0.14.0-next.10 → 0.14.0-next.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5686,8 +5686,8 @@ function legacyRoleInput(flag, envVars = process.env) {
5686
5686
 
5687
5687
  // src/core/version.ts
5688
5688
  var UNBUNDLED_VERSION = "dev";
5689
- var CLI_VERSION = true ? "0.14.0-next.10" : UNBUNDLED_VERSION;
5690
- var CLI_BUILD = true ? "f5e52e5" : void 0;
5689
+ var CLI_VERSION = true ? "0.14.0-next.12" : UNBUNDLED_VERSION;
5690
+ var CLI_BUILD = true ? "d070964" : void 0;
5691
5691
  function cliVersionLabel(version, build, release) {
5692
5692
  return release || build === void 0 ? version : `${version}-dev+${build}`;
5693
5693
  }
@@ -10587,6 +10587,47 @@ var DAEMON_START_ATTEMPTS = 3;
10587
10587
  var DAEMON_LOG_MAX_BYTES = 10 * 1024 * 1024;
10588
10588
  var TERM_STRING_HOLD_MAX_CHARS = 1048576;
10589
10589
 
10590
+ // src/core/term/paths.ts
10591
+ import { createHash as createHash5 } from "crypto";
10592
+ import { homedir as homedir2 } from "os";
10593
+ import { isAbsolute, join as join6, posix, win32 } from "path";
10594
+ function appHome(platform = process.platform, env = process.env, home = homedir2()) {
10595
+ if (platform === "darwin") return posix.join(home, "Library", "Application Support", "ainecto");
10596
+ if (platform === "win32") return win32.join(env.LOCALAPPDATA || win32.join(home, "AppData", "Local"), "ainecto");
10597
+ const xdg = env.XDG_DATA_HOME;
10598
+ return posix.join(xdg && isAbsolute(xdg) ? xdg : posix.join(home, ".local", "share"), "ainecto");
10599
+ }
10600
+ function isUuid(value) {
10601
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value);
10602
+ }
10603
+ function webSessionFolder(app, projectUuid, requestId) {
10604
+ if (!isUuid(requestId)) {
10605
+ throw new TermError("TERM_BAD_REQUEST", `The create request id "${requestId}" is not a UUID, so no session folder was made.`);
10606
+ }
10607
+ if (projectUuid === void 0) return join6(app, "sessions", requestId);
10608
+ if (!isUuid(projectUuid)) {
10609
+ throw new TermError("TERM_BAD_REQUEST", `The project "${projectUuid}" is not a UUID, so no session folder was made.`);
10610
+ }
10611
+ return join6(app, "projects", projectUuid, "sessions", requestId);
10612
+ }
10613
+ function termPaths(home = homedir2()) {
10614
+ const dir = join6(home, ".ainecto", "term");
10615
+ return {
10616
+ dir,
10617
+ socket: join6(dir, "ctl.sock"),
10618
+ lockFile: join6(dir, "daemon.lock"),
10619
+ // ★설계는 `\0ainecto-term-<uid>.lock` 이다. 추상 이름은 홈 폴더와 무관하게 기기 전체에 하나라서, 홈이 다른
10620
+ // 두 폴더(시험·다른 HOME)가 서로의 잠금을 막는다. 잠금이 지키는 것은 «이 폴더의 소켓»이므로 폴더 경로를 넣는다.
10621
+ abstractLockName: `\0ainecto-term-${process.getuid?.() ?? "na"}-${createHash5("sha256").update(dir).digest("hex")}.lock`,
10622
+ daemonInfo: join6(dir, "daemon.json"),
10623
+ manifest: join6(dir, "sessions.json"),
10624
+ log: join6(dir, "daemon.log"),
10625
+ previousLog: join6(dir, "daemon.log.1"),
10626
+ remoteLog: join6(dir, "remote.log"),
10627
+ previousRemoteLog: join6(dir, "remote.log.1")
10628
+ };
10629
+ }
10630
+
10590
10631
  // src/core/term/protocol.ts
10591
10632
  var RETRY_CODE = "TERM_DAEMON_RETRY";
10592
10633
  function encodeLine(message2) {
@@ -10643,7 +10684,8 @@ function parseClientMessage(line) {
10643
10684
  command: record3.command === null ? null : stringArrayField(record3, "command"),
10644
10685
  env: stringMapField(record3, "env"),
10645
10686
  cols: optionalSize(record3, "cols"),
10646
- rows: optionalSize(record3, "rows")
10687
+ rows: optionalSize(record3, "rows"),
10688
+ ...record3.project === void 0 ? {} : { project: projectField(record3, "project") }
10647
10689
  };
10648
10690
  case "ls":
10649
10691
  case "kill-server":
@@ -10775,6 +10817,13 @@ function sizeField(record3, key) {
10775
10817
  }
10776
10818
  return value;
10777
10819
  }
10820
+ function projectField(record3, key) {
10821
+ const value = stringField(record3, key);
10822
+ if (!isUuid(value)) {
10823
+ throw new TermProtocolError(`"${key}" must be a lowercase UUID.`);
10824
+ }
10825
+ return value;
10826
+ }
10778
10827
  function optionalSize(record3, key) {
10779
10828
  return record3[key] === void 0 ? void 0 : sizeField(record3, key);
10780
10829
  }
@@ -11072,7 +11121,7 @@ function isEntry(value) {
11072
11121
  return false;
11073
11122
  }
11074
11123
  const entry = value;
11075
- return typeof entry.name === "string" && typeof entry.cwd === "string" && typeof entry.createdAt === "string" && (entry.label === void 0 || typeof entry.label === "string") && (entry.command === null || Array.isArray(entry.command) && entry.command.every((item) => typeof item === "string"));
11124
+ return typeof entry.name === "string" && typeof entry.cwd === "string" && typeof entry.createdAt === "string" && (entry.label === void 0 || typeof entry.label === "string") && (entry.project === void 0 || typeof entry.project === "string") && (entry.command === null || Array.isArray(entry.command) && entry.command.every((item) => typeof item === "string"));
11076
11125
  }
11077
11126
 
11078
11127
  // src/core/term/sessionName.ts
@@ -11110,15 +11159,26 @@ var CURSOR_KEYS = {
11110
11159
  home: "H",
11111
11160
  end: "F"
11112
11161
  };
11162
+ var TILDE_KEYS = {
11163
+ delete: 3,
11164
+ pageup: 5,
11165
+ pagedown: 6
11166
+ };
11113
11167
  var ALIASES = {
11114
11168
  esc: "escape",
11115
11169
  return: "enter",
11116
- btab: "shift-tab"
11170
+ btab: "shift-tab",
11171
+ "/": "slash"
11117
11172
  };
11173
+ var MODIFIERS = ["ctrl", "shift", "alt"];
11118
11174
  var KEY_NAMES = [
11119
11175
  ...Object.keys(PLAIN_KEYS),
11120
11176
  ...Object.keys(CURSOR_KEYS),
11121
- "ctrl-a \u2026 ctrl-z"
11177
+ "ctrl-a \u2026 ctrl-z",
11178
+ "ctrl-space",
11179
+ "ctrl-slash",
11180
+ "alt-<key>",
11181
+ "ctrl-/shift-/alt- + up/down/left/right/home/end/pageup/pagedown/delete"
11122
11182
  ];
11123
11183
  function normalizeKeyName(raw) {
11124
11184
  const lower = raw.trim().toLowerCase().replace(/\+/g, "-");
@@ -11134,11 +11194,39 @@ function keyBytes(raw, context) {
11134
11194
  if (cursor !== void 0) {
11135
11195
  return `${context.applicationCursorKeys ? "\x1BO" : "\x1B["}${cursor}`;
11136
11196
  }
11137
- const ctrl = /^ctrl-([a-z])$/.exec(name);
11138
- if (ctrl?.[1]) {
11139
- return String.fromCharCode(ctrl[1].charCodeAt(0) - 96);
11140
- }
11141
- return void 0;
11197
+ return comboBytes(name);
11198
+ }
11199
+ function comboBytes(name) {
11200
+ const parts = name.split("-");
11201
+ const last = parts.pop() ?? "";
11202
+ const base = ALIASES[last] ?? last;
11203
+ const mods = /* @__PURE__ */ new Set();
11204
+ for (const part of parts) {
11205
+ const mod = MODIFIERS.find((m2) => m2 === part);
11206
+ if (!mod || mods.has(mod)) return void 0;
11207
+ mods.add(mod);
11208
+ }
11209
+ if (mods.size === 0 || base === "") return void 0;
11210
+ const ctrl = mods.has("ctrl");
11211
+ const shift = mods.has("shift");
11212
+ const alt = mods.has("alt");
11213
+ const m = 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
11214
+ const cursor = CURSOR_KEYS[base];
11215
+ if (cursor !== void 0) return `\x1B[1;${m}${cursor}`;
11216
+ const tilde = TILDE_KEYS[base];
11217
+ if (tilde !== void 0) return `\x1B[${tilde};${m}~`;
11218
+ const single = singleByte(base, ctrl, shift);
11219
+ if (single === void 0) return void 0;
11220
+ return alt ? `\x1B${single}` : single;
11221
+ }
11222
+ function singleByte(base, ctrl, shift) {
11223
+ if (/^[a-z]$/.test(base)) {
11224
+ return ctrl ? String.fromCharCode(base.charCodeAt(0) - 96) : shift ? base.toUpperCase() : base;
11225
+ }
11226
+ if (base === "space") return ctrl && !shift ? "\0" : !ctrl && !shift ? " " : void 0;
11227
+ if (base === "slash") return ctrl && !shift ? "" : !ctrl && !shift ? "/" : void 0;
11228
+ const plain = PLAIN_KEYS[base];
11229
+ return !ctrl && !shift && plain !== void 0 && plain.length === 1 ? plain : void 0;
11142
11230
  }
11143
11231
  function pasteBytes(text2, bracketedPasteMode) {
11144
11232
  return bracketedPasteMode ? `\x1B[200~${text2}\x1B[201~` : text2;
@@ -11596,6 +11684,7 @@ var TermSession = class _TermSession {
11596
11684
  rows: this.pty.rows,
11597
11685
  clients: this.attached.size,
11598
11686
  ...this.label !== void 0 ? { label: this.label } : {},
11687
+ ...this.spec.project !== void 0 ? { project: this.spec.project } : {},
11599
11688
  ...this.lastOutputAt !== void 0 ? { lastOutputAt: this.lastOutputAt } : {}
11600
11689
  };
11601
11690
  }
@@ -11988,7 +12077,13 @@ var TermDaemon = class {
11988
12077
  switch (request.op) {
11989
12078
  case "new": {
11990
12079
  assertSessionName(request.name);
11991
- const entry = { name: request.name, cwd: request.cwd, command: request.command, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
12080
+ const entry = {
12081
+ name: request.name,
12082
+ cwd: request.cwd,
12083
+ command: request.command,
12084
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
12085
+ ...request.project !== void 0 ? { project: request.project } : {}
12086
+ };
11992
12087
  const session = await this.startSession(entry, request.env, request.cols, request.rows);
11993
12088
  this.updateManifest((entries2) => [...entries2.filter((item) => item.name !== entry.name), entry]);
11994
12089
  return { data: session.info() };
@@ -12076,7 +12171,10 @@ var TermDaemon = class {
12076
12171
  */
12077
12172
  async startSession(entry, env, cols, rows) {
12078
12173
  if (this.sessions.has(entry.name) || this.starting.has(entry.name)) {
12079
- throw new TermError("TERM_SESSION_EXISTS", `A session named "${entry.name}" already exists.`);
12174
+ throw new TermError(
12175
+ "TERM_SESSION_EXISTS",
12176
+ `A session named "${entry.name}" already exists. Open it with \`ainecto term attach ${entry.name}\`, or choose another name.`
12177
+ );
12080
12178
  }
12081
12179
  this.starting.add(entry.name);
12082
12180
  try {
@@ -12258,28 +12356,6 @@ var DetachKeyScanner = class {
12258
12356
  }
12259
12357
  };
12260
12358
 
12261
- // src/core/term/paths.ts
12262
- import { createHash as createHash5 } from "crypto";
12263
- import { homedir as homedir2 } from "os";
12264
- import { join as join6 } from "path";
12265
- function termPaths(home = homedir2()) {
12266
- const dir = join6(home, ".ainecto", "term");
12267
- return {
12268
- dir,
12269
- socket: join6(dir, "ctl.sock"),
12270
- lockFile: join6(dir, "daemon.lock"),
12271
- // ★설계는 `\0ainecto-term-<uid>.lock` 이다. 추상 이름은 홈 폴더와 무관하게 기기 전체에 하나라서, 홈이 다른
12272
- // 두 폴더(시험·다른 HOME)가 서로의 잠금을 막는다. 잠금이 지키는 것은 «이 폴더의 소켓»이므로 폴더 경로를 넣는다.
12273
- abstractLockName: `\0ainecto-term-${process.getuid?.() ?? "na"}-${createHash5("sha256").update(dir).digest("hex")}.lock`,
12274
- daemonInfo: join6(dir, "daemon.json"),
12275
- manifest: join6(dir, "sessions.json"),
12276
- log: join6(dir, "daemon.log"),
12277
- previousLog: join6(dir, "daemon.log.1"),
12278
- remoteLog: join6(dir, "remote.log"),
12279
- previousRemoteLog: join6(dir, "remote.log.1")
12280
- };
12281
- }
12282
-
12283
12359
  // src/core/term/wait.ts
12284
12360
  async function waitForMatch(paths, name, pattern, range, timeoutMs) {
12285
12361
  const client = await openTermClient(paths, { start: false });
@@ -12768,12 +12844,18 @@ var DEFAULT_AGENT = "claude-code";
12768
12844
  function isAgentId(value) {
12769
12845
  return typeof value === "string" && AGENT_IDS.includes(value);
12770
12846
  }
12771
- function agentReplySchema(textMaxCharacters) {
12847
+ var REPLY_KEYS = ["reply", "openDocumentUuids", "openCardUuids"];
12848
+ function agentReplySchema(textMaxCharacters, documentsMax) {
12849
+ const ids = (description) => ({ type: "array", maxItems: documentsMax, items: { type: "string", pattern: "^[0-9a-f]{32}$" }, description });
12772
12850
  return {
12773
12851
  type: "object",
12774
12852
  additionalProperties: false,
12775
- required: ["reply"],
12776
- properties: { reply: { type: "string", minLength: 1, maxLength: textMaxCharacters } }
12853
+ required: [...REPLY_KEYS],
12854
+ properties: {
12855
+ reply: { type: "string", minLength: 1, maxLength: textMaxCharacters },
12856
+ openDocumentUuids: ids("AiNecto documents you found or worked on in this turn that the user should open (documentUuid). May be empty."),
12857
+ openCardUuids: ids("AiNecto kanban cards you found or worked on in this turn that the user should open (cardUuid). May be empty.")
12858
+ }
12777
12859
  };
12778
12860
  }
12779
12861
  var AINECTO_MCP_SERVER = "ainecto";
@@ -12910,6 +12992,7 @@ function createAgentHttp(input) {
12910
12992
  }
12911
12993
 
12912
12994
  // src/core/agent/prompt.ts
12995
+ var AGENT_OPEN_RULE = "[AiNecto rule] You cannot change the user's AiNecto web screen \u2014 never say you opened, showed or switched to a document or card. When asked to open or show one, find it with the AiNecto tools and put it in openDocumentUuids / openCardUuids (the chat shows an \xAB\uC5F4\uAE30\xBB button for each), then say so truthfully, e.g. \xAB\uCC3E\uC558\uC2B5\uB2C8\uB2E4. \uC544\uB798 \uC5F4\uAE30 \uBC84\uD2BC\uC5D0\uC11C \uD655\uC778\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4.\xBB";
12913
12996
  function agentPromptText(text2, context) {
12914
12997
  const parts = [];
12915
12998
  const p = context?.project;
@@ -12920,12 +13003,16 @@ function agentPromptText(text2, context) {
12920
13003
  if (d && typeof d.uuid === "string") {
12921
13004
  parts.push(`open document \xAB${str(d.title)}\xBB (documentUuid ${d.uuid}${typeof d.type === "string" ? `, ${d.type}` : ""})`);
12922
13005
  }
13006
+ const c = context?.card;
13007
+ if (c && typeof c.uuid === "string") {
13008
+ parts.push(`card \xAB${str(c.title)}\xBB (${typeof c.key === "string" ? `${c.key}, ` : ""}cardUuid ${c.uuid})`);
13009
+ }
12923
13010
  const files = Array.isArray(context?.attachments) ? context.attachments.map((f) => str(f?.filename)).filter((name) => name !== "") : [];
12924
13011
  if (files.length > 0) {
12925
13012
  parts.push(`attached files ${files.map((name) => `\xAB${name}\xBB`).join(", ")} (names only \u2014 the files are not available on this machine)`);
12926
13013
  }
12927
- if (parts.length === 0) return text2;
12928
- return `[AiNecto context \u2014 "this project" / "this document" mean these] ${parts.join(" \xB7 ")}
13014
+ const head = parts.length === 0 ? [AGENT_OPEN_RULE] : [AGENT_OPEN_RULE, `[AiNecto context \u2014 "this project" / "this document" / "this card" mean these] ${parts.join(" \xB7 ")}`];
13015
+ return `${head.join("\n")}
12929
13016
 
12930
13017
  ${text2}`;
12931
13018
  }
@@ -12949,10 +13036,9 @@ ${outcome.stderrTail}` : ""));
12949
13036
  return failed("AGENT_ERROR", `${agentName} \uAC00 \uC2E4\uD328\uD588\uC5B4\uC694(${result.subtype ?? "error"}).` + (result.resultText ? `
12950
13037
  ${result.resultText}` : ""));
12951
13038
  }
12952
- const reply = result.structuredOutput?.reply;
12953
- const keys = result.structuredOutput && typeof result.structuredOutput === "object" ? Object.keys(result.structuredOutput) : [];
12954
- if (typeof reply === "string" && reply.trim().length > 0 && keys.length === 1 && codePoints(reply) <= limits.textMaxCharacters) {
12955
- return { status: "DONE", reply, ...attached };
13039
+ const answer = schemaAnswer(result.structuredOutput, limits.textMaxCharacters);
13040
+ if (answer) {
13041
+ return { status: "DONE", reply: answer.reply, ...attachedWork(outcome, limits, answer) };
12956
13042
  }
12957
13043
  const raw = result.structuredOutput !== void 0 ? JSON.stringify(result.structuredOutput) : result.resultText ?? "";
12958
13044
  return failed("SCHEMA_VIOLATION", `\uB2F5 \uD615\uC2DD\uC774 \uC5B4\uAE0B\uB0AC\uC5B4\uC694.
@@ -12967,17 +13053,35 @@ function stoppedReply(outcome, limits) {
12967
13053
  ...outcome ? attachedWork(outcome, limits) : { documentUuids: [] }
12968
13054
  };
12969
13055
  }
12970
- function attachedWork(outcome, limits) {
13056
+ function schemaAnswer(value, textMaxCharacters) {
13057
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
13058
+ const keys = Object.keys(value);
13059
+ if (keys.length !== REPLY_KEYS.length || !REPLY_KEYS.every((key) => keys.includes(key))) return void 0;
13060
+ const { reply, openDocumentUuids, openCardUuids } = value;
13061
+ if (typeof reply !== "string" || reply.trim().length === 0 || codePoints(reply) > textMaxCharacters) return void 0;
13062
+ if (!isStringArray2(openDocumentUuids) || !isStringArray2(openCardUuids)) return void 0;
13063
+ return { reply, openDocumentUuids, openCardUuids };
13064
+ }
13065
+ function attachedWork(outcome, limits, open2) {
12971
13066
  const facts = outcome.kind === "result" ? outcome.facts : void 0;
12972
- const documentUuids = facts ? facts.documents.slice(0, limits.documentsMax) : [];
12973
- const createdDocumentUuids = facts ? facts.createdDocuments.filter((uuid) => documentUuids.includes(uuid)) : [];
12974
- const cardUuids = facts ? facts.cards.slice(0, limits.documentsMax) : [];
13067
+ const seen = (uuids) => (uuids ?? []).filter((uuid) => facts?.seen.includes(uuid));
13068
+ const documentUuids = unique([...facts?.documents ?? [], ...seen(open2?.openDocumentUuids)]).slice(0, limits.documentsMax);
13069
+ const createdDocumentUuids = (facts?.createdDocuments ?? []).filter((uuid) => documentUuids.includes(uuid));
13070
+ const foundDocumentUuids = documentUuids.filter((uuid) => !facts?.documents.includes(uuid));
13071
+ const cardUuids = unique([...facts?.cards ?? [], ...seen(open2?.openCardUuids)]).slice(0, limits.documentsMax);
12975
13072
  return {
12976
13073
  documentUuids,
12977
13074
  ...createdDocumentUuids.length > 0 ? { createdDocumentUuids } : {},
13075
+ ...foundDocumentUuids.length > 0 ? { foundDocumentUuids } : {},
12978
13076
  ...cardUuids.length > 0 ? { cardUuids } : {}
12979
13077
  };
12980
13078
  }
13079
+ function isStringArray2(value) {
13080
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
13081
+ }
13082
+ function unique(items) {
13083
+ return [...new Set(items)];
13084
+ }
12981
13085
  function codePoints(text2) {
12982
13086
  return Array.from(text2).length;
12983
13087
  }
@@ -13577,6 +13681,7 @@ async function runAgentServe(deps) {
13577
13681
  conversationUuid,
13578
13682
  resumeRef: deps.sessions.get(conversationUuid, adapter.id),
13579
13683
  textMaxCharacters: limits.textMaxCharacters,
13684
+ documentsMax: limits.documentsMax,
13580
13685
  ...agentName ? { agentName } : {}
13581
13686
  });
13582
13687
  live.set(adapter.id, session);
@@ -13619,7 +13724,8 @@ async function runAgentServe(deps) {
13619
13724
  }
13620
13725
  current = { key: offer.key, session };
13621
13726
  try {
13622
- outcome = await session.send(agentPromptText(offer.text, offer.context), deps.turnTimeoutMs ?? AGENT_TURN_TIMEOUT_MS);
13727
+ const text2 = offer.todoId === void 0 ? agentPromptText(offer.text, offer.context) : offer.text;
13728
+ outcome = await session.send(text2, deps.turnTimeoutMs ?? AGENT_TURN_TIMEOUT_MS);
13623
13729
  } finally {
13624
13730
  current = void 0;
13625
13731
  }
@@ -13654,6 +13760,7 @@ async function runAgentServe(deps) {
13654
13760
  sessionId: session?.sessionRef,
13655
13761
  documents: reply?.documentUuids.length ?? 0,
13656
13762
  createdDocuments: reply?.createdDocumentUuids?.length ?? 0,
13763
+ foundDocuments: reply?.foundDocumentUuids?.length ?? 0,
13657
13764
  cards: reply?.cardUuids?.length ?? 0,
13658
13765
  numTurns: result?.numTurns,
13659
13766
  costUsd: result?.costUsd
@@ -13672,6 +13779,7 @@ async function runAgentServe(deps) {
13672
13779
  reply: reply.reply,
13673
13780
  documentUuids: reply.documentUuids,
13674
13781
  ...reply.createdDocumentUuids ? { createdDocumentUuids: reply.createdDocumentUuids } : {},
13782
+ ...reply.foundDocumentUuids ? { foundDocumentUuids: reply.foundDocumentUuids } : {},
13675
13783
  ...reply.cardUuids ? { cardUuids: reply.cardUuids } : {},
13676
13784
  ...reply.errorCode ? { errorCode: reply.errorCode } : {}
13677
13785
  }, { turnUuid: offer.turnUuid, signal: stopController.signal });
@@ -13950,6 +14058,7 @@ function wireSessions(listed2, exclude) {
13950
14058
  return listed2.filter((session) => !exclude.includes(session.name)).map((session) => ({
13951
14059
  name: session.name,
13952
14060
  ...session.label !== void 0 ? { label: session.label } : {},
14061
+ ...session.project !== void 0 ? { project: session.project } : {},
13953
14062
  cols: session.cols,
13954
14063
  rows: session.rows,
13955
14064
  ...session.lastOutputAt !== void 0 ? { lastOutputAt: session.lastOutputAt } : {}
@@ -14138,6 +14247,10 @@ var RemoteViewer = class {
14138
14247
  }
14139
14248
  };
14140
14249
 
14250
+ // src/core/term/remote.ts
14251
+ import { existsSync } from "fs";
14252
+ import { rmdir as rmdir2 } from "fs/promises";
14253
+
14141
14254
  // src/core/pc/pcUpgrade.ts
14142
14255
  var STABLE = /^\d+\.\d+\.\d+$/;
14143
14256
  var NEXT = /^\d+\.\d+\.\d+-next\.\d+(\.\d+)*$/;
@@ -14501,6 +14614,30 @@ var CommandRunner = class {
14501
14614
  remote;
14502
14615
  /** 여러 바이트 글자가 poll 경계에서 갈려도 잇는다 — 세션마다(바이트는 그대로, 글자로 바꾸는 곳만 한 곳). */
14503
14616
  decoders = /* @__PURE__ */ new Map();
14617
+ /**
14618
+ * 웹이 폴더를 비운 만들기 — {@link webSessionFolder}(꼬리표가 있으면 프로젝트 아래)를 만든다. requestId 는 서버가 만들기마다 새로
14619
+ * 뽑는 UUID 라 세션마다 새 폴더가 되고, remote_command 로그 줄(같은 requestId)로 어느 만들기의 폴더인지 잇는다.
14620
+ */
14621
+ async sessionFolder(projectUuid, requestId) {
14622
+ const folder = webSessionFolder(this.deps.appHome, projectUuid, requestId);
14623
+ const made = !existsSync(folder);
14624
+ await ensurePrivateDir(folder);
14625
+ return { folder, made };
14626
+ }
14627
+ /** 거절된 만들기 — 방금 만든 세션 폴더를 비어 있을 때만 지운다(rmdir, 재귀 아님). 못 지우면 한 줄 남기고 넘어간다. */
14628
+ async dropSessionFolder(requestId, folder) {
14629
+ try {
14630
+ await rmdir2(folder);
14631
+ } catch (error) {
14632
+ this.deps.log.write({
14633
+ event: "remote_session_folder_kept",
14634
+ requestId,
14635
+ folder,
14636
+ code: error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : "UNKNOWN",
14637
+ message: error instanceof Error ? error.message : String(error)
14638
+ });
14639
+ }
14640
+ }
14504
14641
  async run(commands, ctx) {
14505
14642
  let listChanged = false;
14506
14643
  for (const command of commands) {
@@ -14574,15 +14711,37 @@ var CommandRunner = class {
14574
14711
  this.viewers.get(command.session)?.setSize(applied);
14575
14712
  return true;
14576
14713
  }
14577
- case "create":
14578
- await this.control.request({
14579
- op: "new",
14580
- name: command.name,
14581
- cwd: command.cwd ?? this.deps.home,
14582
- command: command.command === void 0 ? null : shellLineCommand(command.command, this.deps.sessionEnv),
14583
- env: this.deps.sessionEnv
14584
- });
14714
+ case "create": {
14715
+ const project = command.projectUuid;
14716
+ if (project !== void 0 && !isUuid(project)) {
14717
+ throw new TermError("TERM_BAD_REQUEST", `The project "${project}" is not a UUID, so the session was not made.`);
14718
+ }
14719
+ let cwd = command.cwd;
14720
+ let made;
14721
+ if (cwd === void 0) {
14722
+ const fresh = await this.sessionFolder(project, command.requestId);
14723
+ cwd = fresh.folder;
14724
+ if (fresh.made) made = fresh.folder;
14725
+ }
14726
+ let created;
14727
+ try {
14728
+ created = await this.control.request({
14729
+ op: "new",
14730
+ name: command.name,
14731
+ cwd,
14732
+ command: command.command === void 0 ? null : shellLineCommand(command.command, this.deps.sessionEnv),
14733
+ env: this.deps.sessionEnv,
14734
+ ...project !== void 0 ? { project } : {}
14735
+ });
14736
+ } catch (error) {
14737
+ if (made) await this.dropSessionFolder(command.requestId, made);
14738
+ throw error;
14739
+ }
14740
+ if (project !== void 0 && createdProject(created) !== project) {
14741
+ this.deps.log.write({ event: "remote_create_project_dropped", requestId: command.requestId, session: command.name });
14742
+ }
14585
14743
  return true;
14744
+ }
14586
14745
  case "kill":
14587
14746
  await this.control.request({ op: "kill", name: command.session });
14588
14747
  this.decoders.delete(command.session);
@@ -14604,6 +14763,9 @@ function answerSummary(body) {
14604
14763
  ...typeof body.version === "number" ? { version: body.version } : {}
14605
14764
  };
14606
14765
  }
14766
+ function createdProject(data) {
14767
+ return data && typeof data === "object" && "project" in data && typeof data.project === "string" ? data.project : void 0;
14768
+ }
14607
14769
  function serverLimits2(value) {
14608
14770
  if (!value || typeof value !== "object") return void 0;
14609
14771
  const pollHoldSeconds = "pollHoldSeconds" in value ? value.pollHoldSeconds : void 0;
@@ -14639,10 +14801,18 @@ function remoteCommands(answer) {
14639
14801
  }
14640
14802
  case "create": {
14641
14803
  const name = text(c.get("name"));
14804
+ const projectUuid = text(c.get("projectUuid"));
14642
14805
  const cwd = text(c.get("cwd"));
14643
14806
  const command = c.get("command");
14644
14807
  if (!requestId || !name) return [];
14645
- return [{ type: "create", requestId, name, ...cwd ? { cwd } : {}, ...typeof command === "string" ? { command } : {} }];
14808
+ return [{
14809
+ type: "create",
14810
+ requestId,
14811
+ name,
14812
+ ...projectUuid ? { projectUuid } : {},
14813
+ ...cwd ? { cwd } : {},
14814
+ ...typeof command === "string" ? { command } : {}
14815
+ }];
14646
14816
  }
14647
14817
  case "kill":
14648
14818
  return requestId && session ? [{ type: "kill", requestId, session }] : [];
@@ -15495,16 +15665,28 @@ function writeResultFacts(content) {
15495
15665
  }
15496
15666
  return { documents, createdDocuments: documents.filter((uuid) => created.has(uuid)), cards };
15497
15667
  }
15498
- var WriteFactsCollector = class {
15499
- facts = { documents: [], createdDocuments: [], cards: [] };
15500
- add(content) {
15668
+ function seenIdsIn(content) {
15669
+ const out = documentUuidsIn(content);
15670
+ for (const value of jsonObjectsIn(content)) collectHexValues(value, out);
15671
+ return out;
15672
+ }
15673
+ var TurnFactsCollector = class {
15674
+ facts = { documents: [], createdDocuments: [], cards: [], seen: [] };
15675
+ add(content, write) {
15676
+ appendUnique(this.facts.seen, seenIdsIn(content));
15677
+ if (!write) return;
15501
15678
  const next = writeResultFacts(content);
15502
15679
  appendUnique(this.facts.documents, next.documents);
15503
15680
  appendUnique(this.facts.createdDocuments, next.createdDocuments);
15504
15681
  appendUnique(this.facts.cards, next.cards);
15505
15682
  }
15506
15683
  snapshot() {
15507
- return { documents: [...this.facts.documents], createdDocuments: [...this.facts.createdDocuments], cards: [...this.facts.cards] };
15684
+ return {
15685
+ documents: [...this.facts.documents],
15686
+ createdDocuments: [...this.facts.createdDocuments],
15687
+ cards: [...this.facts.cards],
15688
+ seen: [...this.facts.seen]
15689
+ };
15508
15690
  }
15509
15691
  };
15510
15692
  function writeToolNames(tools) {
@@ -15540,6 +15722,15 @@ function collectCards(value, out) {
15540
15722
  }
15541
15723
  }
15542
15724
  }
15725
+ function collectHexValues(value, out) {
15726
+ if (typeof value === "string") {
15727
+ if (HEX32.test(value) && !out.includes(value)) out.push(value);
15728
+ } else if (Array.isArray(value)) {
15729
+ for (const item of value) collectHexValues(item, out);
15730
+ } else if (value && typeof value === "object") {
15731
+ for (const child of Object.values(value)) collectHexValues(child, out);
15732
+ }
15733
+ }
15543
15734
  function appendUnique(target, items) {
15544
15735
  for (const item of items) {
15545
15736
  if (!target.includes(item)) target.push(item);
@@ -15565,11 +15756,11 @@ function claudeCodeAdapter(deps) {
15565
15756
  }
15566
15757
  return claudeAuthFromJson(run.stdout, run.code, run.stderrTail, hasApiKeyVariable(deps.env));
15567
15758
  },
15568
- open: ({ conversationUuid, resumeRef, textMaxCharacters, agentName }) => new ClaudeCodeSession(
15759
+ open: ({ conversationUuid, resumeRef, textMaxCharacters, documentsMax, agentName }) => new ClaudeCodeSession(
15569
15760
  conversationUuid,
15570
15761
  resumeRef,
15571
15762
  agentName,
15572
- deps.args({ textMaxCharacters, resumeSessionId: resumeRef, agentName }),
15763
+ deps.args({ textMaxCharacters, documentsMax, resumeSessionId: resumeRef, agentName }),
15573
15764
  deps
15574
15765
  )
15575
15766
  };
@@ -15628,7 +15819,7 @@ var ClaudeCodeSession = class {
15628
15819
  const exit = this.child.exit;
15629
15820
  if (exit) return { kind: "exited", ...exit };
15630
15821
  const outcome = new Promise((resolve4) => {
15631
- this.pending = { resolve: resolve4, facts: new WriteFactsCollector() };
15822
+ this.pending = { resolve: resolve4, facts: new TurnFactsCollector() };
15632
15823
  });
15633
15824
  this.child.writeLine({ type: "user", message: { role: "user", content: text2 } });
15634
15825
  try {
@@ -15686,10 +15877,10 @@ var ClaudeCodeSession = class {
15686
15877
  }
15687
15878
  if (event.type === "user" && Array.isArray(content) && this.pending) {
15688
15879
  for (const part of content) {
15689
- if (part.type !== "tool_result" || typeof part.tool_use_id !== "string") continue;
15880
+ if (part.type !== "tool_result" || typeof part.tool_use_id !== "string" || part.is_error === true) continue;
15690
15881
  const name = this.toolNames.get(part.tool_use_id);
15691
- if (!name?.startsWith(AINECTO_TOOL_PREFIX) || !this.deps.writeTools.has(name.slice(AINECTO_TOOL_PREFIX.length))) continue;
15692
- this.pending.facts.add(part.content);
15882
+ if (!name?.startsWith(AINECTO_TOOL_PREFIX)) continue;
15883
+ this.pending.facts.add(part.content, this.deps.writeTools.has(name.slice(AINECTO_TOOL_PREFIX.length)));
15693
15884
  }
15694
15885
  return;
15695
15886
  }
@@ -15697,7 +15888,7 @@ var ClaudeCodeSession = class {
15697
15888
  if (typeof event.session_id === "string") this.sessionRef = event.session_id;
15698
15889
  this.finish({
15699
15890
  kind: "result",
15700
- facts: this.pending?.facts.snapshot() ?? { documents: [], createdDocuments: [], cards: [] },
15891
+ facts: this.pending?.facts.snapshot() ?? { documents: [], createdDocuments: [], cards: [], seen: [] },
15701
15892
  result: {
15702
15893
  subtype: typeof event.subtype === "string" ? event.subtype : void 0,
15703
15894
  isError: event.is_error === true,
@@ -15825,7 +16016,7 @@ function codexAdapter(deps) {
15825
16016
  await server.child.stop();
15826
16017
  }
15827
16018
  },
15828
- open: ({ conversationUuid, resumeRef, textMaxCharacters, agentName }) => new CodexSession(conversationUuid, resumeRef, textMaxCharacters, agentName, deps)
16019
+ open: ({ conversationUuid, resumeRef, textMaxCharacters, documentsMax, agentName }) => new CodexSession(conversationUuid, resumeRef, agentReplySchema(textMaxCharacters, documentsMax), agentName, deps)
15829
16020
  };
15830
16021
  }
15831
16022
  var CodexRpc = class {
@@ -15925,9 +16116,9 @@ function startAppServer(deps, args, hooks) {
15925
16116
  return { child, rpc };
15926
16117
  }
15927
16118
  var CodexSession = class {
15928
- constructor(conversationUuid, resumeRef, textMaxCharacters, agentName, deps) {
16119
+ constructor(conversationUuid, resumeRef, replySchema, agentName, deps) {
15929
16120
  this.conversationUuid = conversationUuid;
15930
- this.textMaxCharacters = textMaxCharacters;
16121
+ this.replySchema = replySchema;
15931
16122
  this.agentName = agentName;
15932
16123
  this.deps = deps;
15933
16124
  this.resumed = resumeRef !== void 0;
@@ -15941,7 +16132,7 @@ var CodexSession = class {
15941
16132
  this.started = this.start(resumeRef).then(() => void 0, toError);
15942
16133
  }
15943
16134
  conversationUuid;
15944
- textMaxCharacters;
16135
+ replySchema;
15945
16136
  agentName;
15946
16137
  deps;
15947
16138
  agent = "codex";
@@ -15976,7 +16167,7 @@ var CodexSession = class {
15976
16167
  const exit = this.child.exit;
15977
16168
  if (exit || !this.sessionRef) return { kind: "exited", code: exit?.code ?? null, signal: exit?.signal ?? null, stderrTail: exit?.stderrTail ?? "" };
15978
16169
  const turn = { resolve: () => {
15979
- }, facts: new WriteFactsCollector() };
16170
+ }, facts: new TurnFactsCollector() };
15980
16171
  const outcome = new Promise((resolve4) => {
15981
16172
  turn.resolve = resolve4;
15982
16173
  });
@@ -15984,7 +16175,7 @@ var CodexSession = class {
15984
16175
  try {
15985
16176
  const started = await this.rpc.request(
15986
16177
  "turn/start",
15987
- codexTurnStartParams(this.sessionRef, text2, agentReplySchema(this.textMaxCharacters))
16178
+ codexTurnStartParams(this.sessionRef, text2, this.replySchema)
15988
16179
  );
15989
16180
  const id = started.turn?.id;
15990
16181
  if (typeof id === "string") {
@@ -16079,8 +16270,8 @@ var CodexSession = class {
16079
16270
  const item = params.item && typeof params.item === "object" ? params.item : {};
16080
16271
  if (item.type === "agentMessage" && typeof item.text === "string") {
16081
16272
  turn.lastMessage = item.text;
16082
- } else if (item.type === "mcpToolCall" && item.server === AINECTO_MCP_SERVER && typeof item.tool === "string" && this.deps.writeTools.has(item.tool)) {
16083
- turn.facts.add(item.result?.content);
16273
+ } else if (item.type === "mcpToolCall" && item.server === AINECTO_MCP_SERVER && typeof item.tool === "string" && item.status !== "failed") {
16274
+ turn.facts.add(item.result?.content, this.deps.writeTools.has(item.tool));
16084
16275
  }
16085
16276
  }
16086
16277
  };
@@ -16265,7 +16456,7 @@ function entries(value) {
16265
16456
  }
16266
16457
 
16267
16458
  // src/adapters/cli/pcRemote.ts
16268
- import { homedir as homedir5, hostname as hostname2 } from "os";
16459
+ import { hostname as hostname2 } from "os";
16269
16460
  async function runPcParts(agent, remote, signal) {
16270
16461
  const stop = new AbortController();
16271
16462
  const onStop = () => stop.abort();
@@ -16312,7 +16503,7 @@ async function pcRemoteSetup(input) {
16312
16503
  pcId: settings.pcId,
16313
16504
  hostName,
16314
16505
  remoteEnabled: userId !== void 0 && settings.accounts[accountKey(input.endpoint, userId)]?.remoteTerminal === true,
16315
- home: input.home ?? homedir5(),
16506
+ appHome: input.appHome ?? appHome(),
16316
16507
  env: input.env ?? stringEnv()
16317
16508
  };
16318
16509
  }
@@ -16339,7 +16530,7 @@ async function runPcRemote(setup, signal, onAnswer) {
16339
16530
  remoteEnabled: setup.remoteEnabled,
16340
16531
  exclude: [PC_SESSION_NAME],
16341
16532
  sessionEnv: setup.env,
16342
- home: setup.home,
16533
+ appHome: setup.appHome,
16343
16534
  signal,
16344
16535
  print: (line) => setup.io.stderr.write(`${line}
16345
16536
  `),
@@ -16393,7 +16584,7 @@ async function executeAgentServe(input) {
16393
16584
  const bridge = (agentName) => ainectoBridge(process.execPath, cliScript, input.endpoint, agentName);
16394
16585
  const shared = { spawnImpl: spawnAgent, cwd: paths.work, env: agentEnv(process.env), log, writeTools };
16395
16586
  const all = [
16396
- claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, resumeSessionId, agentName }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters), mcpConfig: claudeMcpConfig(bridge(agentName)), resumeSessionId }) }),
16587
+ claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, documentsMax, resumeSessionId, agentName }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters, documentsMax), mcpConfig: claudeMcpConfig(bridge(agentName)), resumeSessionId }) }),
16397
16588
  codexAdapter({ ...shared, appServerArgs: (agentName) => codexAppServerArgs(bridge(agentName), writeTools), clientVersion: CLI_VERSION })
16398
16589
  ];
16399
16590
  const checks = await checkAgents(all, log);
@@ -16474,7 +16665,7 @@ async function executeAgentServe(input) {
16474
16665
  }
16475
16666
 
16476
16667
  // src/adapters/cli/ainectoCli.ts
16477
- import { homedir as homedir6, hostname as hostname4, tmpdir } from "os";
16668
+ import { homedir as homedir5, hostname as hostname4, tmpdir } from "os";
16478
16669
  async function runAinectoCli(argv, io) {
16479
16670
  let parsed = { json: argv.includes("--json"), help: false, version: false, positionals: [] };
16480
16671
  try {
@@ -16562,8 +16753,8 @@ async function runAinectoCli(argv, io) {
16562
16753
  auth,
16563
16754
  client: client2,
16564
16755
  // ★외부 CLI 는 홈 폴더에서 돈다 — 지금 저장소의 local·project 범위 항목이 사용자 범위 판정에 끼지 않게.
16565
- runner: systemCommandRunner({ cwd: homedir6() }),
16566
- home: homedir6(),
16756
+ runner: systemCommandRunner({ cwd: homedir5() }),
16757
+ home: homedir5(),
16567
16758
  json: parsed.json,
16568
16759
  io
16569
16760
  });
@@ -16577,9 +16768,9 @@ async function runAinectoCli(argv, io) {
16577
16768
  tokenStore,
16578
16769
  auth,
16579
16770
  client: client2,
16580
- runner: systemCommandRunner({ cwd: homedir6() }),
16771
+ runner: systemCommandRunner({ cwd: homedir5() }),
16581
16772
  hereRunner: systemCommandRunner({ cwd: process.cwd() }),
16582
- home: homedir6(),
16773
+ home: homedir5(),
16583
16774
  cwd: process.cwd(),
16584
16775
  envVars: process.env
16585
16776
  };
@@ -16669,7 +16860,7 @@ async function runAinectoCli(argv, io) {
16669
16860
  },
16670
16861
  makeTempDir: () => mkdtemp(join10(tmpdir(), "ainecto-upgrade-")),
16671
16862
  removeDir: (path) => rm3(path, { recursive: true, force: true }),
16672
- home: homedir6(),
16863
+ home: homedir5(),
16673
16864
  log: openAgentLog(swapPaths)
16674
16865
  });
16675
16866
  }