@yukino.js/yukino 0.0.11 → 0.0.13-dev

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.
Files changed (53) hide show
  1. package/README.md +111 -68
  2. package/dist/a2a-DG2JNM3U.js +14 -0
  3. package/dist/acp-DCZDS6FQ.js +14 -0
  4. package/dist/anthropic-5BTWVZVT.js +4 -0
  5. package/dist/chunk-4CLD7LEU.js +5 -0
  6. package/dist/{chunk-QMHSZVNF.js → chunk-5DK2M7VI.js} +1 -1
  7. package/dist/chunk-5URXBVET.js +4 -0
  8. package/dist/{chunk-3VTVI62N.js → chunk-AZQD75PX.js} +1 -1
  9. package/dist/{chunk-WH5FUZXY.js → chunk-BDLFNDC4.js} +3 -3
  10. package/dist/{chunk-TPEUG7AU.js → chunk-COHBT6M7.js} +161 -155
  11. package/dist/chunk-CW5XFH7H.js +59 -0
  12. package/dist/{chunk-YWTRNPNR.js → chunk-IWMCIYOG.js} +21 -21
  13. package/dist/chunk-OI2W6R6H.js +28 -0
  14. package/dist/chunk-SZXXASVH.js +4 -0
  15. package/dist/chunk-UGX62ZSO.js +4 -0
  16. package/dist/chunk-W4GMCNWF.js +65 -0
  17. package/dist/lib/{anthropic-7HQY42TP.js → anthropic-AVZIC22O.js} +5 -5
  18. package/dist/lib/bwrap-JS5GRKWY.js +7 -0
  19. package/dist/lib/{chunk-QQ2V5EX3.js → chunk-EGJKLA2W.js} +3 -3
  20. package/dist/lib/{chunk-AUU4RKMV.js → chunk-GVI5R2DA.js} +47 -29
  21. package/dist/lib/{chunk-XDGZMZ2B.js → chunk-LSI3T24Q.js} +2 -2
  22. package/dist/lib/{chunk-EATSQNOB.js → chunk-O2H6VKKR.js} +3 -3
  23. package/dist/lib/{chunk-55LKYMVV.js → chunk-OFDOP6I2.js} +2 -2
  24. package/dist/lib/{chunk-JXZ5KIUV.js → chunk-PCZ63WQL.js} +1 -1
  25. package/dist/lib/{chunk-Q6B6TAR3.js → chunk-QJ32WYQY.js} +120 -152
  26. package/dist/lib/{chunk-VXHBKGZW.js → chunk-TUNZLQLO.js} +12 -13
  27. package/dist/lib/{chunk-OCGX3ISG.js → chunk-XH7D5FLE.js} +4 -4
  28. package/dist/lib/{chunk-KC54MV5H.js → chunk-XLRV26YW.js} +1 -1
  29. package/dist/lib/index.d.ts +380 -351
  30. package/dist/lib/index.js +925 -638
  31. package/dist/lib/{openai-Z7PCXN2X.js → openai-54IQOU6Y.js} +4 -4
  32. package/dist/lib/{providers-GOU5DD3X.js → providers-MOCB6Y5L.js} +3 -3
  33. package/dist/lib/seatbelt-LDM6UB6N.js +7 -0
  34. package/dist/lib/{tool-filter-GVVYY5QO.js → tool-filter-5Z6UTRRR.js} +4 -4
  35. package/dist/main-IA22XMQR.js +494 -0
  36. package/dist/main.js +2 -487
  37. package/dist/{openai-WNPMC64P.js → openai-I2TTMBWK.js} +1 -1
  38. package/dist/providers-DXQRJUIY.js +4 -0
  39. package/dist/server-QS7CX37F.js +4 -0
  40. package/dist/tool-filter-KDQMXIDC.js +4 -0
  41. package/package.json +2 -2
  42. package/dist/a2a-WKGEGTP6.js +0 -14
  43. package/dist/acp-W2I7T2NT.js +0 -14
  44. package/dist/anthropic-CQUMQFUK.js +0 -4
  45. package/dist/chunk-CH7VZVG4.js +0 -4
  46. package/dist/chunk-F6WFTAOT.js +0 -59
  47. package/dist/chunk-R567WVDL.js +0 -90
  48. package/dist/chunk-ZPL2YHQU.js +0 -5
  49. package/dist/lib/bwrap-V6MFP7PT.js +0 -7
  50. package/dist/lib/seatbelt-2OE46ZE7.js +0 -7
  51. package/dist/providers-CMCKMYGG.js +0 -4
  52. package/dist/server-OQ5XVSZY.js +0 -4
  53. package/dist/tool-filter-BTQ7WTHR.js +0 -4
package/dist/lib/index.js CHANGED
@@ -3,21 +3,21 @@ import {
3
3
  providers_exports,
4
4
  version,
5
5
  version_exports
6
- } from "./chunk-QQ2V5EX3.js";
6
+ } from "./chunk-EGJKLA2W.js";
7
7
  import {
8
8
  bwrap_exports
9
- } from "./chunk-KC54MV5H.js";
9
+ } from "./chunk-XLRV26YW.js";
10
10
  import {
11
11
  seatbelt_exports
12
- } from "./chunk-JXZ5KIUV.js";
12
+ } from "./chunk-PCZ63WQL.js";
13
13
  import {
14
14
  anthropic_exports,
15
15
  decideAndApply,
16
16
  strategy_exports
17
- } from "./chunk-OCGX3ISG.js";
17
+ } from "./chunk-XH7D5FLE.js";
18
18
  import {
19
19
  openai_exports
20
- } from "./chunk-EATSQNOB.js";
20
+ } from "./chunk-O2H6VKKR.js";
21
21
  import {
22
22
  ContextTooLongError,
23
23
  DEFAULT_CONTEXT_WINDOW,
@@ -44,7 +44,7 @@ import {
44
44
  persistThinkingLevel,
45
45
  resolveDefaultProvider,
46
46
  withProjectMcpServers
47
- } from "./chunk-VXHBKGZW.js";
47
+ } from "./chunk-TUNZLQLO.js";
48
48
  import {
49
49
  AgentTool,
50
50
  BUILTIN_AGENTS,
@@ -126,7 +126,7 @@ import {
126
126
  withFileSyncLock,
127
127
  worktree_exports,
128
128
  writeTeamFile
129
- } from "./chunk-Q6B6TAR3.js";
129
+ } from "./chunk-QJ32WYQY.js";
130
130
  import {
131
131
  MCPToolWrapper,
132
132
  MCP_TOOL_PREFIX,
@@ -136,7 +136,7 @@ import {
136
136
  normalizeToolResultContentBlock,
137
137
  tool_wrapper_exports,
138
138
  types_exports
139
- } from "./chunk-XDGZMZ2B.js";
139
+ } from "./chunk-LSI3T24Q.js";
140
140
  import {
141
141
  asErrorString,
142
142
  asRecord,
@@ -146,23 +146,28 @@ import {
146
146
  createChildLogger,
147
147
  fetchPublicHttpUrl,
148
148
  generateSlug,
149
+ getSessionsDir,
150
+ getYukinoDir,
149
151
  initLogger,
150
152
  intArg,
151
153
  isObject,
152
154
  isRecord,
153
155
  logger,
154
156
  logger_exports,
157
+ projectPath,
155
158
  safeJSONParse,
156
159
  sanitizeNameSegment,
160
+ sessionPath,
157
161
  strArg,
158
- utils_exports
159
- } from "./chunk-AUU4RKMV.js";
162
+ utils_exports,
163
+ yukinoPath
164
+ } from "./chunk-GVI5R2DA.js";
160
165
  import {
161
166
  __export,
162
167
  canonicalPath,
163
168
  isPathWithin,
164
169
  resolveToolPath
165
- } from "./chunk-55LKYMVV.js";
170
+ } from "./chunk-OFDOP6I2.js";
166
171
 
167
172
  // src/a2a/index.ts
168
173
  var a2a_exports = {};
@@ -438,7 +443,7 @@ __export(server_exports, {
438
443
  });
439
444
  import { readFileSync as readFileSync12, existsSync as existsSync14, statSync as statSync10 } from "fs";
440
445
  import { createServer } from "http";
441
- import { join as join21, extname as extname4, normalize } from "path";
446
+ import { join as join20, extname as extname4, normalize } from "path";
442
447
  import { cwd } from "process";
443
448
  import express from "express";
444
449
  import { WebSocketServer, WebSocket } from "ws";
@@ -702,8 +707,8 @@ function getBackupName(filePath, snapshotIndex) {
702
707
  function getBaselineBackupName(filePath) {
703
708
  return `${filePathHash(filePath)}@baseline`;
704
709
  }
705
- function fileHistoryDir(baseDir, sessionId) {
706
- return join(baseDir, ".yukino", "file-history", sessionId);
710
+ function fileHistoryDir(sessionId) {
711
+ return sessionPath(sessionId, "file-history");
707
712
  }
708
713
  var FileHistory = class {
709
714
  sessionDir;
@@ -715,8 +720,8 @@ var FileHistory = class {
715
720
  snapshots = [];
716
721
  /** Monotonic backup-name counter; array positions recycle, this must not. */
717
722
  nextSnapshotSeq = 0;
718
- constructor(baseDir, sessionID) {
719
- this.sessionDir = fileHistoryDir(baseDir, sessionID);
723
+ constructor(sessionID) {
724
+ this.sessionDir = fileHistoryDir(sessionID);
720
725
  this.statePath = join(this.sessionDir, "snapshots.json");
721
726
  mkdirSync(this.sessionDir, { recursive: true });
722
727
  withFileSyncLock(this.statePath, () => {
@@ -1192,24 +1197,24 @@ var CompactBoundaryPayloadSchema = z3.object({
1192
1197
  keep: z3.array(KeptMessageSchema)
1193
1198
  });
1194
1199
  var log2 = createChildLogger({ module: "session" });
1195
- function sessionsDir(workDir) {
1196
- return join2(workDir, ".yukino", "sessions");
1200
+ function getSessionArtifactsDir(sessionId) {
1201
+ return sessionPath(sessionId);
1197
1202
  }
1198
- function getSessionArtifactsDir(workDir, sessionId) {
1199
- return join2(sessionsDir(workDir), sessionId);
1200
- }
1201
- function getSessionFilePath(workDir, sessionId) {
1202
- return join2(sessionsDir(workDir), sessionId + ".jsonl");
1203
+ function getSessionFilePath(cwd2, sessionId) {
1204
+ if (!/^[A-Za-z0-9_-]+$/u.test(sessionId)) {
1205
+ throw new Error("Invalid session ID");
1206
+ }
1207
+ return join2(getSessionsDir(cwd2), sessionId + ".jsonl");
1203
1208
  }
1204
1209
  function newSessionId() {
1205
1210
  const ts = Date.now().toString(36);
1206
1211
  const rand = randomBytes(4).toString("hex");
1207
1212
  return `${ts}-${rand}`;
1208
1213
  }
1209
- function saveMessage(workDir, sessionId, msg) {
1210
- const dir = sessionsDir(workDir);
1214
+ function saveMessage(cwd2, sessionId, msg) {
1215
+ const dir = getSessionsDir(cwd2);
1211
1216
  mkdirSync2(dir, { recursive: true });
1212
- const filePath = join2(dir, `${sessionId}.jsonl`);
1217
+ const filePath = getSessionFilePath(cwd2, sessionId);
1213
1218
  const line = JSON.stringify(msg) + "\n";
1214
1219
  withFileSyncLock(filePath, () => {
1215
1220
  writeFileSync2(filePath, line, {
@@ -1221,8 +1226,8 @@ function saveMessage(workDir, sessionId, msg) {
1221
1226
  });
1222
1227
  });
1223
1228
  }
1224
- function saveCompactBoundary(workDir, sessionId, payload) {
1225
- saveMessage(workDir, sessionId, {
1229
+ function saveCompactBoundary(cwd2, sessionId, payload) {
1230
+ saveMessage(cwd2, sessionId, {
1226
1231
  role: "system",
1227
1232
  content: JSON.stringify(payload),
1228
1233
  timestamp: Math.floor(Date.now() / 1e3),
@@ -1270,8 +1275,8 @@ function truncateSessionLines(filePath, keepLines) {
1270
1275
  }
1271
1276
  });
1272
1277
  }
1273
- function loadSession(workDir, sessionId) {
1274
- const filePath = join2(sessionsDir(workDir), `${sessionId}.jsonl`);
1278
+ function loadSession(cwd2, sessionId) {
1279
+ const filePath = getSessionFilePath(cwd2, sessionId);
1275
1280
  if (!existsSync2(dirname2(filePath))) {
1276
1281
  return [];
1277
1282
  }
@@ -1310,8 +1315,8 @@ function loadSession(workDir, sessionId) {
1310
1315
  return out;
1311
1316
  });
1312
1317
  }
1313
- function touchSession(workDir, sessionId) {
1314
- const filePath = join2(sessionsDir(workDir), `${sessionId}.jsonl`);
1318
+ function touchSession(cwd2, sessionId) {
1319
+ const filePath = getSessionFilePath(cwd2, sessionId);
1315
1320
  if (!existsSync2(dirname2(filePath))) {
1316
1321
  return;
1317
1322
  }
@@ -1436,11 +1441,11 @@ function toRestored(m, includeExcludedUserBash = false) {
1436
1441
  };
1437
1442
  }
1438
1443
  var sweptSessionDirs = /* @__PURE__ */ new Set();
1439
- function listSessions(workDir) {
1440
- const dir = sessionsDir(workDir);
1444
+ function listSessions(cwd2) {
1445
+ const dir = getSessionsDir(cwd2);
1441
1446
  if (!sweptSessionDirs.has(dir)) {
1442
1447
  sweptSessionDirs.add(dir);
1443
- cleanExpiredSessions(workDir);
1448
+ cleanExpiredSessions(cwd2);
1444
1449
  }
1445
1450
  if (!existsSync2(dir)) {
1446
1451
  return [];
@@ -1496,8 +1501,8 @@ function listSessions(workDir) {
1496
1501
  sessions.sort((a, b) => b.modTime.getTime() - a.modTime.getTime());
1497
1502
  return sessions;
1498
1503
  }
1499
- function cleanExpiredSessions(workDir) {
1500
- const dir = sessionsDir(workDir);
1504
+ function cleanExpiredSessions(cwd2) {
1505
+ const dir = getSessionsDir(cwd2);
1501
1506
  if (!existsSync2(dir)) {
1502
1507
  return 0;
1503
1508
  }
@@ -1531,14 +1536,7 @@ function cleanExpiredSessions(workDir) {
1531
1536
  unlinkSync2(filePath);
1532
1537
  const id = file.replace(".jsonl", "");
1533
1538
  try {
1534
- rmSync(getSessionArtifactsDir(workDir, id), {
1535
- recursive: true,
1536
- force: true
1537
- });
1538
- } catch {
1539
- }
1540
- try {
1541
- rmSync(fileHistoryDir(workDir, id), {
1539
+ rmSync(getSessionArtifactsDir(id), {
1542
1540
  recursive: true,
1543
1541
  force: true
1544
1542
  });
@@ -1575,10 +1573,10 @@ var GoalSchema = z4.object({
1575
1573
  lastBlockedTurn: z4.number().int().nullable()
1576
1574
  });
1577
1575
  var GoalManager = class {
1578
- constructor(workDir, sessionId) {
1579
- this.workDir = workDir;
1576
+ constructor(cwd2, sessionId) {
1577
+ this.cwd = cwd2;
1580
1578
  this.sessionId = sessionId;
1581
- for (const record2 of loadSession(workDir, sessionId)) {
1579
+ for (const record2 of loadSession(cwd2, sessionId)) {
1582
1580
  if (record2.type !== GOAL_RECORD || typeof record2.content !== "string") {
1583
1581
  continue;
1584
1582
  }
@@ -1596,7 +1594,7 @@ var GoalManager = class {
1596
1594
  }
1597
1595
  }
1598
1596
  }
1599
- workDir;
1597
+ cwd;
1600
1598
  sessionId;
1601
1599
  state = null;
1602
1600
  activeSince = null;
@@ -1614,7 +1612,7 @@ var GoalManager = class {
1614
1612
  if (this.activeSince !== null) {
1615
1613
  this.activeSince = Date.now();
1616
1614
  }
1617
- saveMessage(this.workDir, this.sessionId, {
1615
+ saveMessage(this.cwd, this.sessionId, {
1618
1616
  role: "system",
1619
1617
  type: GOAL_RECORD,
1620
1618
  content: JSON.stringify(this.state),
@@ -1898,13 +1896,13 @@ function restoreRemoteSession(state, sessionId, saved) {
1898
1896
  state.conv.appendMessages(replay);
1899
1897
  state.sessionId = sessionId;
1900
1898
  state.planFilePath = "";
1901
- state.goalManager = new GoalManager(state.workDir, sessionId);
1902
- state.fileHistory = new FileHistory(state.workDir, sessionId);
1899
+ state.goalManager = new GoalManager(state.cwd, sessionId);
1900
+ state.fileHistory = new FileHistory(sessionId);
1903
1901
  state.fileStateCache = new FileStateCache();
1904
1902
  state.recoveryState = new RecoveryState();
1905
1903
  state.activeSkills.clear();
1906
1904
  state.toolFilter = null;
1907
- state.taskList.useStore(new TaskStore(state.workDir, sessionId));
1905
+ state.taskList.useStore(new TaskStore(sessionId));
1908
1906
  return replay;
1909
1907
  }
1910
1908
 
@@ -1989,7 +1987,7 @@ async function initializeTelemetry() {
1989
1987
  if (!shouldInitialize()) {
1990
1988
  return;
1991
1989
  }
1992
- initialization = import("./providers-GOU5DD3X.js").then(async ({ createTelemetryRuntime }) => {
1990
+ initialization = import("./providers-MOCB6Y5L.js").then(async ({ createTelemetryRuntime }) => {
1993
1991
  runtime = await createTelemetryRuntime();
1994
1992
  runtime.setMode(mode);
1995
1993
  process.once("beforeExit", () => {
@@ -2004,8 +2002,8 @@ function setTelemetryMode(nextMode) {
2004
2002
  mode = nextMode;
2005
2003
  runtime.setMode(nextMode);
2006
2004
  }
2007
- function captureTelemetryError(error, context) {
2008
- runtime.captureError(error, context);
2005
+ function captureTelemetryError(error, context2) {
2006
+ runtime.captureError(error, context2);
2009
2007
  }
2010
2008
  async function flushTelemetry() {
2011
2009
  await initialization;
@@ -2444,7 +2442,7 @@ function isPngBuffer(bytes) {
2444
2442
  function clipboardImageFileName(bytes) {
2445
2443
  return `${createHash3("sha256").update(bytes).digest("hex").slice(0, 16)}.png`;
2446
2444
  }
2447
- async function storeClipboardImage(workDir, sessionId, bytes) {
2445
+ async function storeClipboardImage(sessionId, bytes) {
2448
2446
  if (!isPngBuffer(bytes)) {
2449
2447
  throw new Error("Clipboard data is not a PNG image.");
2450
2448
  }
@@ -2453,7 +2451,7 @@ async function storeClipboardImage(workDir, sessionId, bytes) {
2453
2451
  `Clipboard image is too large (${String(bytes.length)} bytes, limit ${String(MAX_CLIPBOARD_IMAGE_BYTES)}).`
2454
2452
  );
2455
2453
  }
2456
- const dir = fileHistoryDir(workDir, sessionId);
2454
+ const dir = fileHistoryDir(sessionId);
2457
2455
  await mkdir(dir, { recursive: true });
2458
2456
  const path = join3(dir, clipboardImageFileName(bytes));
2459
2457
  await writeFile(path, bytes);
@@ -2627,8 +2625,8 @@ async function readWindowsClipboard(tempPath) {
2627
2625
  }
2628
2626
  return readFile(tempPath);
2629
2627
  }
2630
- async function saveClipboardImage(workDir, sessionId) {
2631
- const dir = fileHistoryDir(workDir, sessionId);
2628
+ async function saveClipboardImage(sessionId) {
2629
+ const dir = fileHistoryDir(sessionId);
2632
2630
  const tempPath = join3(dir, `.clipboard-${String(process.pid)}.tmp`);
2633
2631
  try {
2634
2632
  let bytes;
@@ -2655,7 +2653,7 @@ async function saveClipboardImage(workDir, sessionId) {
2655
2653
  }
2656
2654
  return {
2657
2655
  ok: true,
2658
- value: await storeClipboardImage(workDir, sessionId, bytes)
2656
+ value: await storeClipboardImage(sessionId, bytes)
2659
2657
  };
2660
2658
  } catch (err) {
2661
2659
  return {
@@ -2847,7 +2845,7 @@ function appendWithinLimit(appendix, block) {
2847
2845
  }
2848
2846
  return { appendix: appendix + block, appended: true };
2849
2847
  }
2850
- function expandAtRefs(text, workDir) {
2848
+ function expandAtRefs(text, cwd2) {
2851
2849
  const refs = collectAtRefs(text);
2852
2850
  if (refs.length === 0) {
2853
2851
  return text;
@@ -2860,7 +2858,7 @@ function expandAtRefs(text, workDir) {
2860
2858
  }
2861
2859
  seen.add(ref);
2862
2860
  const { path: refPath, lineStart, lineEnd } = parseRef(ref);
2863
- const p = isAbsolute(refPath) ? refPath : join4(workDir, refPath);
2861
+ const p = isAbsolute(refPath) ? refPath : join4(cwd2, refPath);
2864
2862
  try {
2865
2863
  const st = statSync3(p);
2866
2864
  if (!st.isFile()) {
@@ -2900,7 +2898,7 @@ ${readFileSync3(p, "utf-8")}
2900
2898
  }
2901
2899
  return appendix ? text + appendix : text;
2902
2900
  }
2903
- async function expandAtRefsWithImages(text, workDir) {
2901
+ async function expandAtRefsWithImages(text, cwd2) {
2904
2902
  const refs = collectAtRefs(text);
2905
2903
  if (refs.length === 0) {
2906
2904
  return text;
@@ -2914,7 +2912,7 @@ async function expandAtRefsWithImages(text, workDir) {
2914
2912
  }
2915
2913
  seen.add(ref);
2916
2914
  const { path: refPath, lineStart, lineEnd } = parseRef(ref);
2917
- const p = isAbsolute(refPath) ? refPath : join4(workDir, refPath);
2915
+ const p = isAbsolute(refPath) ? refPath : join4(cwd2, refPath);
2918
2916
  try {
2919
2917
  const st = statSync3(p);
2920
2918
  if (!st.isFile()) {
@@ -3678,35 +3676,35 @@ __export(plan_file_exports, {
3678
3676
  import { readFileSync as readFileSync4, writeFileSync as writeFileSync3, mkdirSync as mkdirSync3, existsSync as existsSync3 } from "fs";
3679
3677
  import { isAbsolute as isAbsolute2, join as join5, relative, resolve as resolve2 } from "path";
3680
3678
  var log7 = createChildLogger({ module: "plan-file" });
3681
- function isPlanUnderWorkDir(planPath, workDir) {
3682
- const plansDir = resolve2(workDir, ".yukino", "plans");
3679
+ function isPlanInStorage(planPath) {
3680
+ const plansDir = yukinoPath("plans");
3683
3681
  const rel = relative(plansDir, resolve2(planPath));
3684
3682
  return rel !== "" && !rel.startsWith("..") && !isAbsolute2(rel);
3685
3683
  }
3686
- function getOrCreatePlanPath(workDir, owner) {
3684
+ function getOrCreatePlanPath(owner) {
3687
3685
  if (owner.planFilePath && existsSync3(owner.planFilePath)) {
3688
- if (!isPlanUnderWorkDir(owner.planFilePath, workDir)) {
3686
+ if (!isPlanInStorage(owner.planFilePath)) {
3689
3687
  log7.warn(
3690
- { planPath: owner.planFilePath, workDir },
3691
- "current plan path is not under work dir"
3688
+ { planPath: owner.planFilePath },
3689
+ "current plan path is outside plan storage"
3692
3690
  );
3693
3691
  } else {
3694
3692
  return owner.planFilePath;
3695
3693
  }
3696
3694
  }
3697
- owner.planFilePath = createPlanPath(workDir);
3695
+ owner.planFilePath = createPlanPath();
3698
3696
  return owner.planFilePath;
3699
3697
  }
3700
- function createPlanPath(workDir) {
3701
- const dir = join5(workDir, ".yukino", "plans");
3698
+ function createPlanPath() {
3699
+ const dir = yukinoPath("plans");
3702
3700
  mkdirSync3(dir, { recursive: true });
3703
3701
  const slug = generateSlug();
3704
3702
  const path = join5(dir, `${slug}.md`);
3705
3703
  writeFileSync3(path, "", { encoding: "utf-8", flag: "wx" });
3706
3704
  return path;
3707
3705
  }
3708
- function savePlan(workDir, owner, content) {
3709
- const path = getOrCreatePlanPath(workDir, owner);
3706
+ function savePlan(owner, content) {
3707
+ const path = getOrCreatePlanPath(owner);
3710
3708
  writeFileSync3(path, content, "utf-8");
3711
3709
  }
3712
3710
  function loadPlan(owner) {
@@ -3715,14 +3713,14 @@ function loadPlan(owner) {
3715
3713
  }
3716
3714
  return readFileSync4(owner.planFilePath, "utf-8");
3717
3715
  }
3718
- function planExists(workDir, owner) {
3716
+ function planExists(owner) {
3719
3717
  if (!owner.planFilePath || !existsSync3(owner.planFilePath)) {
3720
3718
  return false;
3721
3719
  }
3722
- if (!isPlanUnderWorkDir(owner.planFilePath, workDir)) {
3720
+ if (!isPlanInStorage(owner.planFilePath)) {
3723
3721
  log7.warn(
3724
- { planPath: owner.planFilePath, workDir },
3725
- "current plan path is not under work dir"
3722
+ { planPath: owner.planFilePath },
3723
+ "current plan path is outside plan storage"
3726
3724
  );
3727
3725
  return false;
3728
3726
  }
@@ -3962,14 +3960,14 @@ import { join as join6, resolve as resolve3, sep } from "path";
3962
3960
  var log8 = createChildLogger({ module: "tool-result" });
3963
3961
  var MESSAGE_AGGREGATE_LIMIT = 2e5;
3964
3962
  var TOOL_RESULT_PREVIEW_CHARS = 2e3;
3965
- function spillDir(workDir, sessionId) {
3963
+ function spillDir(sessionId) {
3966
3964
  if (!sessionId) {
3967
3965
  throw new Error("Tool-result spilling requires a session ID");
3968
3966
  }
3969
- return join6(getSessionArtifactsDir(workDir, sessionId), "tool-results");
3967
+ return join6(getSessionArtifactsDir(sessionId), "tool-results");
3970
3968
  }
3971
- function writeSpill(workDir, sessionId, toolUseId, content) {
3972
- const dir = spillDir(workDir, sessionId);
3969
+ function writeSpill(sessionId, toolUseId, content) {
3970
+ const dir = spillDir(sessionId);
3973
3971
  mkdirSync4(dir, { recursive: true });
3974
3972
  const path = join6(dir, toolUseId + ".txt");
3975
3973
  try {
@@ -4022,7 +4020,7 @@ function buildSpillPreview(content, spillPath) {
4022
4020
  spillPath
4023
4021
  );
4024
4022
  }
4025
- function isSpillReadback(toolName, args, workDir, sessionId) {
4023
+ function isSpillReadback(toolName, args, cwd2, sessionId) {
4026
4024
  if (toolName !== "ReadFile" || !args) {
4027
4025
  return false;
4028
4026
  }
@@ -4033,11 +4031,11 @@ function isSpillReadback(toolName, args, workDir, sessionId) {
4033
4031
  if (!sessionId) {
4034
4032
  return false;
4035
4033
  }
4036
- const target = resolveToolPath(workDir, raw);
4037
- const spill = resolve3(spillDir(workDir, sessionId));
4034
+ const target = resolveToolPath(cwd2, raw);
4035
+ const spill = resolve3(spillDir(sessionId));
4038
4036
  return target === spill || target.startsWith(spill + sep);
4039
4037
  }
4040
- function applyBudget(toolResults, workDir, sessionId, exemptIds) {
4038
+ function applyBudget(toolResults, sessionId, exemptIds) {
4041
4039
  let total = toolResults.reduce(
4042
4040
  (sum, result) => sum + result.content.length,
4043
4041
  0
@@ -4061,7 +4059,7 @@ function applyBudget(toolResults, workDir, sessionId, exemptIds) {
4061
4059
  }
4062
4060
  let spillPath;
4063
4061
  try {
4064
- spillPath = writeSpill(workDir, sessionId, r.toolUseId, content);
4062
+ spillPath = writeSpill(sessionId, r.toolUseId, content);
4065
4063
  } catch {
4066
4064
  continue;
4067
4065
  }
@@ -4070,10 +4068,10 @@ function applyBudget(toolResults, workDir, sessionId, exemptIds) {
4070
4068
  replaceToolResultContent(r, replacement);
4071
4069
  }
4072
4070
  }
4073
- function persistLargeResult(workDir, sessionId, toolUseId, content) {
4071
+ function persistLargeResult(sessionId, toolUseId, content) {
4074
4072
  let path;
4075
4073
  try {
4076
- path = writeSpill(workDir, sessionId, toolUseId, content);
4074
+ path = writeSpill(sessionId, toolUseId, content);
4077
4075
  } catch {
4078
4076
  return content;
4079
4077
  }
@@ -4095,7 +4093,7 @@ var Agent = class {
4095
4093
  registry;
4096
4094
  checker;
4097
4095
  conversation;
4098
- workDir;
4096
+ cwd;
4099
4097
  sessionId;
4100
4098
  sessionFilePath;
4101
4099
  goalManager;
@@ -4132,11 +4130,11 @@ var Agent = class {
4132
4130
  this.registry = config.registry;
4133
4131
  this.checker = config.checker;
4134
4132
  this.conversation = config.conversation;
4135
- this.workDir = config.workDir;
4133
+ this.cwd = config.cwd;
4136
4134
  this.sessionId = config.sessionId ?? "";
4137
- this.goalManager = config.goalManager ?? (config.sessionId ? new GoalManager(config.workDir, config.sessionId) : void 0);
4135
+ this.goalManager = config.goalManager ?? (config.sessionId ? new GoalManager(config.cwd, config.sessionId) : void 0);
4138
4136
  this.shouldContinueGoal = config.shouldContinueGoal;
4139
- this.sessionFilePath = config.sessionId ? getSessionFilePath(config.workDir, config.sessionId) : "";
4137
+ this.sessionFilePath = config.sessionId ? getSessionFilePath(config.cwd, config.sessionId) : "";
4140
4138
  this.hookEngine = config.hookEngine;
4141
4139
  this.fileHistory = config.fileHistory;
4142
4140
  this.fileStateCache = config.fileStateCache;
@@ -4178,7 +4176,7 @@ var Agent = class {
4178
4176
  if (!sessionId) {
4179
4177
  sessionId = newSessionId();
4180
4178
  anonymousArtifactSessions.set(this.conversation, sessionId);
4181
- const artifactsDir = getSessionArtifactsDir(this.workDir, sessionId);
4179
+ const artifactsDir = getSessionArtifactsDir(sessionId);
4182
4180
  registerExitCleanup(() => {
4183
4181
  rmSync2(artifactsDir, { recursive: true, force: true });
4184
4182
  });
@@ -4319,7 +4317,7 @@ No tools are currently callable. Return findings or blockers without issuing too
4319
4317
  );
4320
4318
  }
4321
4319
  if (this.checker.mode === "plan") {
4322
- const planPath = this.checker.planModeLocked ? this.checker.planFilePath || createPlanPath(this.workDir) : getOrCreatePlanPath(this.workDir, this.checker);
4320
+ const planPath = this.checker.planModeLocked ? this.checker.planFilePath || createPlanPath() : getOrCreatePlanPath(this.checker);
4323
4321
  this.checker.planFilePath = planPath;
4324
4322
  this.conversation.addSystemReminder(
4325
4323
  buildPlanModeReminder(planPath, existsSync4(planPath), iteration, {
@@ -4388,7 +4386,7 @@ No deferred tools can currently be discovered and invoked. Do not use earlier de
4388
4386
  );
4389
4387
  if (mc.message) {
4390
4388
  if (mc.boundary && this.sessionId) {
4391
- saveCompactBoundary(this.workDir, this.sessionId, mc.boundary);
4389
+ saveCompactBoundary(this.cwd, this.sessionId, mc.boundary);
4392
4390
  }
4393
4391
  yield {
4394
4392
  type: "compact",
@@ -4519,7 +4517,7 @@ No deferred tools can currently be discovered and invoked. Do not use earlier de
4519
4517
  this.restoreContext();
4520
4518
  if (result.boundary && this.sessionId) {
4521
4519
  saveCompactBoundary(
4522
- this.workDir,
4520
+ this.cwd,
4523
4521
  this.sessionId,
4524
4522
  result.boundary
4525
4523
  );
@@ -4687,7 +4685,7 @@ ${this.goalManager.format()}
4687
4685
  if (isSpillReadback(
4688
4686
  tu.toolName,
4689
4687
  tu.arguments,
4690
- this.workDir,
4688
+ this.cwd,
4691
4689
  toolResultSessionId
4692
4690
  )) {
4693
4691
  exemptIds.add(tu.toolUseId);
@@ -4705,7 +4703,6 @@ ${this.goalManager.format()}
4705
4703
  };
4706
4704
  if (toolResult.content.length > MAX_OUTPUT_CHARS && !exemptIds.has(r.toolId)) {
4707
4705
  const replacement = persistLargeResult(
4708
- this.workDir,
4709
4706
  toolResultSessionId,
4710
4707
  r.toolId,
4711
4708
  toolResult.content
@@ -4718,12 +4715,7 @@ ${this.goalManager.format()}
4718
4715
  toolResults.push(toolResult);
4719
4716
  }
4720
4717
  }
4721
- applyBudget(
4722
- toolResults,
4723
- this.workDir,
4724
- toolResultSessionId,
4725
- exemptIds
4726
- );
4718
+ applyBudget(toolResults, toolResultSessionId, exemptIds);
4727
4719
  const exitPlanSucceeded = toolUses.some((tu) => {
4728
4720
  if (tu.toolName !== "ExitPlanMode") {
4729
4721
  return false;
@@ -4841,7 +4833,7 @@ ${this.goalManager.format()}
4841
4833
  const results = await this.hookEngine.fire(
4842
4834
  event,
4843
4835
  { event, message },
4844
- { workDir: this.workDir, abortSignal: this.abortSignal }
4836
+ { cwd: this.cwd, abortSignal: this.abortSignal }
4845
4837
  );
4846
4838
  for (const r of results) {
4847
4839
  if (r.output) {
@@ -4900,7 +4892,7 @@ ${this.goalManager.format()}
4900
4892
  const executor = new StreamingExecutor(
4901
4893
  this.registry,
4902
4894
  {
4903
- workDir: this.workDir,
4895
+ cwd: this.cwd,
4904
4896
  sessionId: this.sessionId,
4905
4897
  goalManager: this.goalManager,
4906
4898
  taskManager: this.taskManager,
@@ -4985,7 +4977,7 @@ ${this.goalManager.format()}
4985
4977
  const hookResult = await this.hookEngine.firePreToolHooks(
4986
4978
  call.name,
4987
4979
  call.args,
4988
- { workDir: this.workDir, abortSignal: this.abortSignal }
4980
+ { cwd: this.cwd, abortSignal: this.abortSignal }
4989
4981
  );
4990
4982
  if (hookResult.rejected) {
4991
4983
  yield {
@@ -5147,7 +5139,7 @@ ${this.goalManager.format()}
5147
5139
  ),
5148
5140
  message: output
5149
5141
  },
5150
- { workDir: this.workDir, abortSignal: this.abortSignal }
5142
+ { cwd: this.cwd, abortSignal: this.abortSignal }
5151
5143
  );
5152
5144
  for (const hr of hookResults) {
5153
5145
  if (hr.output) {
@@ -5165,7 +5157,7 @@ ${this.goalManager.format()}
5165
5157
  * Skipped when sessionId is empty (one-shot invocations, sub-agents).
5166
5158
  */
5167
5159
  persistLastMessage() {
5168
- if (!this.workDir || !this.sessionId) {
5160
+ if (!this.cwd || !this.sessionId) {
5169
5161
  return;
5170
5162
  }
5171
5163
  const msgs = this.conversation.getMessages();
@@ -5173,7 +5165,7 @@ ${this.goalManager.format()}
5173
5165
  return;
5174
5166
  }
5175
5167
  const last = msgs[msgs.length - 1];
5176
- saveMessage(this.workDir, this.sessionId, {
5168
+ saveMessage(this.cwd, this.sessionId, {
5177
5169
  ...messageToKeptRecord(last),
5178
5170
  timestamp: Math.floor(Date.now() / 1e3)
5179
5171
  });
@@ -5198,11 +5190,11 @@ import os from "os";
5198
5190
  async function createSandbox() {
5199
5191
  const platform2 = os.platform();
5200
5192
  if (platform2 === "darwin") {
5201
- const { SeatbeltSandbox } = await import("./seatbelt-2OE46ZE7.js");
5193
+ const { SeatbeltSandbox } = await import("./seatbelt-LDM6UB6N.js");
5202
5194
  return new SeatbeltSandbox();
5203
5195
  }
5204
5196
  if (platform2 === "linux") {
5205
- const { BwrapSandbox } = await import("./bwrap-V6MFP7PT.js");
5197
+ const { BwrapSandbox } = await import("./bwrap-JS5GRKWY.js");
5206
5198
  return new BwrapSandbox();
5207
5199
  }
5208
5200
  return null;
@@ -5237,13 +5229,13 @@ var BASH_DESCRIPTION = `Execute command in Bash; return stdout and stderr. Prefe
5237
5229
  - Quote paths with spaces. To change directory, use cd "path" && command in the same call. Separate independent commands; chain dependent commands with &&, not ;.
5238
5230
  - Prefer dedicated file/search tools over cat, head, tail, sed, awk, echo, or find. Scope searches to a directory, never the filesystem root. Diagnose failures rather than retrying in sleep loops.
5239
5231
  ${GIT_GUIDANCE}`;
5240
- var BASH_BACKGROUND_DESCRIPTION = `- Set run_in_background to true to run the command in the background. The call returns a task ID immediately and the result arrives later as a task notification; do not poll or sleep waiting for it. Use this for long-running commands you do not need the result of right away. Use TaskStop with the task_id to kill a background command early. A foreground command that exceeds its timeout is moved to the background automatically instead of being killed, unless it is a bare sleep.`;
5232
+ var BASH_BACKGROUND_DESCRIPTION = `- Set run_in_background to true to run the command in the background. The call returns a task ID immediately and the result arrives later as a task notification; do not poll or sleep waiting for it. Use this for long-running commands you do not need the result of right away. Use TaskStop with the task_id to kill a background command early. A foreground command that exceeds its timeout is moved to the background automatically instead of being killed.`;
5241
5233
  var POWERSHELL_DESCRIPTION = `Execute command in PowerShell; return stdout and stderr. Recommended on Windows (powershell.exe); uses pwsh elsewhere.
5242
5234
  - timeout is in seconds: default 120, maximum 600. Each call starts a fresh, independent shell in the Agent's working directory; location, variables, and options do not persist.
5243
5235
  - Quote paths with spaces; use Set-Location -LiteralPath "path" in the same call. Separate independent commands. For dependencies, check $LASTEXITCODE for native commands and use -ErrorAction Stop for cmdlets; ; does not stop on failure. Do not assume PowerShell 7 syntax.
5244
5236
  - Prefer dedicated file/search tools over Get-Content, Select-String, or Write-Output. Scope recursion to a directory, not a drive root. Diagnose failures rather than retrying in Start-Sleep loops.
5245
5237
  ${GIT_GUIDANCE}`;
5246
- var POWERSHELL_BACKGROUND_DESCRIPTION = `- Set run_in_background to true to run the command in the background. The call returns a task ID immediately and the result arrives later as a task notification; do not poll or Start-Sleep waiting for it. Use this for long-running commands you do not need the result of right away. Use TaskStop with the task_id to kill a background command early. A foreground command that exceeds its timeout is moved to the background automatically instead of being killed, unless it is a bare Start-Sleep.`;
5238
+ var POWERSHELL_BACKGROUND_DESCRIPTION = `- Set run_in_background to true to run the command in the background. The call returns a task ID immediately and the result arrives later as a task notification; do not poll or Start-Sleep waiting for it. Use this for long-running commands you do not need the result of right away. Use TaskStop with the task_id to kill a background command early. A foreground command that exceeds its timeout is moved to the background automatically instead of being killed.`;
5247
5239
  var READ_FILE_DESCRIPTION = `Read text with 1-based display line numbers, or images (png, jpg, jpeg, gif, webp) as visual content; not directories.
5248
5240
  - file_path is absolute or relative to the Agent's working directory. offset skips lines (0-based, default 0); limit defaults to 2000 lines, with a 50KB text output cap. Displayed line 101 starts at offset=100. Follow continuation/readback instructions for partial output.
5249
5241
  - Images ignore offset/limit. A successful read refreshes the file-state cache used by EditFile/WriteFile; re-read after an external-change error.`;
@@ -5285,7 +5277,6 @@ __export(shell_background_exports, {
5285
5277
  discardFd: () => discardFd,
5286
5278
  formatFinalResult: () => formatFinalResult,
5287
5279
  hasAnyForegroundTasks: () => hasAnyForegroundTasks,
5288
- isAutobackgroundingAllowed: () => isAutobackgroundingAllowed,
5289
5280
  openOutputFd: () => openOutputFd,
5290
5281
  readOutputFile: () => readOutputFile,
5291
5282
  sliceUtf8Safe: () => sliceUtf8Safe,
@@ -5572,12 +5563,12 @@ function takeUtf8Prefix(value, maxBytes) {
5572
5563
  }
5573
5564
  let used = 0;
5574
5565
  const parts = [];
5575
- for (const character of value) {
5576
- const bytes = utf8ByteLength(character);
5566
+ for (const character2 of value) {
5567
+ const bytes = utf8ByteLength(character2);
5577
5568
  if (used + bytes > maxBytes) {
5578
5569
  break;
5579
5570
  }
5580
- parts.push(character);
5571
+ parts.push(character2);
5581
5572
  used += bytes;
5582
5573
  }
5583
5574
  return parts.join("");
@@ -5683,11 +5674,6 @@ var BACKGROUND_NOTIFICATION_BYTES = 3e4;
5683
5674
  var BACKGROUND_PREVIEW_BYTES = TOOL_RESULT_PREVIEW_CHARS;
5684
5675
  var BACKGROUND_MAX_OUTPUT_BYTES = 5 * 1024 * 1024 * 1024;
5685
5676
  var SIZE_WATCHDOG_INTERVAL_MS = 500;
5686
- function isAutobackgroundingAllowed(command, disallowed) {
5687
- const first = /^\S+/.exec(command.trimStart())?.[0] ?? "";
5688
- const base = first.replace(/^.*\//, "").replace(/^["']|["']$/g, "").toLowerCase();
5689
- return !disallowed.has(base);
5690
- }
5691
5677
  function backgroundTaskName(command) {
5692
5678
  const flat = command.replace(/\s+/g, " ").trim();
5693
5679
  return flat.length > 80 ? `${flat.slice(0, 77)}...` : flat;
@@ -5771,11 +5757,11 @@ function openOutputFd(path) {
5771
5757
  const flags = process.platform === "win32" ? "w" : fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND | fsConstants.O_NOFOLLOW;
5772
5758
  return openSync(path, flags, 384);
5773
5759
  }
5774
- function createShellOutputFile(workDir, sessionId) {
5760
+ function createShellOutputFile(sessionId) {
5775
5761
  const fileName = `shell-${randomBytes2(8).toString("hex")}.output`;
5776
5762
  const candidates = [];
5777
5763
  try {
5778
- const dir = spillDir(workDir, sessionId);
5764
+ const dir = spillDir(sessionId);
5779
5765
  mkdirSync5(dir, { recursive: true });
5780
5766
  candidates.push(join7(dir, fileName));
5781
5767
  } catch {
@@ -5912,7 +5898,6 @@ function backgroundAllForegroundTasks(registry) {
5912
5898
  var MAX_TIMEOUT = 600;
5913
5899
  var log9 = createChildLogger({ module: "bash" });
5914
5900
  var KILL_GRACE_MS = 3e3;
5915
- var DISALLOWED_AUTO_BACKGROUND_COMMANDS = /* @__PURE__ */ new Set(["sleep"]);
5916
5901
  var BashTool = class {
5917
5902
  async dispose() {
5918
5903
  await this.sandbox?.dispose?.();
@@ -6039,7 +6024,7 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6039
6024
  const runInBackground = boolArg(args, "run_in_background") && backgroundAvailable;
6040
6025
  let outputFile;
6041
6026
  try {
6042
- outputFile = createShellOutputFile(ctx.workDir, ctx.sessionId ?? "");
6027
+ outputFile = createShellOutputFile(ctx.sessionId ?? "");
6043
6028
  } catch (error) {
6044
6029
  return {
6045
6030
  output: `Error creating output file: ${asErrorString(error)}`,
@@ -6084,7 +6069,7 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6084
6069
  ]
6085
6070
  },
6086
6071
  {
6087
- cwd: ctx.workDir,
6072
+ cwd: ctx.cwd,
6088
6073
  abortSignal: ctx.abortSignal,
6089
6074
  commandId: ctx.toolCallId
6090
6075
  }
@@ -6147,7 +6132,7 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6147
6132
  let child;
6148
6133
  try {
6149
6134
  child = spawn2(prepared.executable, prepared.args, {
6150
- cwd: ctx.workDir,
6135
+ cwd: ctx.cwd,
6151
6136
  detached: true,
6152
6137
  env: prepared.env,
6153
6138
  // stdout and stderr share one output fd, opened O_APPEND on POSIX so
@@ -6222,19 +6207,15 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6222
6207
  terminate();
6223
6208
  };
6224
6209
  const backgroundAvailableHere = manager !== null && process.env.YUKINO_DISABLE_BACKGROUND_TASKS !== "1";
6225
- const autoBackgroundAllowed = backgroundAvailableHere && isAutobackgroundingAllowed(
6226
- command,
6227
- DISALLOWED_AUTO_BACKGROUND_COMMANDS
6228
- );
6229
6210
  let timedOut = false;
6230
- const timeoutTimer = setTimeout(() => {
6231
- if (autoBackgroundAllowed && backgroundExecution("timeout") !== null) {
6211
+ const timeoutTimer = ctx.shellTimeoutDisabled ? void 0 : setTimeout(() => {
6212
+ if (backgroundExecution("timeout") !== null) {
6232
6213
  return;
6233
6214
  }
6234
6215
  timedOut = true;
6235
6216
  terminate();
6236
6217
  }, timeout * 1e3);
6237
- timeoutTimer.unref();
6218
+ timeoutTimer?.unref();
6238
6219
  ctx.abortSignal?.addEventListener("abort", onAbort, { once: true });
6239
6220
  if (ctx.abortSignal?.aborted) {
6240
6221
  onAbort();
@@ -6376,7 +6357,7 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6376
6357
  };
6377
6358
 
6378
6359
  // src/bootstrap/sandbox.ts
6379
- async function configureBashSandbox(registry, workDir, config, checker) {
6360
+ async function configureBashSandbox(registry, cwd2, config, checker) {
6380
6361
  const bash = registry.getInstanceOf("Bash", BashTool);
6381
6362
  if (!bash) {
6382
6363
  return;
@@ -6385,7 +6366,7 @@ async function configureBashSandbox(registry, workDir, config, checker) {
6385
6366
  if (bash.sandboxRequired) {
6386
6367
  bash.sandbox = await createSandbox();
6387
6368
  bash.sandboxConfig = {
6388
- allowWrite: [workDir, tmpdir2()],
6369
+ allowWrite: [cwd2, tmpdir2()],
6389
6370
  denyWrite: [],
6390
6371
  networkEnabled: config?.network_enabled ?? true
6391
6372
  };
@@ -8095,6 +8076,112 @@ function buildDiff(oldContent, newContent) {
8095
8076
  };
8096
8077
  }
8097
8078
 
8079
+ // src/tools/edit-file-diagnostics.ts
8080
+ var edit_file_diagnostics_exports = {};
8081
+ __export(edit_file_diagnostics_exports, {
8082
+ describeEditMismatch: () => describeEditMismatch
8083
+ });
8084
+ function position(text, offset) {
8085
+ const prefix = text.slice(0, offset);
8086
+ const line = (prefix.match(/\n/gu)?.length ?? 0) + 1;
8087
+ const column = Array.from(prefix.slice(prefix.lastIndexOf("\n") + 1)).length + 1;
8088
+ return `line ${String(line)}, column ${String(column)}`;
8089
+ }
8090
+ function character(text, offset) {
8091
+ const codePoint = text.codePointAt(offset);
8092
+ if (codePoint === void 0) {
8093
+ return "end of text";
8094
+ }
8095
+ const value = JSON.stringify(String.fromCodePoint(codePoint)).replace(
8096
+ / /gu,
8097
+ "\\u0020"
8098
+ );
8099
+ return `${value} (U+${codePoint.toString(16).toUpperCase().padStart(4, "0")})`;
8100
+ }
8101
+ function context(text, offset) {
8102
+ return JSON.stringify(
8103
+ text.slice(Math.max(0, offset - 30), offset + 30)
8104
+ ).replace(/ /gu, "\\u0020");
8105
+ }
8106
+ function mismatch(file, snippet, start, length) {
8107
+ return [
8108
+ `First difference: old_string ${position(snippet, length)} has ${character(snippet, length)}; file ${position(file, start + length)} has ${character(file, start + length)}.`,
8109
+ `old_string context: ${context(snippet, length)}`,
8110
+ `file context: ${context(file, start + length)}`
8111
+ ].join("\n");
8112
+ }
8113
+ function commonPrefix(file, snippet, start) {
8114
+ let length = 0;
8115
+ while (length < snippet.length && file.codePointAt(start + length) === snippet.codePointAt(length)) {
8116
+ length += (snippet.codePointAt(length) ?? 0) > 65535 ? 2 : 1;
8117
+ }
8118
+ return length;
8119
+ }
8120
+ function sourceOffset(text, normalizedOffset) {
8121
+ let removed = 0;
8122
+ for (const whitespace of text.matchAll(/[^\S\r\n]+/gu)) {
8123
+ if (whitespace.index - removed >= normalizedOffset) {
8124
+ break;
8125
+ }
8126
+ removed += whitespace[0].length - 1;
8127
+ }
8128
+ return normalizedOffset + removed;
8129
+ }
8130
+ function describeEditMismatch(content, oldString) {
8131
+ const file = content.replace(/\r\n/gu, "\n");
8132
+ const snippet = oldString.replace(/\r\n/gu, "\n");
8133
+ const normalizedFile = file.replace(/[^\S\r\n]+/gu, " ");
8134
+ const normalizedSnippet = snippet.replace(/[^\S\r\n]+/gu, " ");
8135
+ const candidates = [];
8136
+ if (normalizedSnippet) {
8137
+ let cursor = 0;
8138
+ while (candidates.length < 3) {
8139
+ const index = normalizedFile.indexOf(normalizedSnippet, cursor);
8140
+ if (index < 0) {
8141
+ break;
8142
+ }
8143
+ candidates.push(sourceOffset(file, index));
8144
+ cursor = index + normalizedSnippet.length;
8145
+ }
8146
+ }
8147
+ const details = [];
8148
+ if (candidates.length > 0) {
8149
+ details.push(
8150
+ `Candidates matching after horizontal whitespace normalization (up to 3): ${candidates.map((start2) => `file ${position(file, start2)}`).join("; ")}. These are suggestions only; whitespace must match exactly.`
8151
+ );
8152
+ const start = candidates[0];
8153
+ details.push(
8154
+ mismatch(file, snippet, start, commonPrefix(file, snippet, start))
8155
+ );
8156
+ } else {
8157
+ let low = 0;
8158
+ let high = snippet.length;
8159
+ while (low < high) {
8160
+ const middle = Math.ceil((low + high) / 2);
8161
+ if (file.includes(snippet.slice(0, middle))) {
8162
+ low = middle;
8163
+ } else {
8164
+ high = middle - 1;
8165
+ }
8166
+ }
8167
+ if (low > 0) {
8168
+ const start = file.indexOf(snippet.slice(0, low));
8169
+ details.push(
8170
+ `Longest matching prefix starts at file ${position(file, start)}.`
8171
+ );
8172
+ details.push(
8173
+ mismatch(file, snippet, start, commonPrefix(file, snippet, start))
8174
+ );
8175
+ } else {
8176
+ details.push(
8177
+ "No matching prefix or horizontal-whitespace candidate found."
8178
+ );
8179
+ }
8180
+ }
8181
+ details.push("No edits were written.");
8182
+ return details.join("\n");
8183
+ }
8184
+
8098
8185
  // src/tools/file-mutation-queue.ts
8099
8186
  var file_mutation_queue_exports = {};
8100
8187
  __export(file_mutation_queue_exports, {
@@ -8163,12 +8250,14 @@ function applyEdits(content, edits) {
8163
8250
  const ending = /\r?\n/u.exec(content)?.[0] ?? "\n";
8164
8251
  const replacements = [];
8165
8252
  for (const [editIndex, edit] of edits.entries()) {
8166
- let pattern = editPattern(edit.oldString);
8253
+ let oldString = edit.oldString;
8254
+ let pattern = editPattern(oldString);
8167
8255
  let match = pattern.exec(content);
8168
8256
  let newString = edit.newString;
8169
8257
  if (!match) {
8170
8258
  const cleanedOldString = withoutStrayCarriageReturns(edit.oldString);
8171
8259
  if (cleanedOldString && cleanedOldString !== edit.oldString) {
8260
+ oldString = cleanedOldString;
8172
8261
  pattern = editPattern(cleanedOldString);
8173
8262
  match = pattern.exec(content);
8174
8263
  newString = withoutStrayCarriageReturns(newString);
@@ -8199,7 +8288,8 @@ function applyEdits(content, edits) {
8199
8288
  }
8200
8289
  if (count === 0) {
8201
8290
  throw new Error(
8202
- `edits[${String(editIndex)}].old_string not found in file`
8291
+ `edits[${String(editIndex)}].old_string not found in file
8292
+ ${describeEditMismatch(content, oldString)}`
8203
8293
  );
8204
8294
  }
8205
8295
  }
@@ -8272,7 +8362,7 @@ var EditFileTool = class {
8272
8362
  isError: true
8273
8363
  };
8274
8364
  }
8275
- const filePath = resolveToolPath(ctx.workDir, requestedPath);
8365
+ const filePath = resolveToolPath(ctx.cwd, requestedPath);
8276
8366
  if (!Array.isArray(args.edits) || args.edits.length === 0) {
8277
8367
  return {
8278
8368
  output: "Error: edits must contain at least one replacement",
@@ -8406,7 +8496,7 @@ var EnterWorktreeTool = class {
8406
8496
  });
8407
8497
  }
8408
8498
  try {
8409
- const result = await createAgentWorktree(slug, void 0, ctx.workDir);
8499
+ const result = await createAgentWorktree(slug, void 0, ctx.cwd);
8410
8500
  return {
8411
8501
  output: `Worktree created at ${result.path}
8412
8502
  Branch: ${result.branch}
@@ -8451,7 +8541,7 @@ var ExitPlanModeTool = class {
8451
8541
  }
8452
8542
  execute(ctx, _args) {
8453
8543
  if (ctx.permissionChecker?.mode !== "plan") {
8454
- if (ctx.permissionChecker && planExists(ctx.workDir, ctx.permissionChecker)) {
8544
+ if (ctx.permissionChecker && planExists(ctx.permissionChecker)) {
8455
8545
  return Promise.resolve({
8456
8546
  output: "You are not in plan mode. Continue within the user's requested scope and current permissions. Only the user can enter plan mode with /plan; AskUserQuestion is for clarification, not approval.",
8457
8547
  isError: true
@@ -8462,7 +8552,7 @@ var ExitPlanModeTool = class {
8462
8552
  isError: true
8463
8553
  });
8464
8554
  }
8465
- if (!planExists(ctx.workDir, ctx.permissionChecker) || !loadPlan(ctx.permissionChecker)?.trim()) {
8555
+ if (!planExists(ctx.permissionChecker) || !loadPlan(ctx.permissionChecker)?.trim()) {
8466
8556
  return Promise.resolve({
8467
8557
  output: "No non-empty plan file found. Write your plan to the declared plan file before calling ExitPlanMode.",
8468
8558
  isError: true
@@ -8639,10 +8729,7 @@ var GlobTool = class {
8639
8729
  isError: true
8640
8730
  };
8641
8731
  }
8642
- const basePath = resolveToolPath(
8643
- ctx.workDir,
8644
- strArg(args, "path", ctx.workDir)
8645
- );
8732
+ const basePath = resolveToolPath(ctx.cwd, strArg(args, "path", ctx.cwd));
8646
8733
  const maxResults = 1e3;
8647
8734
  try {
8648
8735
  if (!statSync6(basePath, { throwIfNoEntry: false })?.isDirectory()) {
@@ -8881,10 +8968,7 @@ var GrepTool = class {
8881
8968
  isError: true
8882
8969
  };
8883
8970
  }
8884
- const searchPath = resolveToolPath(
8885
- ctx.workDir,
8886
- strArg(args, "path", ctx.workDir)
8887
- );
8971
+ const searchPath = resolveToolPath(ctx.cwd, strArg(args, "path", ctx.cwd));
8888
8972
  const include = strArg(args, "include");
8889
8973
  let regex;
8890
8974
  try {
@@ -8901,9 +8985,7 @@ var GrepTool = class {
8901
8985
  }
8902
8986
  }
8903
8987
  const includeMatcher = include ? new Minimatch(include, { dot: true, matchBase: true }) : null;
8904
- const matchesInclude = (fullPath) => includeMatcher === null || includeMatcher.match(
8905
- relative2(ctx.workDir, fullPath).split(sep2).join("/")
8906
- );
8988
+ const matchesInclude = (fullPath) => includeMatcher === null || includeMatcher.match(relative2(ctx.cwd, fullPath).split(sep2).join("/"));
8907
8989
  const results = new SearchOutput(MAX_RESULTS);
8908
8990
  let shortenedLines = 0;
8909
8991
  let skippedLargeFiles = 0;
@@ -8930,7 +9012,7 @@ var GrepTool = class {
8930
9012
  const buf = await file.readFile({ signal: ctx.abortSignal });
8931
9013
  ctx.abortSignal?.throwIfAborted();
8932
9014
  const lines = buf.toString("utf-8").split("\n");
8933
- const rel = relative2(ctx.workDir, filePath);
9015
+ const rel = relative2(ctx.cwd, filePath);
8934
9016
  for (let i = 0; i < lines.length; i++) {
8935
9017
  if (regex.test(lines[i])) {
8936
9018
  const preview2 = takeUtf8Prefix(lines[i], MAX_MATCH_LINE_BYTES);
@@ -9082,11 +9164,11 @@ import {
9082
9164
  } from "child_process";
9083
9165
  import { pathToFileURL } from "url";
9084
9166
  var LspClient = class {
9085
- constructor(config, workDir) {
9167
+ constructor(config, cwd2) {
9086
9168
  this.config = config;
9087
- this.workDir = workDir;
9169
+ this.cwd = cwd2;
9088
9170
  this.child = spawn4(config.command, config.args ?? [], {
9089
- cwd: workDir,
9171
+ cwd: cwd2,
9090
9172
  env: { ...process.env, ...config.env },
9091
9173
  shell: false,
9092
9174
  detached: process.platform !== "win32",
@@ -9126,7 +9208,7 @@ var LspClient = class {
9126
9208
  });
9127
9209
  }
9128
9210
  config;
9129
- workDir;
9211
+ cwd;
9130
9212
  child;
9131
9213
  buffer = Buffer.alloc(0);
9132
9214
  nextId = 1;
@@ -9318,9 +9400,7 @@ var LspClient = class {
9318
9400
  case "workspace/workspaceFolders":
9319
9401
  this.send({
9320
9402
  id: message.id,
9321
- result: [
9322
- { uri: pathToFileURL(this.workDir).href, name: this.workDir }
9323
- ]
9403
+ result: [{ uri: pathToFileURL(this.cwd).href, name: this.cwd }]
9324
9404
  });
9325
9405
  return;
9326
9406
  case "window/showMessageRequest":
@@ -9347,10 +9427,8 @@ var LspClient = class {
9347
9427
  const result = await this.request("initialize", {
9348
9428
  processId: process.pid,
9349
9429
  clientInfo: { name: "yukino" },
9350
- rootUri: pathToFileURL(this.workDir).href,
9351
- workspaceFolders: [
9352
- { uri: pathToFileURL(this.workDir).href, name: this.workDir }
9353
- ],
9430
+ rootUri: pathToFileURL(this.cwd).href,
9431
+ workspaceFolders: [{ uri: pathToFileURL(this.cwd).href, name: this.cwd }],
9354
9432
  initializationOptions: this.config.initialization_options,
9355
9433
  capabilities: {
9356
9434
  general: { positionEncodings: ["utf-16"] },
@@ -9485,15 +9563,15 @@ var LspTool = class {
9485
9563
  }
9486
9564
  };
9487
9565
  }
9488
- session(config, workDir) {
9566
+ session(config, cwd2) {
9489
9567
  if (this.disposed) {
9490
9568
  throw new Error("LSP tool is disposed");
9491
9569
  }
9492
- const key = JSON.stringify([workDir, config.name]);
9570
+ const key = JSON.stringify([cwd2, config.name]);
9493
9571
  let promise = this.sessions.get(key);
9494
9572
  if (!promise) {
9495
9573
  promise = (async () => {
9496
- const client = new LspClient(config, workDir);
9574
+ const client = new LspClient(config, cwd2);
9497
9575
  const session = {
9498
9576
  client,
9499
9577
  documents: /* @__PURE__ */ new Map(),
@@ -9564,13 +9642,13 @@ var LspTool = class {
9564
9642
  }
9565
9643
  }
9566
9644
  const textDocument = { uri };
9567
- const position = {
9645
+ const position2 = {
9568
9646
  line: (args.line ?? 1) - 1,
9569
9647
  character: (args.character ?? 1) - 1
9570
9648
  };
9571
9649
  if (args.line !== void 0) {
9572
9650
  const lines = text.split(/\r?\n/u);
9573
- if (position.line >= lines.length || position.character > (lines[position.line]?.length ?? 0)) {
9651
+ if (position2.line >= lines.length || position2.character > (lines[position2.line]?.length ?? 0)) {
9574
9652
  throw new Error("LSP position is outside the document");
9575
9653
  }
9576
9654
  }
@@ -9638,7 +9716,7 @@ var LspTool = class {
9638
9716
  if (args.operation === "incomingCalls" || args.operation === "outgoingCalls") {
9639
9717
  const prepared = await session.client.request(
9640
9718
  "textDocument/prepareCallHierarchy",
9641
- { textDocument, position },
9719
+ { textDocument, position: position2 },
9642
9720
  signal
9643
9721
  );
9644
9722
  if (!Array.isArray(prepared)) {
@@ -9661,7 +9739,7 @@ var LspTool = class {
9661
9739
  `textDocument/${args.operation}`,
9662
9740
  {
9663
9741
  textDocument,
9664
- position,
9742
+ position: position2,
9665
9743
  ...args.operation === "references" ? { context: { includeDeclaration: true } } : {}
9666
9744
  },
9667
9745
  signal
@@ -9674,8 +9752,8 @@ var LspTool = class {
9674
9752
  }
9675
9753
  try {
9676
9754
  ctx.abortSignal?.throwIfAborted();
9677
- const workDir = resolve5(ctx.workDir);
9678
- const filePath = resolveToolPath(workDir, parsed.data.file_path);
9755
+ const cwd2 = resolve5(ctx.cwd);
9756
+ const filePath = resolveToolPath(cwd2, parsed.data.file_path);
9679
9757
  const config = this.configs.find(
9680
9758
  (server) => Object.hasOwn(server.languages, extname2(filePath))
9681
9759
  );
@@ -9688,18 +9766,15 @@ var LspTool = class {
9688
9766
  if (!info.isFile() || info.size > 10 * 1024 * 1024) {
9689
9767
  throw new Error("LSP requires a regular file no larger than 10MB");
9690
9768
  }
9691
- const key = JSON.stringify([workDir, config.name]);
9692
- const activeSession = this.session(config, workDir);
9769
+ const key = JSON.stringify([cwd2, config.name]);
9770
+ const activeSession = this.session(config, cwd2);
9693
9771
  let session = await abortable(activeSession, ctx.abortSignal);
9694
9772
  if (session.client.isClosed) {
9695
9773
  await session.client.dispose();
9696
9774
  if (this.sessions.get(key) === activeSession) {
9697
9775
  this.sessions.delete(key);
9698
9776
  }
9699
- session = await abortable(
9700
- this.session(config, workDir),
9701
- ctx.abortSignal
9702
- );
9777
+ session = await abortable(this.session(config, cwd2), ctx.abortSignal);
9703
9778
  }
9704
9779
  const current = session;
9705
9780
  const result = current.queue.then(
@@ -9740,7 +9815,6 @@ import { execFile as execFile2, spawn as spawn5 } from "child_process";
9740
9815
  import { statSync as statSync7 } from "fs";
9741
9816
  var MAX_TIMEOUT2 = 600;
9742
9817
  var KILL_GRACE_MS2 = 3e3;
9743
- var DISALLOWED_AUTO_BACKGROUND_COMMANDS2 = /* @__PURE__ */ new Set(["start-sleep", "sleep"]);
9744
9818
  var PowerShellTool = class {
9745
9819
  // Use a hardcoded string instead of PowerShellTool.name.replace("Tool", "")
9746
9820
  // because class names are not stable after minification — bundlers like
@@ -9832,7 +9906,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9832
9906
  const shell = process.platform === "win32" ? "powershell.exe" : "pwsh";
9833
9907
  let outputFile;
9834
9908
  try {
9835
- outputFile = createShellOutputFile(ctx.workDir, ctx.sessionId ?? "");
9909
+ outputFile = createShellOutputFile(ctx.sessionId ?? "");
9836
9910
  } catch (error) {
9837
9911
  return {
9838
9912
  output: `Error creating output file: ${asErrorString(error)}`,
@@ -9892,7 +9966,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9892
9966
  let child;
9893
9967
  try {
9894
9968
  child = spawn5(shell, shellArgs, {
9895
- cwd: ctx.workDir,
9969
+ cwd: ctx.cwd,
9896
9970
  // Only POSIX needs its own process group for kill(-pid); the Windows
9897
9971
  // tree kill goes through taskkill and needs no new group.
9898
9972
  detached: process.platform !== "win32",
@@ -9975,19 +10049,15 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9975
10049
  terminate();
9976
10050
  };
9977
10051
  const backgroundAvailableHere = manager !== null && process.env.YUKINO_DISABLE_BACKGROUND_TASKS !== "1";
9978
- const autoBackgroundAllowed = backgroundAvailableHere && isAutobackgroundingAllowed(
9979
- command,
9980
- DISALLOWED_AUTO_BACKGROUND_COMMANDS2
9981
- );
9982
10052
  let timedOut = false;
9983
- const timeoutTimer = setTimeout(() => {
9984
- if (autoBackgroundAllowed && backgroundExecution("timeout") !== null) {
10053
+ const timeoutTimer = ctx.shellTimeoutDisabled ? void 0 : setTimeout(() => {
10054
+ if (backgroundExecution("timeout") !== null) {
9985
10055
  return;
9986
10056
  }
9987
10057
  timedOut = true;
9988
10058
  terminate();
9989
10059
  }, timeout * 1e3);
9990
- timeoutTimer.unref();
10060
+ timeoutTimer?.unref();
9991
10061
  ctx.abortSignal?.addEventListener("abort", onAbort, { once: true });
9992
10062
  if (ctx.abortSignal?.aborted) {
9993
10063
  onAbort();
@@ -10161,7 +10231,7 @@ var ReadFileTool = class {
10161
10231
  isError: true
10162
10232
  };
10163
10233
  }
10164
- const filePath = resolveToolPath(ctx.workDir, requestedPath);
10234
+ const filePath = resolveToolPath(ctx.cwd, requestedPath);
10165
10235
  if (ctx.abortSignal?.aborted) {
10166
10236
  return { output: "Error: operation interrupted", isError: true };
10167
10237
  }
@@ -10833,7 +10903,7 @@ var WriteFileTool = class {
10833
10903
  });
10834
10904
  }
10835
10905
  const content = args.content;
10836
- const filePath = resolveToolPath(ctx.workDir, requestedPath);
10906
+ const filePath = resolveToolPath(ctx.cwd, requestedPath);
10837
10907
  return withFileMutationQueue(filePath, async () => {
10838
10908
  if (ctx.abortSignal?.aborted) {
10839
10909
  return {
@@ -10888,7 +10958,7 @@ function removeMcpTools(registry, serverNames) {
10888
10958
  }
10889
10959
  }
10890
10960
  }
10891
- function createToolRegistry(workDir, taskList, options = {}) {
10961
+ function createToolRegistry(cwd2, taskList, options = {}) {
10892
10962
  const registry = new ToolRegistry();
10893
10963
  registry.register(new GoalTool());
10894
10964
  registry.register(new TaskCreateTool(taskList));
@@ -10932,7 +11002,7 @@ function wireSkillsToRegistry(catalog, commandRegistry, skillHost) {
10932
11002
  type: skill.meta.mode === "fork" ? "skill_fork" : "prompt",
10933
11003
  description: `${meta.description} [skill]`,
10934
11004
  isSkill: true,
10935
- handler: skill.meta.mode === "fork" ? () => "" : (context) => runInline(skill, context.args, skillHost)
11005
+ handler: skill.meta.mode === "fork" ? () => "" : (context2) => runInline(skill, context2.args, skillHost)
10936
11006
  };
10937
11007
  try {
10938
11008
  commandRegistry.register(command);
@@ -12245,16 +12315,16 @@ var DIFF_FLAGS = [
12245
12315
  "--no-color",
12246
12316
  `-U${String(DIFF_CONTEXT_LINES)}`
12247
12317
  ];
12248
- async function runGit(workDir, args, abortSignal) {
12318
+ async function runGit(cwd2, args, abortSignal) {
12249
12319
  return execFileAsync("git", args, {
12250
- cwd: workDir,
12320
+ cwd: cwd2,
12251
12321
  maxBuffer: 256 * 1024 * 1024,
12252
12322
  signal: abortSignal
12253
12323
  });
12254
12324
  }
12255
- async function tryGit(workDir, args, abortSignal) {
12325
+ async function tryGit(cwd2, args, abortSignal) {
12256
12326
  try {
12257
- const { stdout } = await runGit(workDir, args, abortSignal);
12327
+ const { stdout } = await runGit(cwd2, args, abortSignal);
12258
12328
  return stdout;
12259
12329
  } catch {
12260
12330
  return null;
@@ -12297,9 +12367,9 @@ function untrackedFileDiff(relPath, content) {
12297
12367
  return `${text}
12298
12368
  `;
12299
12369
  }
12300
- async function untrackedFileDiffs(workDir, abortSignal) {
12370
+ async function untrackedFileDiffs(cwd2, abortSignal) {
12301
12371
  const list = await tryGit(
12302
- workDir,
12372
+ cwd2,
12303
12373
  [
12304
12374
  "-c",
12305
12375
  "core.quotepath=false",
@@ -12318,7 +12388,7 @@ async function untrackedFileDiffs(workDir, abortSignal) {
12318
12388
  for (const f of files) {
12319
12389
  let content;
12320
12390
  try {
12321
- content = await readFile7(join12(workDir, f));
12391
+ content = await readFile7(join12(cwd2, f));
12322
12392
  } catch {
12323
12393
  continue;
12324
12394
  }
@@ -12331,19 +12401,19 @@ async function untrackedFileDiffs(workDir, abortSignal) {
12331
12401
  return results;
12332
12402
  }
12333
12403
  async function collectDiffs(options) {
12334
- const { workDir, mode: mode2, abortSignal } = options;
12404
+ const { cwd: cwd2, mode: mode2, abortSignal } = options;
12335
12405
  options.abortSignal?.throwIfAborted();
12336
12406
  let combined = "";
12337
12407
  let ref = "";
12338
12408
  if (mode2 === "range") {
12339
12409
  const from = options.from ?? "";
12340
12410
  const to = options.to ?? "";
12341
- const base = await tryGit(workDir, ["merge-base", from, to], abortSignal);
12411
+ const base = await tryGit(cwd2, ["merge-base", from, to], abortSignal);
12342
12412
  if (!base?.trim()) {
12343
12413
  throw new Error(`Cannot find merge-base between ${from} and ${to}`);
12344
12414
  }
12345
12415
  const { stdout } = await runGit(
12346
- workDir,
12416
+ cwd2,
12347
12417
  [...DIFF_FLAGS, "--end-of-options", base.trim(), to, "--"],
12348
12418
  abortSignal
12349
12419
  );
@@ -12352,7 +12422,7 @@ async function collectDiffs(options) {
12352
12422
  } else if (mode2 === "commit") {
12353
12423
  const commit = options.commit ?? "";
12354
12424
  const { stdout } = await runGit(
12355
- workDir,
12425
+ cwd2,
12356
12426
  [
12357
12427
  "-c",
12358
12428
  "core.quotepath=false",
@@ -12374,20 +12444,20 @@ async function collectDiffs(options) {
12374
12444
  ref = commit;
12375
12445
  } else {
12376
12446
  let tracked = await tryGit(
12377
- workDir,
12447
+ cwd2,
12378
12448
  [...DIFF_FLAGS, "--end-of-options", "HEAD", "--"],
12379
12449
  abortSignal
12380
12450
  );
12381
12451
  if (tracked === null) {
12382
12452
  const staged = await runGit(
12383
- workDir,
12453
+ cwd2,
12384
12454
  [...DIFF_FLAGS, "--staged", "--"],
12385
12455
  abortSignal
12386
12456
  );
12387
12457
  tracked = staged.stdout;
12388
12458
  }
12389
12459
  combined = tracked;
12390
- const untracked = await untrackedFileDiffs(workDir, abortSignal);
12460
+ const untracked = await untrackedFileDiffs(cwd2, abortSignal);
12391
12461
  for (const ud of untracked) {
12392
12462
  combined += `${ud}
12393
12463
  `;
@@ -12397,7 +12467,7 @@ async function collectDiffs(options) {
12397
12467
  return parseDiffText(combined, {
12398
12468
  readNewFileContent: async (newPath) => {
12399
12469
  if (ref) {
12400
- const out = await tryGit(workDir, [
12470
+ const out = await tryGit(cwd2, [
12401
12471
  "-c",
12402
12472
  "core.quotepath=false",
12403
12473
  "show",
@@ -12407,7 +12477,7 @@ async function collectDiffs(options) {
12407
12477
  return out ?? void 0;
12408
12478
  }
12409
12479
  try {
12410
- return await readFile7(join12(workDir, newPath), "utf8");
12480
+ return await readFile7(join12(cwd2, newPath), "utf8");
12411
12481
  } catch {
12412
12482
  return void 0;
12413
12483
  }
@@ -12664,21 +12734,21 @@ __export(client_exports2, {
12664
12734
  async function createClient(config, systemPrompt) {
12665
12735
  switch (config.protocol) {
12666
12736
  case "anthropic": {
12667
- const { AnthropicClient } = await import("./anthropic-7HQY42TP.js");
12737
+ const { AnthropicClient } = await import("./anthropic-AVZIC22O.js");
12668
12738
  return registerLlmClient(new AnthropicClient(config, systemPrompt), {
12669
12739
  model: config.model,
12670
12740
  protocol: config.protocol
12671
12741
  });
12672
12742
  }
12673
12743
  case "openai": {
12674
- const { OpenAIClient } = await import("./openai-Z7PCXN2X.js");
12744
+ const { OpenAIClient } = await import("./openai-54IQOU6Y.js");
12675
12745
  return registerLlmClient(new OpenAIClient(config, systemPrompt), {
12676
12746
  model: config.model,
12677
12747
  protocol: config.protocol
12678
12748
  });
12679
12749
  }
12680
12750
  case "openai-compat": {
12681
- const { OpenAICompatClient } = await import("./openai-Z7PCXN2X.js");
12751
+ const { OpenAICompatClient } = await import("./openai-54IQOU6Y.js");
12682
12752
  return registerLlmClient(new OpenAICompatClient(config, systemPrompt), {
12683
12753
  model: config.model,
12684
12754
  protocol: config.protocol
@@ -12724,7 +12794,7 @@ function diffsChurn(diffs) {
12724
12794
  function noopProgress() {
12725
12795
  }
12726
12796
  async function runCodeReview(options, deps) {
12727
- const { workDir, abortSignal } = options;
12797
+ const { cwd: cwd2, abortSignal } = options;
12728
12798
  const progress = options.onProgress ?? noopProgress;
12729
12799
  const maxConcurrency = options.maxConcurrency ?? DEFAULT_CONCURRENCY;
12730
12800
  const maxRounds = options.maxRounds ?? DEFAULT_MAX_ROUNDS;
@@ -12748,7 +12818,7 @@ async function runCodeReview(options, deps) {
12748
12818
  };
12749
12819
  progress({ phase: "diff", message: "Collecting git diffs\u2026" });
12750
12820
  const diffs = await collectDiffs({
12751
- workDir,
12821
+ cwd: cwd2,
12752
12822
  mode: mode2,
12753
12823
  from: options.from,
12754
12824
  to: options.to,
@@ -12827,7 +12897,7 @@ async function runCodeReview(options, deps) {
12827
12897
  const collector = new CommentCollector();
12828
12898
  try {
12829
12899
  await executeGroupSubtask(g, {
12830
- workDir,
12900
+ cwd: cwd2,
12831
12901
  provider: deps.provider,
12832
12902
  utilClient,
12833
12903
  collector,
@@ -13034,9 +13104,9 @@ async function runGroupAgent(g, deps, opts) {
13034
13104
  // All review tools are category "read", so "default" mode auto-allows
13035
13105
  // everything an unattended review can do while write/command attempts
13036
13106
  // (which have no permission handler here) are simply not executed.
13037
- checker: new PermissionChecker(deps.workDir, "default"),
13107
+ checker: new PermissionChecker(deps.cwd, "default"),
13038
13108
  conversation,
13039
- workDir: deps.workDir,
13109
+ cwd: deps.cwd,
13040
13110
  maxIterations: MAX_AGENT_ITERATIONS,
13041
13111
  abortSignal: deps.abortSignal,
13042
13112
  fileStateCache: new FileStateCache(),
@@ -13239,7 +13309,7 @@ function createDefaultRegistry() {
13239
13309
  if (ctx.model) {
13240
13310
  lines.push(` Model: ${ctx.model}`);
13241
13311
  }
13242
- lines.push(` Directory: ${ctx.workDir}`);
13312
+ lines.push(` Directory: ${ctx.cwd}`);
13243
13313
  return lines.join("\n");
13244
13314
  }
13245
13315
  });
@@ -13372,23 +13442,17 @@ __export(loader_exports2, {
13372
13442
  renderBody: () => renderBody
13373
13443
  });
13374
13444
  import { existsSync as existsSync6, lstatSync, readdirSync as readdirSync2, readFileSync as readFileSync5 } from "fs";
13375
- import { homedir } from "os";
13376
13445
  import { join as join13 } from "path";
13377
13446
  import yaml from "js-yaml";
13378
13447
  import { z as z13, parse as parse3 } from "zod";
13379
- function loadUserCommands(workDir) {
13448
+ function loadUserCommands() {
13449
+ const base = yukinoPath("prompts");
13450
+ if (!existsSync6(base)) {
13451
+ return [];
13452
+ }
13380
13453
  const byName = /* @__PURE__ */ new Map();
13381
- const bases = [
13382
- join13(homedir(), ".yukino", "commands"),
13383
- join13(workDir, ".yukino", "commands")
13384
- ];
13385
- for (const base of bases) {
13386
- if (!existsSync6(base)) {
13387
- continue;
13388
- }
13389
- for (const cmd of walkDir(base, base)) {
13390
- byName.set(cmd.name, cmd);
13391
- }
13454
+ for (const cmd of walkDir(base, base)) {
13455
+ byName.set(cmd.name, cmd);
13392
13456
  }
13393
13457
  return [...byName.values()];
13394
13458
  }
@@ -13456,7 +13520,7 @@ function parseCommandFile(base, full) {
13456
13520
  return {
13457
13521
  name,
13458
13522
  type: "prompt",
13459
- description: description || (argumentHint ? `custom command (args: ${argumentHint})` : "custom command"),
13523
+ description: `${description || (argumentHint ? `custom command (args: ${argumentHint})` : "custom command")} [custom]`,
13460
13524
  handler: (ctx) => renderBody(body, ctx.args)
13461
13525
  };
13462
13526
  }
@@ -13579,7 +13643,7 @@ var HookEngine = class {
13579
13643
  this.notifications = [];
13580
13644
  return out;
13581
13645
  }
13582
- async fire(event, context, options = {}) {
13646
+ async fire(event, context2, options = {}) {
13583
13647
  const results = [];
13584
13648
  for (const [index, hook] of this.hooks.entries()) {
13585
13649
  if (options.abortSignal?.aborted) {
@@ -13588,7 +13652,7 @@ var HookEngine = class {
13588
13652
  if (hook.event !== event) {
13589
13653
  continue;
13590
13654
  }
13591
- if (hook.condition && !evaluateCondition(hook.condition, context)) {
13655
+ if (hook.condition && !evaluateCondition(hook.condition, context2)) {
13592
13656
  continue;
13593
13657
  }
13594
13658
  const onceKey = hook.once ? hook.id === void 0 ? `index:${String(index)}` : `id:${hook.id}` : null;
@@ -13599,7 +13663,7 @@ var HookEngine = class {
13599
13663
  this.firedOnce.add(onceKey);
13600
13664
  }
13601
13665
  if (hook.async) {
13602
- this.executeAction(hook, context, options).then((r) => {
13666
+ this.executeAction(hook, context2, options).then((r) => {
13603
13667
  this.recordNotification(r.output);
13604
13668
  }).catch((err) => {
13605
13669
  log18.error({ err }, "hooks operation failed");
@@ -13615,7 +13679,7 @@ var HookEngine = class {
13615
13679
  continue;
13616
13680
  }
13617
13681
  try {
13618
- const result = await this.executeAction(hook, context, options);
13682
+ const result = await this.executeAction(hook, context2, options);
13619
13683
  results.push(result);
13620
13684
  if (result.reject && event === "pre_tool_use") {
13621
13685
  break;
@@ -13641,13 +13705,13 @@ var HookEngine = class {
13641
13705
  return results;
13642
13706
  }
13643
13707
  async firePreToolHooks(toolName, args, options = {}) {
13644
- const context = {
13708
+ const context2 = {
13645
13709
  event: "pre_tool_use",
13646
13710
  toolName,
13647
13711
  args,
13648
13712
  filePath: strArg(args, "file_path", strArg(args, "path", ""))
13649
13713
  };
13650
- const results = await this.fire("pre_tool_use", context, options);
13714
+ const results = await this.fire("pre_tool_use", context2, options);
13651
13715
  for (const r of results) {
13652
13716
  if (r.reject) {
13653
13717
  return { rejected: true, reason: r.output };
@@ -13656,19 +13720,19 @@ var HookEngine = class {
13656
13720
  }
13657
13721
  return { rejected: false, reason: "" };
13658
13722
  }
13659
- async executeAction(hook, context, options) {
13723
+ async executeAction(hook, context2, options) {
13660
13724
  switch (hook.action.type) {
13661
13725
  case "command": {
13662
13726
  const command = hook.action.command ?? "";
13663
13727
  try {
13664
13728
  const output = await execHookAsync(command, {
13665
- cwd: options.workDir,
13729
+ cwd: options.cwd,
13666
13730
  signal: options.abortSignal,
13667
13731
  env: {
13668
13732
  ...process.env,
13669
- YUKINO_EVENT: context.event,
13670
- YUKINO_TOOL: context.toolName ?? "",
13671
- YUKINO_FILE_PATH: context.filePath ?? ""
13733
+ YUKINO_EVENT: context2.event,
13734
+ YUKINO_TOOL: context2.toolName ?? "",
13735
+ YUKINO_FILE_PATH: context2.filePath ?? ""
13672
13736
  }
13673
13737
  });
13674
13738
  return {
@@ -13695,7 +13759,7 @@ var HookEngine = class {
13695
13759
  const resp = await fetch(url, {
13696
13760
  method,
13697
13761
  headers: { "Content-Type": "application/json" },
13698
- ...method === "GET" || method === "HEAD" ? {} : { body: JSON.stringify(context) },
13762
+ ...method === "GET" || method === "HEAD" ? {} : { body: JSON.stringify(context2) },
13699
13763
  signal: options.abortSignal ? AbortSignal.any([
13700
13764
  options.abortSignal,
13701
13765
  AbortSignal.timeout(3e4)
@@ -13726,7 +13790,7 @@ var HookEngine = class {
13726
13790
  }
13727
13791
  const prompt = hook.action.prompt ?? hook.action.command ?? "";
13728
13792
  try {
13729
- const output = await this.agentRunner(prompt, context);
13793
+ const output = await this.agentRunner(prompt, context2);
13730
13794
  return { output, success: true, reject: hook.reject ?? false };
13731
13795
  } catch (err) {
13732
13796
  log18.error({ err }, "hooks operation failed");
@@ -14280,38 +14344,33 @@ __export(consolidation_exports, {
14280
14344
  MemoryConsolidator: () => MemoryConsolidator
14281
14345
  });
14282
14346
  import { existsSync as existsSync7, statSync as statSync8, writeFileSync as writeFileSync5 } from "fs";
14283
- import { homedir as homedir3 } from "os";
14284
- import { join as join15, basename as basename3 } from "path";
14347
+ import { join as join14, basename as basename3 } from "path";
14285
14348
 
14286
14349
  // src/memory/permissions.ts
14287
14350
  var permissions_exports2 = {};
14288
14351
  __export(permissions_exports2, {
14289
14352
  MemoryPermissionChecker: () => MemoryPermissionChecker
14290
14353
  });
14291
- import { homedir as homedir2 } from "os";
14292
- import { extname as extname3, join as join14, resolve as resolve6 } from "path";
14354
+ import { extname as extname3, resolve as resolve6 } from "path";
14293
14355
  var MemoryPermissionChecker = class extends PermissionChecker {
14294
- constructor(memoryWorkDir, allowProjectReads = false) {
14295
- super(memoryWorkDir, "default");
14296
- this.memoryWorkDir = memoryWorkDir;
14356
+ constructor(memoryCwd, allowProjectReads = false) {
14357
+ super(memoryCwd, "default");
14358
+ this.memoryCwd = memoryCwd;
14297
14359
  this.allowProjectReads = allowProjectReads;
14298
- this.memoryRoots = [
14299
- join14(memoryWorkDir, ".yukino", "memory"),
14300
- join14(homedir2(), ".yukino", "memory")
14301
- ];
14360
+ this.memoryRoots = [projectPath(memoryCwd, "memory"), yukinoPath("memory")];
14302
14361
  }
14303
- memoryWorkDir;
14362
+ memoryCwd;
14304
14363
  allowProjectReads;
14305
14364
  memoryRoots;
14306
14365
  check(_name, category, args) {
14307
- const requested = args.file_path ?? args.path ?? this.memoryWorkDir;
14366
+ const requested = args.file_path ?? args.path ?? this.memoryCwd;
14308
14367
  if (category === "command" || typeof requested !== "string") {
14309
14368
  return {
14310
14369
  effect: "deny",
14311
14370
  reason: "Background memory tasks only support scoped file operations"
14312
14371
  };
14313
14372
  }
14314
- const path = canonicalPath(resolve6(this.memoryWorkDir, requested));
14373
+ const path = canonicalPath(resolve6(this.memoryCwd, requested));
14315
14374
  const insideMemory = this.memoryRoots.some(
14316
14375
  (root) => isPathWithin(canonicalPath(root), path)
14317
14376
  );
@@ -14321,7 +14380,7 @@ var MemoryPermissionChecker = class extends PermissionChecker {
14321
14380
  reason: "Background memory writes must stay in the memory directories and use .md files"
14322
14381
  };
14323
14382
  }
14324
- return insideMemory || this.allowProjectReads && isPathWithin(canonicalPath(this.memoryWorkDir), path) ? { effect: "allow", reason: "Memory task read" } : { effect: "deny", reason: "Read outside the memory task's scope" };
14383
+ return insideMemory || this.allowProjectReads && isPathWithin(canonicalPath(this.memoryCwd), path) ? { effect: "allow", reason: "Memory task read" } : { effect: "deny", reason: "Read outside the memory task's scope" };
14325
14384
  }
14326
14385
  };
14327
14386
 
@@ -14356,14 +14415,14 @@ var LOCK_FILE = ".consolidate-lock";
14356
14415
  var MAX_ENTRYPOINT_LINES = 200;
14357
14416
  var MemoryConsolidator = class {
14358
14417
  client;
14359
- workDir;
14418
+ cwd;
14360
14419
  lastScanAt = 0;
14361
14420
  minHours;
14362
14421
  minSessions;
14363
14422
  appendSystem;
14364
- constructor(client, workDir, opts) {
14423
+ constructor(client, cwd2, opts) {
14365
14424
  this.client = client;
14366
- this.workDir = workDir;
14425
+ this.cwd = cwd2;
14367
14426
  this.minHours = opts?.minHours ?? DEFAULT_MIN_HOURS;
14368
14427
  this.minSessions = opts?.minSessions ?? DEFAULT_MIN_SESSIONS;
14369
14428
  this.appendSystem = opts?.appendSystem;
@@ -14373,7 +14432,7 @@ var MemoryConsolidator = class {
14373
14432
  * Should be called when each agent loop completes.
14374
14433
  */
14375
14434
  maybeRun() {
14376
- const memDir = join15(this.workDir, ".yukino", "memory");
14435
+ const memDir = projectPath(this.cwd, "memory");
14377
14436
  if (!existsSync7(memDir)) {
14378
14437
  return Promise.resolve();
14379
14438
  }
@@ -14387,12 +14446,12 @@ var MemoryConsolidator = class {
14387
14446
  return Promise.resolve();
14388
14447
  }
14389
14448
  this.lastScanAt = now;
14390
- const sessionIDs = listSessionsSince(this.workDir, lastAt);
14449
+ const sessionIDs = listSessionsSince(this.cwd, lastAt);
14391
14450
  if (sessionIDs.length < this.minSessions) {
14392
14451
  return Promise.resolve();
14393
14452
  }
14394
14453
  const releaseLock = tryAcquireFileSyncLock(
14395
- join15(memDir, ".consolidate-running")
14454
+ join14(memDir, ".consolidate-running")
14396
14455
  );
14397
14456
  if (!releaseLock) {
14398
14457
  return Promise.resolve();
@@ -14407,8 +14466,8 @@ var MemoryConsolidator = class {
14407
14466
  return Promise.resolve();
14408
14467
  }
14409
14468
  async run(memDir, sessionIDs) {
14410
- const userMemDir = join15(homedir3(), ".yukino", "memory");
14411
- const transcriptDir = join15(this.workDir, ".yukino", "sessions");
14469
+ const userMemDir = yukinoPath("memory");
14470
+ const transcriptDir = getSessionsDir(this.cwd);
14412
14471
  const prompt = buildConsolidationPrompt(
14413
14472
  memDir,
14414
14473
  userMemDir,
@@ -14421,7 +14480,7 @@ var MemoryConsolidator = class {
14421
14480
  subRegistry.register(new EditFileTool());
14422
14481
  subRegistry.register(new GlobTool());
14423
14482
  subRegistry.register(new GrepTool());
14424
- const subChecker = new MemoryPermissionChecker(this.workDir, true);
14483
+ const subChecker = new MemoryPermissionChecker(this.cwd, true);
14425
14484
  const conv = new ConversationManager();
14426
14485
  conv.addUserMessage(prompt);
14427
14486
  const subagent = new Agent({
@@ -14429,7 +14488,7 @@ var MemoryConsolidator = class {
14429
14488
  registry: subRegistry,
14430
14489
  checker: subChecker,
14431
14490
  conversation: conv,
14432
- workDir: this.workDir,
14491
+ cwd: this.cwd,
14433
14492
  fileStateCache: new FileStateCache(),
14434
14493
  maxIterations: 15
14435
14494
  });
@@ -14447,7 +14506,7 @@ var MemoryConsolidator = class {
14447
14506
  }
14448
14507
  };
14449
14508
  function lockPath(memDir) {
14450
- return join15(memDir, LOCK_FILE);
14509
+ return join14(memDir, LOCK_FILE);
14451
14510
  }
14452
14511
  function readLastConsolidatedAt(memDir) {
14453
14512
  const path = lockPath(memDir);
@@ -14467,8 +14526,8 @@ function markConsolidationSucceeded(memDir) {
14467
14526
  log21.error({ err }, "failed to update consolidation timestamp");
14468
14527
  }
14469
14528
  }
14470
- function listSessionsSince(workDir, sinceMs) {
14471
- const sessions = listSessions(workDir);
14529
+ function listSessionsSince(cwd2, sinceMs) {
14530
+ const sessions = listSessions(cwd2);
14472
14531
  const since = new Date(sinceMs);
14473
14532
  return sessions.filter((s) => s.modTime > since).map((s) => s.id);
14474
14533
  }
@@ -14527,8 +14586,7 @@ import {
14527
14586
  mkdirSync as mkdirSync7,
14528
14587
  writeFileSync as writeFileSync7
14529
14588
  } from "fs";
14530
- import { homedir as homedir5 } from "os";
14531
- import { join as join17, basename as basename5 } from "path";
14589
+ import { join as join16, basename as basename5 } from "path";
14532
14590
  import yaml3 from "js-yaml";
14533
14591
 
14534
14592
  // src/memory/manager.ts
@@ -14548,8 +14606,7 @@ import {
14548
14606
  writeFileSync as writeFileSync6,
14549
14607
  statSync as statSync9
14550
14608
  } from "fs";
14551
- import { homedir as homedir4 } from "os";
14552
- import { join as join16, relative as relative3, basename as basename4 } from "path";
14609
+ import { join as join15, relative as relative3, basename as basename4 } from "path";
14553
14610
  import yaml2 from "js-yaml";
14554
14611
  import z14, { parse as parse4 } from "zod";
14555
14612
 
@@ -14625,9 +14682,9 @@ var MemoryManager = class {
14625
14682
  userDir;
14626
14683
  projectDir;
14627
14684
  malformedFingerprints = /* @__PURE__ */ new Map();
14628
- constructor(workDir) {
14629
- this.userDir = join16(homedir4(), ".yukino", "memory");
14630
- this.projectDir = join16(workDir, ".yukino", "memory");
14685
+ constructor(cwd2) {
14686
+ this.userDir = yukinoPath("memory");
14687
+ this.projectDir = projectPath(cwd2, "memory");
14631
14688
  }
14632
14689
  readMemory(fullPath) {
14633
14690
  let fingerprint = "unknown";
@@ -14670,7 +14727,7 @@ var MemoryManager = class {
14670
14727
  continue;
14671
14728
  }
14672
14729
  for (const file of files) {
14673
- const loaded = this.readMemory(join16(dir, file));
14730
+ const loaded = this.readMemory(join15(dir, file));
14674
14731
  if (loaded) {
14675
14732
  memories.push(loaded.memory);
14676
14733
  }
@@ -14740,7 +14797,7 @@ ${body}
14740
14797
  const files = readdirSync3(dir).filter((f) => f.endsWith(".md"));
14741
14798
  for (const file of files) {
14742
14799
  try {
14743
- unlinkSync4(join16(dir, file));
14800
+ unlinkSync4(join15(dir, file));
14744
14801
  } catch (err) {
14745
14802
  log22.error({ err }, "memory operation failed");
14746
14803
  continue;
@@ -14769,7 +14826,7 @@ ${body}
14769
14826
  (entry) => entry.description ? `- [${entry.name}](${entry.relPath}) \u2014 ${entry.description}` : `- [${entry.name}](${entry.relPath})`
14770
14827
  );
14771
14828
  const content = capEntrypoint(lines.slice(0, MAX_ENTRYPOINT_LINES2).join("\n")) + "\n";
14772
- const indexPath = join16(this.projectDir, MEMORY_INDEX_NAME);
14829
+ const indexPath = join15(this.projectDir, MEMORY_INDEX_NAME);
14773
14830
  withFileSyncLock(indexPath, () => {
14774
14831
  mkdirSync6(this.projectDir, { recursive: true });
14775
14832
  if (existsSync8(indexPath)) {
@@ -14892,7 +14949,7 @@ ${manifest}${toolsSection}`;
14892
14949
  }
14893
14950
  const headers = [];
14894
14951
  for (const file of files) {
14895
- const loaded = this.readMemory(join16(dir, file));
14952
+ const loaded = this.readMemory(join15(dir, file));
14896
14953
  if (!loaded) {
14897
14954
  continue;
14898
14955
  }
@@ -15000,12 +15057,12 @@ function parseFrontmatter(content) {
15000
15057
  // src/memory/extractor.ts
15001
15058
  var MemoryExtractor = class {
15002
15059
  client;
15003
- workDir;
15060
+ cwd;
15004
15061
  inProgress = false;
15005
15062
  pendingContext = null;
15006
- constructor(client, workDir) {
15063
+ constructor(client, cwd2) {
15007
15064
  this.client = client;
15008
- this.workDir = workDir;
15065
+ this.cwd = cwd2;
15009
15066
  }
15010
15067
  async extract(conversationSummary) {
15011
15068
  if (this.inProgress) {
@@ -15042,10 +15099,7 @@ var MemoryExtractor = class {
15042
15099
  }
15043
15100
  /** Scan existing memory files and build a manifest for LLM deduplication */
15044
15101
  scanExistingMemories() {
15045
- const dirs = [
15046
- join17(this.workDir, ".yukino", "memory"),
15047
- join17(homedir5(), ".yukino", "memory")
15048
- ];
15102
+ const dirs = [projectPath(this.cwd, "memory"), yukinoPath("memory")];
15049
15103
  const entries = [];
15050
15104
  for (const dir of dirs) {
15051
15105
  if (!existsSync9(dir)) {
@@ -15057,7 +15111,7 @@ var MemoryExtractor = class {
15057
15111
  );
15058
15112
  for (const file of files) {
15059
15113
  try {
15060
- const content = readFileSync7(join17(dir, file), "utf-8");
15114
+ const content = readFileSync7(join16(dir, file), "utf-8");
15061
15115
  const typeMatch = /^\s*type:\s*"?([^"\n]+?)"?\s*$/m.exec(content);
15062
15116
  const descMatch = /^\s*description:\s*"?([^"\n]+?)"?\s*$/m.exec(
15063
15117
  content
@@ -15075,8 +15129,8 @@ var MemoryExtractor = class {
15075
15129
  }
15076
15130
  buildExtractionPrompt(conversationSummary) {
15077
15131
  const manifest = this.scanExistingMemories();
15078
- const projectMemDir = join17(this.workDir, ".yukino", "memory");
15079
- const userMemDir = join17(homedir5(), ".yukino", "memory");
15132
+ const projectMemDir = projectPath(this.cwd, "memory");
15133
+ const userMemDir = yukinoPath("memory");
15080
15134
  return [
15081
15135
  "# Task",
15082
15136
  "Extract durable memories from the conversation only; do not investigate source code. Update existing topics instead of creating duplicates. If nothing is worth saving, do nothing.",
@@ -15114,7 +15168,7 @@ var MemoryExtractor = class {
15114
15168
  subRegistry.register(new EditFileTool());
15115
15169
  subRegistry.register(new GlobTool());
15116
15170
  subRegistry.register(new GrepTool());
15117
- const subChecker = new MemoryPermissionChecker(this.workDir);
15171
+ const subChecker = new MemoryPermissionChecker(this.cwd);
15118
15172
  const forkedConv = new ConversationManager();
15119
15173
  forkedConv.addUserMessage(extractionPrompt);
15120
15174
  const subagent = new Agent({
@@ -15122,7 +15176,7 @@ var MemoryExtractor = class {
15122
15176
  registry: subRegistry,
15123
15177
  checker: subChecker,
15124
15178
  conversation: forkedConv,
15125
- workDir: this.workDir,
15179
+ cwd: this.cwd,
15126
15180
  fileStateCache: new FileStateCache(),
15127
15181
  maxIterations: 5
15128
15182
  });
@@ -15144,7 +15198,7 @@ var MemoryExtractor = class {
15144
15198
  saved = this.persistTextMemories(streamedText);
15145
15199
  }
15146
15200
  if (saved.length > 0) {
15147
- const mgr = new MemoryManager(this.workDir);
15201
+ const mgr = new MemoryManager(this.cwd);
15148
15202
  mgr.rebuildIndex();
15149
15203
  }
15150
15204
  return saved;
@@ -15163,8 +15217,8 @@ var MemoryExtractor = class {
15163
15217
  const saved = [];
15164
15218
  for (const mem of memories) {
15165
15219
  const dir = this.dirForMemoryType(mem.type);
15166
- const filePath = join17(dir, `${mem.name}.md`);
15167
- if (new MemoryPermissionChecker(this.workDir).check("WriteFile", "write", {
15220
+ const filePath = join16(dir, `${mem.name}.md`);
15221
+ if (new MemoryPermissionChecker(this.cwd).check("WriteFile", "write", {
15168
15222
  file_path: filePath
15169
15223
  }).effect !== "allow") {
15170
15224
  continue;
@@ -15245,9 +15299,9 @@ var MemoryExtractor = class {
15245
15299
  dirForMemoryType(type) {
15246
15300
  const t = type.toLowerCase();
15247
15301
  if (t === "user" || t === "feedback") {
15248
- return join17(homedir5(), ".yukino", "memory");
15302
+ return yukinoPath("memory");
15249
15303
  }
15250
- return join17(this.workDir, ".yukino", "memory");
15304
+ return projectPath(this.cwd, "memory");
15251
15305
  }
15252
15306
  /** Format a memory file: frontmatter (name/description/type) + body */
15253
15307
  formatMemoryFile(mem) {
@@ -15270,12 +15324,12 @@ __export(instructions_exports2, {
15270
15324
  loadInstructions: () => loadInstructions
15271
15325
  });
15272
15326
  import { readFileSync as readFileSync8, existsSync as existsSync10 } from "fs";
15273
- import { homedir as homedir6 } from "os";
15274
- import { join as join18, dirname as dirname6, resolve as resolve7, isAbsolute as isAbsolute3, relative as relative4 } from "path";
15327
+ import { homedir } from "os";
15328
+ import { join as join17, dirname as dirname6, resolve as resolve7, isAbsolute as isAbsolute3, relative as relative4 } from "path";
15275
15329
  var log23 = createChildLogger({ module: "memory" });
15276
15330
  var MAX_INCLUDE_DEPTH = 5;
15277
- function loadInstructions(workDir) {
15278
- const sources = discoverInstructions(workDir);
15331
+ function loadInstructions(cwd2) {
15332
+ const sources = discoverInstructions(cwd2);
15279
15333
  if (sources.length === 0) {
15280
15334
  return "";
15281
15335
  }
@@ -15283,7 +15337,7 @@ function loadInstructions(workDir) {
15283
15337
  for (const s of sources) {
15284
15338
  let label = s.path;
15285
15339
  try {
15286
- const rel = relative4(workDir, s.path);
15340
+ const rel = relative4(cwd2, s.path);
15287
15341
  if (!rel.startsWith("..")) {
15288
15342
  label = rel;
15289
15343
  }
@@ -15296,19 +15350,17 @@ ${s.content.replace(/\n+$/, "")}`);
15296
15350
  }
15297
15351
  return parts.join("\n\n---\n\n");
15298
15352
  }
15299
- function discoverInstructions(workDir) {
15353
+ function discoverInstructions(cwd2) {
15300
15354
  const sources = [];
15301
15355
  const seen = /* @__PURE__ */ new Set();
15302
15356
  try {
15303
- const home = homedir6();
15304
- addSource(sources, seen, join18(home, ".yukino", "AGENTS.md"));
15357
+ addSource(sources, seen, yukinoPath("AGENTS.md"));
15305
15358
  } catch (err) {
15306
15359
  log23.error({ err }, "memory operation failed");
15307
15360
  }
15308
- const dirs = projectInstructionDirs(workDir);
15361
+ const dirs = projectInstructionDirs(cwd2);
15309
15362
  for (const dir of dirs) {
15310
- addSource(sources, seen, join18(dir, "AGENTS.md"));
15311
- addSource(sources, seen, join18(dir, ".yukino", "AGENTS.md"));
15363
+ addSource(sources, seen, join17(dir, "AGENTS.md"));
15312
15364
  }
15313
15365
  return sources;
15314
15366
  }
@@ -15413,7 +15465,7 @@ function parseInclude(trimmed) {
15413
15465
  function resolveInclude(p, baseDir) {
15414
15466
  if (p.startsWith("~/")) {
15415
15467
  try {
15416
- return join18(homedir6(), p.slice(2));
15468
+ return join17(homedir(), p.slice(2));
15417
15469
  } catch (err) {
15418
15470
  log23.error({ err }, "memory operation failed");
15419
15471
  return "";
@@ -15422,15 +15474,15 @@ function resolveInclude(p, baseDir) {
15422
15474
  if (isAbsolute3(p)) {
15423
15475
  return p;
15424
15476
  }
15425
- return join18(baseDir, p);
15477
+ return join17(baseDir, p);
15426
15478
  }
15427
- function projectInstructionDirs(workDir) {
15479
+ function projectInstructionDirs(cwd2) {
15428
15480
  let abs;
15429
15481
  try {
15430
- abs = resolve7(workDir);
15482
+ abs = resolve7(cwd2);
15431
15483
  } catch (err) {
15432
15484
  log23.error({ err }, "memory operation failed");
15433
- return [workDir];
15485
+ return [cwd2];
15434
15486
  }
15435
15487
  const root = findGitRoot(abs);
15436
15488
  if (!root) {
@@ -15455,7 +15507,7 @@ function findGitRoot(start) {
15455
15507
  let cur = start;
15456
15508
  while (true) {
15457
15509
  try {
15458
- const gitPath = join18(cur, ".git");
15510
+ const gitPath = join17(cur, ".git");
15459
15511
  if (existsSync10(gitPath)) {
15460
15512
  return cur;
15461
15513
  }
@@ -15557,7 +15609,7 @@ The user may not see tool calls. Before starting, give a one-sentence plan; at m
15557
15609
  function environmentSection(env) {
15558
15610
  const lines = [
15559
15611
  "# Environment",
15560
- ` - Working directory: ${env.workDir}`,
15612
+ ` - Working directory: ${env.cwd}`,
15561
15613
  ` - Platform: ${env.os}/${env.arch}`,
15562
15614
  ` - Shell: ${env.shell}`,
15563
15615
  ` - Git repository: ${env.isGitRepo ? "true" : "false"}`
@@ -15588,9 +15640,9 @@ var PromptBuilder = class {
15588
15640
  return [...new Set(contents)].join("\n\n");
15589
15641
  }
15590
15642
  };
15591
- function detectEnvironment(workDir) {
15643
+ function detectEnvironment(cwd2) {
15592
15644
  const env = {
15593
- workDir,
15645
+ cwd: cwd2,
15594
15646
  os: platform(),
15595
15647
  arch: arch(),
15596
15648
  shell: process.env.SHELL ?? "bash",
@@ -15601,14 +15653,14 @@ function detectEnvironment(workDir) {
15601
15653
  };
15602
15654
  try {
15603
15655
  const result = execSync("git rev-parse --is-inside-work-tree", {
15604
- cwd: workDir,
15656
+ cwd: cwd2,
15605
15657
  stdio: ["pipe", "pipe", "pipe"],
15606
15658
  encoding: "utf-8"
15607
15659
  }).trim();
15608
15660
  if (result === "true") {
15609
15661
  env.isGitRepo = true;
15610
15662
  env.gitBranch = execSync("git rev-parse --abbrev-ref HEAD", {
15611
- cwd: workDir,
15663
+ cwd: cwd2,
15612
15664
  stdio: ["pipe", "pipe", "pipe"],
15613
15665
  encoding: "utf-8"
15614
15666
  }).trim();
@@ -15668,11 +15720,11 @@ ${task}
15668
15720
 
15669
15721
  // src/subagent/spawn.ts
15670
15722
  var SUBAGENT_INTERRUPTED_MARKER = "[Interrupted]";
15671
- async function spawnSubagent(definition, prompt, parentClient, parentRegistry, parentProvider, workDir, onProgress, onEvent, modelOverride, checkerOverride, options = {}) {
15723
+ async function spawnSubagent(definition, prompt, parentClient, parentRegistry, parentProvider, cwd2, onProgress, onEvent, modelOverride, checkerOverride, options = {}) {
15672
15724
  options.abortSignal?.throwIfAborted();
15673
15725
  const effectiveModel = modelOverride ?? definition.model;
15674
15726
  const resolvedModel = effectiveModel ?? parentProvider.model;
15675
- const env = detectEnvironment(workDir);
15727
+ const env = detectEnvironment(cwd2);
15676
15728
  env.model = resolvedModel;
15677
15729
  const systemPrompt = definition.systemPromptOverride ?? buildSystemPrompt(env);
15678
15730
  const provider = {
@@ -15692,10 +15744,10 @@ async function spawnSubagent(definition, prompt, parentClient, parentRegistry, p
15692
15744
  let turn = 0;
15693
15745
  try {
15694
15746
  const inheritedChecker = checkerOverride ?? new PermissionChecker(
15695
- workDir,
15747
+ cwd2,
15696
15748
  options.permissionMode ?? definition.permissionMode
15697
15749
  );
15698
- const checker = inheritedChecker.forSubagent(workDir);
15750
+ const checker = inheritedChecker.forSubagent(cwd2);
15699
15751
  if (definition.permissionMode === "plan") {
15700
15752
  checker.planModeLocked = true;
15701
15753
  }
@@ -15709,12 +15761,12 @@ async function spawnSubagent(definition, prompt, parentClient, parentRegistry, p
15709
15761
  registry,
15710
15762
  checker,
15711
15763
  conversation,
15712
- workDir,
15764
+ cwd: cwd2,
15713
15765
  maxIterations: definition.maxTurns ?? 200,
15714
15766
  abortSignal: options.abortSignal,
15715
15767
  onPermissionRequest: options.onPermissionRequest,
15716
15768
  fileStateCache: new FileStateCache(),
15717
- instructions: loadInstructions(workDir),
15769
+ instructions: loadInstructions(cwd2),
15718
15770
  contextWindow: getContextWindow(provider),
15719
15771
  maxOutput: getMaxOutputTokens(provider),
15720
15772
  taskManager,
@@ -15828,7 +15880,7 @@ __export(teams_exports, {
15828
15880
  import { randomBytes as randomBytes4 } from "crypto";
15829
15881
  import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11, rmSync as rmSync7 } from "fs";
15830
15882
  import { createRequire } from "module";
15831
- import { dirname as dirname8, join as join20 } from "path";
15883
+ import { dirname as dirname8, join as join19 } from "path";
15832
15884
 
15833
15885
  // src/teams/backend.ts
15834
15886
  var backend_exports = {};
@@ -15970,7 +16022,7 @@ import {
15970
16022
  existsSync as existsSync11,
15971
16023
  rmSync as rmSync5
15972
16024
  } from "fs";
15973
- import { join as join19 } from "path";
16025
+ import { join as join18 } from "path";
15974
16026
  import z15 from "zod";
15975
16027
  var log26 = createChildLogger({ module: "teams" });
15976
16028
  var FileMailMessageSchema = z15.object({
@@ -15995,7 +16047,7 @@ var FileMailbox = class {
15995
16047
  throw new Error("Invalid mailbox member name");
15996
16048
  }
15997
16049
  mkdirSync8(dir, { recursive: true });
15998
- this.filePath = join19(dir, `${memberName}.json`);
16050
+ this.filePath = join18(dir, `${memberName}.json`);
15999
16051
  }
16000
16052
  readAll() {
16001
16053
  if (!existsSync11(this.filePath)) {
@@ -16521,7 +16573,7 @@ var Team = class _Team {
16521
16573
  members = /* @__PURE__ */ new Map();
16522
16574
  leaderMailbox;
16523
16575
  mailboxDir;
16524
- workDir;
16576
+ cwd;
16525
16577
  lastLivenessCheck = 0;
16526
16578
  leaderAgentId = "";
16527
16579
  permissionMode = "default";
@@ -16533,11 +16585,11 @@ var Team = class _Team {
16533
16585
  * restarted leader re-claims it when the team is restored from disk.
16534
16586
  */
16535
16587
  leaderPid = 0;
16536
- constructor(name, mode2, workDir) {
16588
+ constructor(name, mode2, cwd2) {
16537
16589
  this.name = name;
16538
16590
  this.mode = mode2;
16539
- this.workDir = workDir;
16540
- this.mailboxDir = join20(teamDir(workDir, name), "inboxes");
16591
+ this.cwd = cwd2;
16592
+ this.mailboxDir = join19(teamDir(cwd2, name), "inboxes");
16541
16593
  mkdirSync10(this.mailboxDir, { recursive: true });
16542
16594
  this.leaderMailbox = new FileMailbox(this.mailboxDir, LEADER_NAME);
16543
16595
  }
@@ -16569,7 +16621,7 @@ var Team = class _Team {
16569
16621
  }
16570
16622
  if (this.members.delete(name)) {
16571
16623
  getNameRegistry().unregister(name);
16572
- writeTeamFile(this.workDir, this.name, this.snapshot(), [name]);
16624
+ writeTeamFile(this.cwd, this.name, this.snapshot(), [name]);
16573
16625
  }
16574
16626
  }
16575
16627
  /** Reconstructs a persisted member without writing a partial team snapshot. */
@@ -16643,7 +16695,7 @@ var Team = class _Team {
16643
16695
  * continuity, not runtime correctness.
16644
16696
  */
16645
16697
  persist() {
16646
- writeTeamFile(this.workDir, this.name, this.snapshot());
16698
+ writeTeamFile(this.cwd, this.name, this.snapshot());
16647
16699
  }
16648
16700
  static IDLE_POLL_INTERVAL_MS = 500;
16649
16701
  // Grace period after the shutdown notice before force-killing an external
@@ -16661,7 +16713,7 @@ var Team = class _Team {
16661
16713
  * Falls back to in-process when the external backend is unavailable (tmux not installed,
16662
16714
  * non-iTerm environment, etc.) to avoid crashes.
16663
16715
  */
16664
- spawnTeammate(name, task, runAgent, checker, providerIndex, originToolCallId, memberWorkDir = this.workDir, role = {}) {
16716
+ spawnTeammate(name, task, runAgent, checker, providerIndex, originToolCallId, memberCwd = this.cwd, role = {}) {
16665
16717
  const member = this.getMember(name) ?? this.addMember(name);
16666
16718
  if (member.active) {
16667
16719
  throw new Error(`Teammate '${name}' is already running`);
@@ -16677,7 +16729,7 @@ var Team = class _Team {
16677
16729
  runAgent,
16678
16730
  checker,
16679
16731
  originToolCallId,
16680
- memberWorkDir,
16732
+ memberCwd,
16681
16733
  role.cleanup
16682
16734
  );
16683
16735
  return "in-process";
@@ -16689,7 +16741,7 @@ var Team = class _Team {
16689
16741
  task,
16690
16742
  providerIndex,
16691
16743
  originToolCallId,
16692
- memberWorkDir,
16744
+ memberCwd,
16693
16745
  role
16694
16746
  );
16695
16747
  return mode2;
@@ -16700,7 +16752,7 @@ var Team = class _Team {
16700
16752
  runAgent,
16701
16753
  checker,
16702
16754
  originToolCallId,
16703
- memberWorkDir,
16755
+ memberCwd,
16704
16756
  role.cleanup
16705
16757
  );
16706
16758
  return "in-process";
@@ -16712,7 +16764,7 @@ var Team = class _Team {
16712
16764
  * by `--team-dir`; task assignments from the leader and idle/result notifications from the
16713
16765
  * worker all land in this directory, keeping both sides in sync.
16714
16766
  */
16715
- spawnExternal(mode2, name, task, providerIndex, originToolCallId, memberWorkDir = this.workDir, role = {}) {
16767
+ spawnExternal(mode2, name, task, providerIndex, originToolCallId, memberCwd = this.cwd, role = {}) {
16716
16768
  const member = this.getMember(name) ?? this.addMember(name);
16717
16769
  member.stopping = void 0;
16718
16770
  member.done = void 0;
@@ -16721,7 +16773,7 @@ var Team = class _Team {
16721
16773
  member.backendType = mode2;
16722
16774
  member.external = true;
16723
16775
  member.paneId = mode2 === "tmux" ? `yukino-${randomBytes4(8).toString("hex")}` : void 0;
16724
- member.worktreePath = memberWorkDir === this.workDir ? void 0 : memberWorkDir;
16776
+ member.worktreePath = memberCwd === this.cwd ? void 0 : memberCwd;
16725
16777
  this.persist();
16726
16778
  getNameRegistry().register(name, name);
16727
16779
  member.uiState = {
@@ -16737,9 +16789,9 @@ var Team = class _Team {
16737
16789
  const packageDir = dirname8(
16738
16790
  require2.resolve("@yukino.js/yukino/package.json")
16739
16791
  );
16740
- const sourceEntry = join20(packageDir, "src", "main.tsx");
16792
+ const sourceEntry = join19(packageDir, "src", "cli.ts");
16741
16793
  const sourceRuntime = existsSync13(sourceEntry);
16742
- const entry = sourceRuntime ? sourceEntry : join20(packageDir, "dist", "main.js");
16794
+ const entry = sourceRuntime ? sourceEntry : join19(packageDir, "dist", "main.js");
16743
16795
  const config = {
16744
16796
  mode: mode2,
16745
16797
  command: process.execPath,
@@ -16751,8 +16803,8 @@ var Team = class _Team {
16751
16803
  this.mailboxDir,
16752
16804
  "--team-name",
16753
16805
  this.name,
16754
- "--team-work-dir",
16755
- this.workDir,
16806
+ "--team-cwd",
16807
+ this.cwd,
16756
16808
  "--member-name",
16757
16809
  name,
16758
16810
  "--task",
@@ -16763,7 +16815,7 @@ var Team = class _Team {
16763
16815
  ...role.model ? ["--model", role.model] : [],
16764
16816
  ...providerIndex !== void 0 ? ["--provider-index", String(providerIndex)] : []
16765
16817
  ],
16766
- cwd: memberWorkDir,
16818
+ cwd: memberCwd,
16767
16819
  paneId: member.paneId
16768
16820
  };
16769
16821
  const { cancel, paneId } = spawnTeammate(config);
@@ -16778,17 +16830,17 @@ var Team = class _Team {
16778
16830
  * Exits the loop upon receiving a shutdown message or being canceled.
16779
16831
  * Uses the idle-poll-continue pattern: after each turn completes, reports idle and waits for the next task.
16780
16832
  */
16781
- spawnInProcess(name, task, runAgent, checker, originToolCallId, memberWorkDir = this.workDir, cleanup) {
16833
+ spawnInProcess(name, task, runAgent, checker, originToolCallId, memberCwd = this.cwd, cleanup) {
16782
16834
  const member = this.getMember(name) ?? this.addMember(name);
16783
16835
  if (checker?.planModeLocked && !checker.planFilePath) {
16784
- checker.planFilePath = createPlanPath(memberWorkDir);
16836
+ checker.planFilePath = createPlanPath();
16785
16837
  }
16786
16838
  member.active = true;
16787
16839
  member.backendType = "in-process";
16788
16840
  member.external = false;
16789
16841
  member.paneId = void 0;
16790
16842
  member.workerPid = void 0;
16791
- member.worktreePath = memberWorkDir === this.workDir ? void 0 : memberWorkDir;
16843
+ member.worktreePath = memberCwd === this.cwd ? void 0 : memberCwd;
16792
16844
  this.persist();
16793
16845
  member.checker = checker;
16794
16846
  const abortController = new AbortController();
@@ -17048,7 +17100,7 @@ Please revise the plan accordingly and resubmit.`;
17048
17100
  releaseMemberTasks(member) {
17049
17101
  try {
17050
17102
  const store = new SharedTaskStore(
17051
- join20(teamDir(this.workDir, this.name), "tasks.json")
17103
+ join19(teamDir(this.cwd, this.name), "tasks.json")
17052
17104
  );
17053
17105
  const tasks = store.releaseOwner(member.name);
17054
17106
  if (tasks.length) {
@@ -17120,7 +17172,7 @@ Please revise the plan accordingly and resubmit.`;
17120
17172
  }
17121
17173
  }
17122
17174
  if (member.external && member.backendType === "iterm") {
17123
- const pid = readTeamFile(this.workDir, this.name)?.members.find(
17175
+ const pid = readTeamFile(this.cwd, this.name)?.members.find(
17124
17176
  (entry) => entry.name === member.name
17125
17177
  )?.workerPid;
17126
17178
  if (pid && pid !== process.pid && isProcessAlive(pid)) {
@@ -17170,7 +17222,7 @@ Please revise the plan accordingly and resubmit.`;
17170
17222
  return;
17171
17223
  }
17172
17224
  this.lastLivenessCheck = now;
17173
- const config = readTeamFile(this.workDir, this.name);
17225
+ const config = readTeamFile(this.cwd, this.name);
17174
17226
  for (const member of this.members.values()) {
17175
17227
  if (!member.external || !member.active) {
17176
17228
  continue;
@@ -17220,7 +17272,7 @@ Please revise the plan accordingly and resubmit.`;
17220
17272
  this.members.delete(member.name);
17221
17273
  }
17222
17274
  writeTeamFile(
17223
- this.workDir,
17275
+ this.cwd,
17224
17276
  this.name,
17225
17277
  this.snapshot(),
17226
17278
  removed.map((member) => member.name)
@@ -17230,14 +17282,14 @@ Please revise the plan accordingly and resubmit.`;
17230
17282
  var TeamManager = class {
17231
17283
  /** Teams keyed by their canonical disk slug; Team.name remains the display name. */
17232
17284
  teams = /* @__PURE__ */ new Map();
17233
- workDir;
17285
+ cwd;
17234
17286
  claimLeadership;
17235
17287
  permissionChecker;
17236
17288
  unsubscribePermissions;
17237
17289
  // One shared task store per canonical team identity.
17238
17290
  taskStores = /* @__PURE__ */ new Map();
17239
- constructor(workDir, opts = {}) {
17240
- this.workDir = canonicalPath(workDir);
17291
+ constructor(cwd2, opts = {}) {
17292
+ this.cwd = canonicalPath(cwd2);
17241
17293
  this.claimLeadership = opts.claimLeadership ?? true;
17242
17294
  }
17243
17295
  setPermissionChecker(checker) {
@@ -17259,7 +17311,7 @@ var TeamManager = class {
17259
17311
  return sanitizeTeamName(name);
17260
17312
  }
17261
17313
  teamDir(name) {
17262
- return teamDir(this.workDir, name);
17314
+ return teamDir(this.cwd, name);
17263
17315
  }
17264
17316
  create(name, mode2 = detectBackend(), opts = {}) {
17265
17317
  const existing = this.get(name);
@@ -17267,7 +17319,7 @@ var TeamManager = class {
17267
17319
  return existing;
17268
17320
  }
17269
17321
  const key = this.teamKey(name);
17270
- const team = new Team(name, mode2, this.workDir);
17322
+ const team = new Team(name, mode2, this.cwd);
17271
17323
  team.permissionMode = this.permissionChecker?.delegatedMode ?? "default";
17272
17324
  team.leaderAgentId = opts.leaderAgentId ?? "";
17273
17325
  team.description = opts.description;
@@ -17275,7 +17327,7 @@ var TeamManager = class {
17275
17327
  team.leaderPid = process.pid;
17276
17328
  }
17277
17329
  this.teams.set(key, team);
17278
- const store = new SharedTaskStore(join20(this.teamDir(name), "tasks.json"));
17330
+ const store = new SharedTaskStore(join19(this.teamDir(name), "tasks.json"));
17279
17331
  store.initEmpty();
17280
17332
  this.taskStores.set(key, store);
17281
17333
  team.persist();
@@ -17293,14 +17345,14 @@ var TeamManager = class {
17293
17345
  if (cached && this.claimLeadership) {
17294
17346
  return cached;
17295
17347
  }
17296
- const tf = readTeamFile(this.workDir, name);
17348
+ const tf = readTeamFile(this.cwd, name);
17297
17349
  if (!tf) {
17298
17350
  if (!this.claimLeadership) {
17299
17351
  this.teams.delete(key);
17300
17352
  }
17301
17353
  return void 0;
17302
17354
  }
17303
- const team = new Team(tf.name, tf.mode, this.workDir);
17355
+ const team = new Team(tf.name, tf.mode, this.cwd);
17304
17356
  team.leaderAgentId = tf.leaderAgentId;
17305
17357
  team.permissionMode = this.permissionChecker?.delegatedMode ?? tf.permissionMode;
17306
17358
  team.description = tf.description;
@@ -17334,7 +17386,7 @@ var TeamManager = class {
17334
17386
  * teammates keep running, and their notifications are drained again.
17335
17387
  */
17336
17388
  restoreFromDisk() {
17337
- for (const name of listTeamNames(this.workDir)) {
17389
+ for (const name of listTeamNames(this.cwd)) {
17338
17390
  this.get(name);
17339
17391
  }
17340
17392
  }
@@ -17346,7 +17398,7 @@ var TeamManager = class {
17346
17398
  return cached;
17347
17399
  }
17348
17400
  const store = new SharedTaskStore(
17349
- join20(this.teamDir(teamName), "tasks.json")
17401
+ join19(this.teamDir(teamName), "tasks.json")
17350
17402
  );
17351
17403
  this.taskStores.set(key, store);
17352
17404
  return store;
@@ -17396,7 +17448,7 @@ var TeamManager = class {
17396
17448
  for (const team of this.list()) {
17397
17449
  await this.delete(team.name);
17398
17450
  }
17399
- for (const name of listTeamNames(this.workDir)) {
17451
+ for (const name of listTeamNames(this.cwd)) {
17400
17452
  await this.delete(name);
17401
17453
  }
17402
17454
  }
@@ -17799,8 +17851,8 @@ var CodeReviewStartSchema = z19.object({
17799
17851
  excludePatterns: z19.array(z19.string()).optional()
17800
17852
  });
17801
17853
  var FE_DIST = [
17802
- join21(import.meta.dirname, "fe", "dist"),
17803
- join21(import.meta.dirname, "..", "fe", "dist")
17854
+ join20(import.meta.dirname, "fe", "dist"),
17855
+ join20(import.meta.dirname, "..", "fe", "dist")
17804
17856
  ].find((directory) => existsSync14(directory));
17805
17857
  var MIME_TYPES = {
17806
17858
  ".html": "text/html; charset=utf-8",
@@ -17817,7 +17869,7 @@ function serveStatic(path) {
17817
17869
  return null;
17818
17870
  }
17819
17871
  const cleanPath = normalize(path).replace(/^(\.\.[/\\])+/, "");
17820
- const fullPath = join21(FE_DIST, cleanPath);
17872
+ const fullPath = join20(FE_DIST, cleanPath);
17821
17873
  if (!fullPath.startsWith(FE_DIST)) {
17822
17874
  return null;
17823
17875
  }
@@ -17836,7 +17888,7 @@ var AgentHandleImpl = class {
17836
17888
  sessionGoal;
17837
17889
  get goalManager() {
17838
17890
  if (this.sessionGoal?.sessionId !== this.sessionId) {
17839
- this.sessionGoal = new GoalManager(this.workDir, this.sessionId);
17891
+ this.sessionGoal = new GoalManager(this.cwd, this.sessionId);
17840
17892
  }
17841
17893
  return this.sessionGoal;
17842
17894
  }
@@ -17866,7 +17918,7 @@ var AgentHandleImpl = class {
17866
17918
  longTermMemoryInstructions;
17867
17919
  longTermMemoryMemoryContent;
17868
17920
  provider;
17869
- workDir;
17921
+ cwd;
17870
17922
  checker;
17871
17923
  get planFilePath() {
17872
17924
  return this.checker.planFilePath;
@@ -17917,8 +17969,8 @@ var AgentHandleImpl = class {
17917
17969
  this.longTermMemoryInstructions = agentHandleImpl.longTermMemoryInstructions;
17918
17970
  this.longTermMemoryMemoryContent = agentHandleImpl.longTermMemoryMemoryContent;
17919
17971
  this.provider = agentHandleImpl.provider;
17920
- this.workDir = agentHandleImpl.workDir;
17921
- this.checker = new PermissionChecker(this.workDir);
17972
+ this.cwd = agentHandleImpl.cwd;
17973
+ this.checker = new PermissionChecker(this.cwd);
17922
17974
  this.checker.sandboxEnabled = this.registry.getInstanceOf("Bash", BashTool)?.sandboxRequired ?? false;
17923
17975
  this.teamManager.setPermissionChecker(this.checker);
17924
17976
  this.taskList = agentHandleImpl.taskList;
@@ -17948,7 +18000,7 @@ var AgentHandleImpl = class {
17948
18000
  registry: this.registry,
17949
18001
  checker,
17950
18002
  conversation: this.conv,
17951
- workDir: this.workDir,
18003
+ cwd: this.cwd,
17952
18004
  sessionId: this.sessionId,
17953
18005
  goalManager: this.goalManager,
17954
18006
  hookEngine: this.hookEngine ?? void 0,
@@ -17968,9 +18020,9 @@ var AgentHandleImpl = class {
17968
18020
  coordinatorActiveFn: () => coordinatorActive(this.enableCoordinatorMode),
17969
18021
  instructions: this.longTermMemoryInstructions,
17970
18022
  memoryContent: this.longTermMemoryMemoryContent,
17971
- skillSection: this.skillCatalog ? buildSkillSection(this.skillCatalog, this.workDir) : "",
18023
+ skillSection: this.skillCatalog ? buildSkillSection(this.skillCatalog) : "",
17972
18024
  skillDeltaFn: () => {
17973
- const section = this.skillCatalog ? buildSkillSection(this.skillCatalog, this.workDir) : "";
18025
+ const section = this.skillCatalog ? buildSkillSection(this.skillCatalog) : "";
17974
18026
  return section && !this.conv.hasReminderContaining(section) ? section : "";
17975
18027
  },
17976
18028
  notificationFn: () => [
@@ -17983,11 +18035,11 @@ var AgentHandleImpl = class {
17983
18035
  return;
17984
18036
  }
17985
18037
  const summary = conv.getMessages().slice(-40).map((m) => `[${m.role}]: ${contentToText(m.content)}`).filter((s) => s.length > 12).join("\n");
17986
- new MemoryExtractor(this.client, this.workDir).extract(summary).catch(() => {
18038
+ new MemoryExtractor(this.client, this.cwd).extract(summary).catch(() => {
17987
18039
  });
17988
18040
  this.memoryConsolidator ??= new MemoryConsolidator(
17989
18041
  this.client,
17990
- this.workDir,
18042
+ this.cwd,
17991
18043
  {
17992
18044
  appendSystem: (msg) => {
17993
18045
  this.conv.addSystemReminder(msg);
@@ -18025,9 +18077,9 @@ var AgentHandleImpl = class {
18025
18077
  this.activeSkills.clear();
18026
18078
  this.sessionId = newSessionId();
18027
18079
  this.planFilePath = "";
18028
- this.fileHistory = new FileHistory(this.workDir, this.sessionId);
18080
+ this.fileHistory = new FileHistory(this.sessionId);
18029
18081
  this.fileStateCache = new FileStateCache();
18030
- this.taskList.useStore(new TaskStore(this.workDir, this.sessionId));
18082
+ this.taskList.useStore(new TaskStore(this.sessionId));
18031
18083
  this.recoveryState = new RecoveryState();
18032
18084
  this.mcpAnnounced.clear();
18033
18085
  }
@@ -18035,7 +18087,7 @@ var AgentHandleImpl = class {
18035
18087
  async function createRemoteAgent(opts) {
18036
18088
  const {
18037
18089
  provider,
18038
- workDir,
18090
+ cwd: cwd2,
18039
18091
  hooks: hookConfigs,
18040
18092
  mcpServers: mcpConfigs,
18041
18093
  enableCoordinatorMode,
@@ -18048,26 +18100,26 @@ async function createRemoteAgent(opts) {
18048
18100
  if (hookErr) {
18049
18101
  throw hookErr;
18050
18102
  }
18051
- const fileHistory = new FileHistory(workDir, sessionId);
18103
+ const fileHistory = new FileHistory(sessionId);
18052
18104
  const fileStateCache = new FileStateCache();
18053
- const taskList = new TaskList(new TaskStore(workDir, sessionId));
18054
- const registry = createToolRegistry(workDir, taskList, {
18105
+ const taskList = new TaskList(new TaskStore(sessionId));
18106
+ const registry = createToolRegistry(cwd2, taskList, {
18055
18107
  lspServers: opts.lspServers
18056
18108
  });
18057
- await configureBashSandbox(registry, workDir, opts.sandboxConfig);
18058
- const env = detectEnvironment(workDir);
18109
+ await configureBashSandbox(registry, cwd2, opts.sandboxConfig);
18110
+ const env = detectEnvironment(cwd2);
18059
18111
  env.model = provider.model;
18060
18112
  const systemPrompt = buildSystemPrompt(env);
18061
18113
  const client = await createClient(provider, systemPrompt);
18062
18114
  const conv = new ConversationManager();
18063
18115
  const contextWindow = getContextWindow(provider);
18064
- const instructions = loadInstructions(workDir);
18065
- const memoryManager = new MemoryManager(workDir);
18116
+ const instructions = loadInstructions(cwd2);
18117
+ const memoryManager = new MemoryManager(cwd2);
18066
18118
  const memReminder = memoryEnabled2 ? memoryManager.buildSystemReminder() : "";
18067
18119
  conv.injectLongTermMemory(instructions, memReminder);
18068
18120
  const hookEngine = new HookEngine(hookConfigs ?? []);
18069
18121
  const catalog = new SkillCatalog();
18070
- catalog.load(workDir);
18122
+ catalog.load(cwd2);
18071
18123
  const activeSkills = /* @__PURE__ */ new Map();
18072
18124
  const skillHost = {
18073
18125
  activateSkill: (name, body) => {
@@ -18083,21 +18135,21 @@ async function createRemoteAgent(opts) {
18083
18135
  const msgs = conv.getMessages();
18084
18136
  return msgs.slice(-count).map((m) => `${m.role}: ${contentToText(m.content)}`).join("\n");
18085
18137
  },
18086
- runSubagent: (prompt, abortSignal, context) => spawnSubagent(
18138
+ runSubagent: (prompt, abortSignal, context2) => spawnSubagent(
18087
18139
  BUILTIN_AGENTS[0],
18088
18140
  prompt,
18089
18141
  client,
18090
18142
  registry,
18091
18143
  provider,
18092
- workDir,
18144
+ cwd2,
18093
18145
  void 0,
18094
18146
  void 0,
18095
18147
  void 0,
18096
- context?.permissionChecker?.forWorkDir(workDir) ?? handle.checker.forWorkDir(workDir),
18148
+ context2?.permissionChecker?.forCwd(cwd2) ?? handle.checker.forCwd(cwd2),
18097
18149
  {
18098
18150
  abortSignal,
18099
18151
  background: false,
18100
- onPermissionRequest: context?.onPermissionRequest
18152
+ onPermissionRequest: context2?.onPermissionRequest
18101
18153
  }
18102
18154
  )
18103
18155
  };
@@ -18105,7 +18157,7 @@ async function createRemoteAgent(opts) {
18105
18157
  if (askUser) {
18106
18158
  registry.register(new AskUserQuestionTool(askUser));
18107
18159
  }
18108
- const teamRunAgentFactory = (registry2, teamChecker, memberWorkDir = workDir, options) => {
18160
+ const teamRunAgentFactory = (registry2, teamChecker, memberCwd = cwd2, options) => {
18109
18161
  const conversation = new ConversationManager();
18110
18162
  return (task, onEvent, abortSignal) => spawnSubagent(
18111
18163
  options?.definition ?? BUILTIN_AGENTS[0],
@@ -18113,7 +18165,7 @@ async function createRemoteAgent(opts) {
18113
18165
  client,
18114
18166
  registry2,
18115
18167
  provider,
18116
- memberWorkDir,
18168
+ memberCwd,
18117
18169
  void 0,
18118
18170
  onEvent,
18119
18171
  options?.modelOverride,
@@ -18127,7 +18179,7 @@ async function createRemoteAgent(opts) {
18127
18179
  }
18128
18180
  );
18129
18181
  };
18130
- const teamManager = new TeamManager(workDir);
18182
+ const teamManager = new TeamManager(cwd2);
18131
18183
  registerLeaderTaskTools(registry, teamManager, taskList);
18132
18184
  teamManager.restoreFromDisk();
18133
18185
  const backgroundTaskManager = new TaskManager();
@@ -18138,40 +18190,40 @@ async function createRemoteAgent(opts) {
18138
18190
  registry.register(new TaskStopTool(teamManager, backgroundTaskManager));
18139
18191
  registry.register(new SyntheticOutputTool());
18140
18192
  const agentTool = new AgentTool(
18141
- workDir,
18193
+ cwd2,
18142
18194
  registry,
18143
- async (def, prompt, background, modelOverride, workDirOverride, context) => {
18195
+ async (def, prompt, background, modelOverride, cwdOverride, context2) => {
18144
18196
  return spawnSubagent(
18145
18197
  def,
18146
18198
  prompt,
18147
18199
  client,
18148
18200
  registry,
18149
18201
  provider,
18150
- workDirOverride ?? workDir,
18202
+ cwdOverride ?? cwd2,
18151
18203
  void 0,
18152
18204
  void 0,
18153
18205
  modelOverride,
18154
- workDirOverride ? context?.permissionChecker?.forWorkDir(workDirOverride) : context?.permissionChecker,
18206
+ cwdOverride ? context2?.permissionChecker?.forCwd(cwdOverride) : context2?.permissionChecker,
18155
18207
  {
18156
- abortSignal: context?.abortSignal,
18208
+ abortSignal: context2?.abortSignal,
18157
18209
  background,
18158
- onPermissionRequest: context?.onPermissionRequest,
18159
- permissionMode: context?.permissionChecker?.mode
18210
+ onPermissionRequest: context2?.onPermissionRequest,
18211
+ permissionMode: context2?.permissionChecker?.mode
18160
18212
  }
18161
18213
  );
18162
18214
  },
18163
18215
  conv,
18164
- async (prompt, forkConv, forkRegistry, modelOverride, context) => {
18165
- const forkWorkDir = context?.workDir ?? workDir;
18216
+ async (prompt, forkConv, forkRegistry, modelOverride, context2) => {
18217
+ const forkCwd = context2?.cwd ?? cwd2;
18166
18218
  const resolvedModel = modelOverride ?? provider.model;
18167
- const forkEnv = detectEnvironment(forkWorkDir);
18219
+ const forkEnv = detectEnvironment(forkCwd);
18168
18220
  forkEnv.model = resolvedModel;
18169
18221
  const forkSystemPrompt = buildSystemPrompt(forkEnv);
18170
18222
  const forkClient = modelOverride ? await createClient(
18171
18223
  { ...provider, model: resolvedModel },
18172
18224
  forkSystemPrompt
18173
18225
  ) : client;
18174
- const checker = (context?.permissionChecker ?? handle.checker).forSubagent(forkWorkDir);
18226
+ const checker = (context2?.permissionChecker ?? handle.checker).forSubagent(forkCwd);
18175
18227
  forkConv.addUserMessage(prompt);
18176
18228
  const forkTaskManager = new TaskManager();
18177
18229
  const agent2 = new Agent({
@@ -18179,12 +18231,12 @@ async function createRemoteAgent(opts) {
18179
18231
  registry: forkRegistry,
18180
18232
  checker,
18181
18233
  conversation: forkConv,
18182
- workDir: forkWorkDir,
18234
+ cwd: forkCwd,
18183
18235
  maxIterations: 200,
18184
- abortSignal: context?.abortSignal,
18185
- onPermissionRequest: context?.onPermissionRequest,
18236
+ abortSignal: context2?.abortSignal,
18237
+ onPermissionRequest: context2?.onPermissionRequest,
18186
18238
  fileStateCache: new FileStateCache(),
18187
- instructions: loadInstructions(forkWorkDir),
18239
+ instructions: loadInstructions(forkCwd),
18188
18240
  contextWindow: getContextWindow(provider),
18189
18241
  maxOutput: getMaxOutputTokens(provider),
18190
18242
  memoryContent: memReminder,
@@ -18218,7 +18270,7 @@ async function createRemoteAgent(opts) {
18218
18270
  agentTool.setTeamManager(teamManager, teamRunAgentFactory);
18219
18271
  registry.register(agentTool);
18220
18272
  const cmdRegistry = createDefaultRegistry();
18221
- for (const cmd of loadUserCommands(workDir)) {
18273
+ for (const cmd of loadUserCommands()) {
18222
18274
  try {
18223
18275
  cmdRegistry.register(cmd);
18224
18276
  } catch {
@@ -18272,7 +18324,7 @@ async function createRemoteAgent(opts) {
18272
18324
  longTermMemoryInstructions: instructions,
18273
18325
  longTermMemoryMemoryContent: memReminder,
18274
18326
  provider,
18275
- workDir,
18327
+ cwd: cwd2,
18276
18328
  taskList
18277
18329
  });
18278
18330
  handle.checker.sandboxAutoAllow = opts.sandboxConfig?.auto_allow ?? false;
@@ -18565,7 +18617,7 @@ var RemoteServer = class {
18565
18617
  try {
18566
18618
  const handle = await factory({
18567
18619
  provider: this.startProvider(),
18568
- workDir: cwd(),
18620
+ cwd: cwd(),
18569
18621
  hooks: this.opts.hookConfigs,
18570
18622
  mcpServers: this.opts.mcpServers,
18571
18623
  lspServers: this.opts.lspServers,
@@ -18628,9 +18680,9 @@ var RemoteServer = class {
18628
18680
  await this.handleSlashCommand(text);
18629
18681
  } else {
18630
18682
  const startTime = Date.now();
18631
- const workDir = handle.workDir;
18683
+ const cwd2 = handle.cwd;
18632
18684
  const sessionId = handle.sessionId;
18633
- saveMessage(workDir, sessionId, {
18685
+ saveMessage(cwd2, sessionId, {
18634
18686
  role: "user",
18635
18687
  content: text,
18636
18688
  timestamp: Math.floor(Date.now() / 1e3)
@@ -18857,9 +18909,9 @@ var RemoteServer = class {
18857
18909
  const displayText = args ? `/${name} ${args}` : `/${name}`;
18858
18910
  this.streaming = true;
18859
18911
  this.exitPlanSucceeded = false;
18860
- const workDir = handle.workDir;
18912
+ const cwd2 = handle.cwd;
18861
18913
  const sessionId = handle.sessionId;
18862
- saveMessage(workDir, sessionId, {
18914
+ saveMessage(cwd2, sessionId, {
18863
18915
  role: "user",
18864
18916
  content: displayText,
18865
18917
  timestamp: Math.floor(Date.now() / 1e3)
@@ -19037,10 +19089,10 @@ ${lines.join("\n")}`
19037
19089
  buildCommandContext(args) {
19038
19090
  const handle = this.agentHandle;
19039
19091
  if (!handle) {
19040
- return { workDir: cwd(), args, model: "" };
19092
+ return { cwd: cwd(), args, model: "" };
19041
19093
  }
19042
19094
  return {
19043
- workDir: handle.workDir,
19095
+ cwd: handle.cwd,
19044
19096
  args,
19045
19097
  permissionMode: () => handle.permissionMode,
19046
19098
  tokenCount: () => [0, 0],
@@ -19088,7 +19140,7 @@ ${lines.join("\n")}`
19088
19140
  handle.recoveryState,
19089
19141
  toolNames,
19090
19142
  toolSchemas,
19091
- getSessionFilePath(handle.workDir, handle.sessionId),
19143
+ getSessionFilePath(handle.cwd, handle.sessionId),
19092
19144
  controller.signal,
19093
19145
  customInstructions
19094
19146
  );
@@ -19097,7 +19149,7 @@ ${lines.join("\n")}`
19097
19149
  data: { message: `Compacted: ${result.message}` }
19098
19150
  });
19099
19151
  if (result.boundary) {
19100
- saveCompactBoundary(handle.workDir, handle.sessionId, result.boundary);
19152
+ saveCompactBoundary(handle.cwd, handle.sessionId, result.boundary);
19101
19153
  }
19102
19154
  } catch (err) {
19103
19155
  this.broadcast({
@@ -19116,8 +19168,8 @@ ${lines.join("\n")}`
19116
19168
  return;
19117
19169
  }
19118
19170
  const handle = this.agentHandle;
19119
- const workDir = handle.workDir;
19120
- const planPath = getOrCreatePlanPath(workDir, handle);
19171
+ const cwd2 = handle.cwd;
19172
+ const planPath = getOrCreatePlanPath(handle);
19121
19173
  if (handle.permissionMode !== "plan") {
19122
19174
  this.prePlanMode = handle.permissionMode;
19123
19175
  handle.permissionMode = "plan";
@@ -19130,7 +19182,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19130
19182
  }
19131
19183
  });
19132
19184
  this.broadcastStatus();
19133
- if (this.hasExitedPlanMode && planExists(workDir, handle)) {
19185
+ if (this.hasExitedPlanMode && planExists(handle)) {
19134
19186
  const reentryMsg = buildPlanModeReentryReminder(planPath, true);
19135
19187
  if (reentryMsg) {
19136
19188
  handle.conv.addSystemReminder(reentryMsg);
@@ -19142,7 +19194,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19142
19194
  this.streaming = true;
19143
19195
  this.exitPlanSucceeded = false;
19144
19196
  this.runCanceled = false;
19145
- saveMessage(workDir, handle.sessionId, {
19197
+ saveMessage(cwd2, handle.sessionId, {
19146
19198
  role: "user",
19147
19199
  content: `/plan ${args}`,
19148
19200
  timestamp: Math.floor(Date.now() / 1e3)
@@ -19207,7 +19259,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19207
19259
  data: { planPath: "", planContent: "" }
19208
19260
  };
19209
19261
  }
19210
- const planPath = getOrCreatePlanPath(handle.workDir, handle);
19262
+ const planPath = getOrCreatePlanPath(handle);
19211
19263
  let planContent = "";
19212
19264
  try {
19213
19265
  if (existsSync14(planPath)) {
@@ -19263,8 +19315,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19263
19315
  }
19264
19316
  return;
19265
19317
  }
19266
- const workDir = handle.workDir;
19267
- const planPath = getOrCreatePlanPath(workDir, handle);
19318
+ const planPath = getOrCreatePlanPath(handle);
19268
19319
  let planContent = "";
19269
19320
  try {
19270
19321
  if (existsSync14(planPath)) {
@@ -19338,7 +19389,7 @@ ${planContent}`;
19338
19389
  });
19339
19390
  const result = await runCodeReview(
19340
19391
  {
19341
- workDir: handle.workDir,
19392
+ cwd: handle.cwd,
19342
19393
  background: options.background?.trim() || void 0,
19343
19394
  from,
19344
19395
  to,
@@ -19459,8 +19510,8 @@ ${report}
19459
19510
  return;
19460
19511
  }
19461
19512
  const handle = this.agentHandle;
19462
- const workDir = handle.workDir;
19463
- const sessions = listSessions(workDir);
19513
+ const cwd2 = handle.cwd;
19514
+ const sessions = listSessions(cwd2);
19464
19515
  if (!args) {
19465
19516
  if (sessions.length === 0) {
19466
19517
  this.broadcast({
@@ -19489,7 +19540,7 @@ ${report}
19489
19540
  if (!Number.isNaN(idx) && idx >= 1 && idx <= sessions.length) {
19490
19541
  targetId = sessions[idx - 1].id;
19491
19542
  }
19492
- const saved = sessions.some((session) => session.id === targetId) ? loadSession(workDir, targetId) : [];
19543
+ const saved = sessions.some((session) => session.id === targetId) ? loadSession(cwd2, targetId) : [];
19493
19544
  if (saved.length === 0) {
19494
19545
  this.broadcast({
19495
19546
  type: "error",
@@ -19499,10 +19550,10 @@ ${report}
19499
19550
  return;
19500
19551
  }
19501
19552
  const replay = restoreRemoteSession(handle, targetId, saved);
19502
- touchSession(workDir, targetId);
19553
+ touchSession(cwd2, targetId);
19503
19554
  this.broadcast({
19504
19555
  type: "connected",
19505
- data: { session: targetId, cwd: cwd(), streaming: false }
19556
+ data: { session: targetId, cwd: cwd2, streaming: false }
19506
19557
  });
19507
19558
  this.broadcast({ type: "clear", data: null });
19508
19559
  for (const msg of replay) {
@@ -19663,7 +19714,7 @@ ${report}
19663
19714
  const factory = this.opts.agentFactory ?? createRemoteAgent;
19664
19715
  this.agentHandle = await factory({
19665
19716
  provider: this.startProvider(),
19666
- workDir: cwd(),
19717
+ cwd: cwd(),
19667
19718
  hooks: this.opts.hookConfigs,
19668
19719
  mcpServers: this.opts.mcpServers,
19669
19720
  lspServers: this.opts.lspServers,
@@ -19778,8 +19829,8 @@ ${report}
19778
19829
  };
19779
19830
 
19780
19831
  // src/a2a/executor.ts
19781
- async function createA2aRuntime(workDir, sessionId) {
19782
- const config = withProjectMcpServers(loadConfig(), workDir);
19832
+ async function createA2aRuntime(cwd2, sessionId) {
19833
+ const config = withProjectMcpServers(loadConfig(), cwd2);
19783
19834
  const provider = resolveDefaultProvider(
19784
19835
  config.providers,
19785
19836
  config.default_provider
@@ -19789,7 +19840,7 @@ async function createA2aRuntime(workDir, sessionId) {
19789
19840
  }
19790
19841
  const runtime2 = await createRemoteAgent({
19791
19842
  provider,
19792
- workDir,
19843
+ cwd: cwd2,
19793
19844
  hooks: config.hooks,
19794
19845
  mcpServers: config.mcp_servers,
19795
19846
  lspServers: config.lsp_servers,
@@ -19801,12 +19852,12 @@ async function createA2aRuntime(workDir, sessionId) {
19801
19852
  });
19802
19853
  if (sessionId) {
19803
19854
  runtime2.conv.appendMessages(
19804
- rebuildFromSession(loadSession(workDir, sessionId))
19855
+ rebuildFromSession(loadSession(cwd2, sessionId))
19805
19856
  );
19806
19857
  }
19807
19858
  return {
19808
19859
  sessionId: runtime2.sessionId,
19809
- workDir: runtime2.workDir,
19860
+ cwd: runtime2.cwd,
19810
19861
  run: runtime2.run.bind(runtime2),
19811
19862
  abort: () => {
19812
19863
  runtime2.abort();
@@ -19834,13 +19885,13 @@ function deferred() {
19834
19885
  return { promise, resolve: resolve11 };
19835
19886
  }
19836
19887
  var YukinoA2aExecutor = class {
19837
- constructor(runtimeFactory = createA2aRuntime, workDir = process.cwd(), idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS) {
19888
+ constructor(runtimeFactory = createA2aRuntime, cwd2 = process.cwd(), idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS) {
19838
19889
  this.runtimeFactory = runtimeFactory;
19839
- this.workDir = workDir;
19890
+ this.cwd = cwd2;
19840
19891
  this.idleTimeoutMs = idleTimeoutMs;
19841
19892
  }
19842
19893
  runtimeFactory;
19843
- workDir;
19894
+ cwd;
19844
19895
  idleTimeoutMs;
19845
19896
  sessions = /* @__PURE__ */ new Map();
19846
19897
  permissionCounter = 0;
@@ -19992,7 +20043,7 @@ var YukinoA2aExecutor = class {
19992
20043
  */
19993
20044
  async ensureRuntime(session) {
19994
20045
  session.runtimePromise ??= this.runtimeFactory(
19995
- this.workDir,
20046
+ this.cwd,
19996
20047
  session.sessionId
19997
20048
  ).then((runtime2) => {
19998
20049
  session.sessionId = runtime2.sessionId;
@@ -20105,7 +20156,7 @@ var YukinoA2aExecutor = class {
20105
20156
  permissions: /* @__PURE__ */ new Map()
20106
20157
  };
20107
20158
  session.run = run2;
20108
- saveMessage(runtime2.workDir, runtime2.sessionId, {
20159
+ saveMessage(runtime2.cwd, runtime2.sessionId, {
20109
20160
  role: "user",
20110
20161
  content: text,
20111
20162
  timestamp: Math.floor(Date.now() / 1e3)
@@ -20299,7 +20350,7 @@ async function startA2aServer(options = {}) {
20299
20350
  const card = buildAgentCard(url);
20300
20351
  const executor = new YukinoA2aExecutor(
20301
20352
  options.runtimeFactory ?? createA2aRuntime,
20302
- options.workDir ?? process.cwd()
20353
+ options.cwd ?? process.cwd()
20303
20354
  );
20304
20355
  const requestHandler = new DefaultRequestHandler(
20305
20356
  card,
@@ -20523,14 +20574,14 @@ function toolKind(toolName) {
20523
20574
  }
20524
20575
  return "other";
20525
20576
  }
20526
- function toolLocations(args, workDir) {
20577
+ function toolLocations(args, cwd2) {
20527
20578
  const path = strArg(args, "file_path") || strArg(args, "path");
20528
20579
  if (!path) {
20529
20580
  return void 0;
20530
20581
  }
20531
- return [{ path: isAbsolute4(path) ? path : resolve8(workDir, path) }];
20582
+ return [{ path: isAbsolute4(path) ? path : resolve8(cwd2, path) }];
20532
20583
  }
20533
- function toolCallUpdate(toolName, toolCallId, args, workDir) {
20584
+ function toolCallUpdate(toolName, toolCallId, args, cwd2) {
20534
20585
  return {
20535
20586
  sessionUpdate: "tool_call",
20536
20587
  toolCallId,
@@ -20538,7 +20589,7 @@ function toolCallUpdate(toolName, toolCallId, args, workDir) {
20538
20589
  kind: toolKind(toolName),
20539
20590
  status: "pending",
20540
20591
  rawInput: args,
20541
- locations: toolLocations(args, workDir)
20592
+ locations: toolLocations(args, cwd2)
20542
20593
  };
20543
20594
  }
20544
20595
  function toolResultUpdate(toolCallId, output, isError, elapsed) {
@@ -20554,7 +20605,7 @@ function toolResultUpdate(toolCallId, output, isError, elapsed) {
20554
20605
  }
20555
20606
  };
20556
20607
  }
20557
- function agentEventToUpdate(event, workDir, contextWindow) {
20608
+ function agentEventToUpdate(event, cwd2, contextWindow) {
20558
20609
  switch (event.type) {
20559
20610
  case "stream_text":
20560
20611
  return {
@@ -20567,7 +20618,7 @@ function agentEventToUpdate(event, workDir, contextWindow) {
20567
20618
  content: { type: "text", text: event.text }
20568
20619
  };
20569
20620
  case "tool_use":
20570
- return toolCallUpdate(event.toolName, event.toolId, event.args, workDir);
20621
+ return toolCallUpdate(event.toolName, event.toolId, event.args, cwd2);
20571
20622
  case "tool_result":
20572
20623
  return toolResultUpdate(
20573
20624
  event.toolId,
@@ -20622,7 +20673,7 @@ function stopReason(reason) {
20622
20673
  return "end_turn";
20623
20674
  }
20624
20675
  }
20625
- function* historyNotifications(sessionId, messages, workDir) {
20676
+ function* historyNotifications(sessionId, messages, cwd2) {
20626
20677
  for (const message of messages) {
20627
20678
  if (message.type === COMPACT_BOUNDARY || message.role !== "user" && message.role !== "assistant") {
20628
20679
  continue;
@@ -20644,7 +20695,7 @@ function* historyNotifications(sessionId, messages, workDir) {
20644
20695
  tool.tool_name,
20645
20696
  tool.tool_use_id,
20646
20697
  tool.arguments ?? {},
20647
- workDir
20698
+ cwd2
20648
20699
  )
20649
20700
  };
20650
20701
  }
@@ -20664,8 +20715,8 @@ function* historyNotifications(sessionId, messages, workDir) {
20664
20715
 
20665
20716
  // src/acp/agent.ts
20666
20717
  var SESSION_ID_PATTERN = /^[a-z0-9]+-[a-f0-9]{8}$/u;
20667
- async function createRuntime(workDir, sessionId) {
20668
- const config = withProjectMcpServers(loadConfig(), workDir);
20718
+ async function createRuntime(cwd2, sessionId) {
20719
+ const config = withProjectMcpServers(loadConfig(), cwd2);
20669
20720
  const provider = resolveDefaultProvider(
20670
20721
  config.providers,
20671
20722
  config.default_provider
@@ -20675,7 +20726,7 @@ async function createRuntime(workDir, sessionId) {
20675
20726
  }
20676
20727
  const runtime2 = await createRemoteAgent({
20677
20728
  provider,
20678
- workDir,
20729
+ cwd: cwd2,
20679
20730
  hooks: config.hooks,
20680
20731
  mcpServers: config.mcp_servers,
20681
20732
  lspServers: config.lsp_servers,
@@ -20687,7 +20738,7 @@ async function createRuntime(workDir, sessionId) {
20687
20738
  });
20688
20739
  return {
20689
20740
  sessionId: runtime2.sessionId,
20690
- workDir: runtime2.workDir,
20741
+ cwd: runtime2.cwd,
20691
20742
  contextWindow: runtime2.contextWindow,
20692
20743
  conv: runtime2.conv,
20693
20744
  run: runtime2.run.bind(runtime2),
@@ -20707,7 +20758,7 @@ async function createRuntime(workDir, sessionId) {
20707
20758
  }
20708
20759
  };
20709
20760
  }
20710
- function validateWorkDir(cwd2) {
20761
+ function validateCwd(cwd2) {
20711
20762
  if (!isAbsolute5(cwd2)) {
20712
20763
  throw acp.RequestError.invalidParams(
20713
20764
  void 0,
@@ -20721,7 +20772,7 @@ function validateSessionId(sessionId) {
20721
20772
  }
20722
20773
  }
20723
20774
  function validateWorkspaceInputs(params) {
20724
- validateWorkDir(params.cwd);
20775
+ validateCwd(params.cwd);
20725
20776
  if ((params.mcpServers?.length ?? 0) > 0) {
20726
20777
  throw acp.RequestError.invalidParams(
20727
20778
  void 0,
@@ -20785,7 +20836,7 @@ var YukinoAcpAgent = class {
20785
20836
  validateWorkspaceInputs(params);
20786
20837
  validateSessionId(params.sessionId);
20787
20838
  let session = this.sessions.get(params.sessionId);
20788
- if (session && session.runtime.workDir !== params.cwd) {
20839
+ if (session && session.runtime.cwd !== params.cwd) {
20789
20840
  throw acp.RequestError.invalidParams(
20790
20841
  void 0,
20791
20842
  "Session cwd does not match."
@@ -20823,7 +20874,7 @@ var YukinoAcpAgent = class {
20823
20874
  );
20824
20875
  }
20825
20876
  const cwd2 = params.cwd ?? process.cwd();
20826
- validateWorkDir(cwd2);
20877
+ validateCwd(cwd2);
20827
20878
  return {
20828
20879
  sessions: listSessions(cwd2).map((session) => ({
20829
20880
  sessionId: session.id,
@@ -20833,17 +20884,17 @@ var YukinoAcpAgent = class {
20833
20884
  }))
20834
20885
  };
20835
20886
  }
20836
- prompt(params, context) {
20887
+ prompt(params, context2) {
20837
20888
  const session = this.requireSession(params.sessionId);
20838
20889
  const text = promptToText(params.prompt);
20839
20890
  const generation = session.generation;
20840
20891
  const run2 = session.tail.catch(() => void 0).then(async () => {
20841
- if (session.closed || generation !== session.generation || context.signal.aborted) {
20892
+ if (session.closed || generation !== session.generation || context2.signal.aborted) {
20842
20893
  return { stopReason: "cancelled" };
20843
20894
  }
20844
20895
  const turnAbort = new AbortController();
20845
20896
  session.turnAbort = turnAbort;
20846
- const signal = AbortSignal.any([context.signal, turnAbort.signal]);
20897
+ const signal = AbortSignal.any([context2.signal, turnAbort.signal]);
20847
20898
  const abort = () => {
20848
20899
  session.runtime.abort();
20849
20900
  };
@@ -20857,7 +20908,7 @@ var YukinoAcpAgent = class {
20857
20908
  session,
20858
20909
  params.sessionId,
20859
20910
  text,
20860
- context,
20911
+ context2,
20861
20912
  signal
20862
20913
  );
20863
20914
  } finally {
@@ -20921,8 +20972,8 @@ var YukinoAcpAgent = class {
20921
20972
  }
20922
20973
  return session;
20923
20974
  }
20924
- async runPrompt(session, sessionId, text, context, signal) {
20925
- saveMessage(session.runtime.workDir, sessionId, {
20975
+ async runPrompt(session, sessionId, text, context2, signal) {
20976
+ saveMessage(session.runtime.cwd, sessionId, {
20926
20977
  role: "user",
20927
20978
  content: text,
20928
20979
  timestamp: Math.floor(Date.now() / 1e3)
@@ -20933,7 +20984,7 @@ var YukinoAcpAgent = class {
20933
20984
  for await (const event of session.runtime.run(text, {
20934
20985
  onPermissionRequest: async (toolName, args, decision, toolCallId, requestSignal) => {
20935
20986
  const permissionSignal = requestSignal ?? signal;
20936
- const permission = context.client.request(
20987
+ const permission = context2.client.request(
20937
20988
  acp.methods.client.session.requestPermission,
20938
20989
  {
20939
20990
  sessionId,
@@ -20943,7 +20994,7 @@ var YukinoAcpAgent = class {
20943
20994
  kind: toolKind(toolName),
20944
20995
  status: "pending",
20945
20996
  rawInput: args,
20946
- locations: toolLocations(args, session.runtime.workDir)
20997
+ locations: toolLocations(args, session.runtime.cwd)
20947
20998
  },
20948
20999
  options: [
20949
21000
  { optionId: "allow", name: "Allow once", kind: "allow_once" },
@@ -20995,12 +21046,12 @@ var YukinoAcpAgent = class {
20995
21046
  }
20996
21047
  const update = agentEventToUpdate(
20997
21048
  event,
20998
- session.runtime.workDir,
21049
+ session.runtime.cwd,
20999
21050
  session.runtime.contextWindow
21000
21051
  );
21001
21052
  if (update) {
21002
21053
  const notification = { sessionId, update };
21003
- await context.client.notify(
21054
+ await context2.client.notify(
21004
21055
  acp.methods.client.session.update,
21005
21056
  notification
21006
21057
  );
@@ -21016,30 +21067,30 @@ function createYukinoAcpApp(runtimeFactory) {
21016
21067
  const implementation = new YukinoAcpAgent(runtimeFactory);
21017
21068
  const app = acp.agent({ name: "yukino" }).onRequest(
21018
21069
  acp.methods.agent.initialize,
21019
- (context) => implementation.initialize(context.params)
21070
+ (context2) => implementation.initialize(context2.params)
21020
21071
  ).onRequest(
21021
21072
  acp.methods.agent.authenticate,
21022
21073
  () => implementation.authenticate()
21023
21074
  ).onRequest(
21024
21075
  acp.methods.agent.session.new,
21025
- (context) => implementation.newSession(context.params)
21076
+ (context2) => implementation.newSession(context2.params)
21026
21077
  ).onRequest(
21027
21078
  acp.methods.agent.session.prompt,
21028
- (context) => implementation.prompt(context.params, context)
21079
+ (context2) => implementation.prompt(context2.params, context2)
21029
21080
  ).onRequest(
21030
21081
  acp.methods.agent.session.list,
21031
- (context) => implementation.listSessions(context.params)
21082
+ (context2) => implementation.listSessions(context2.params)
21032
21083
  ).onRequest(
21033
21084
  acp.methods.agent.session.load,
21034
- (context) => implementation.loadSession(context.params, context.client, true)
21085
+ (context2) => implementation.loadSession(context2.params, context2.client, true)
21035
21086
  ).onRequest(
21036
21087
  acp.methods.agent.session.resume,
21037
- (context) => implementation.loadSession(context.params, context.client, false)
21088
+ (context2) => implementation.loadSession(context2.params, context2.client, false)
21038
21089
  ).onRequest(
21039
21090
  acp.methods.agent.session.close,
21040
- (context) => implementation.closeSession(context.params)
21041
- ).onNotification(acp.methods.agent.session.cancel, (context) => {
21042
- implementation.cancel(context.params);
21091
+ (context2) => implementation.closeSession(context2.params)
21092
+ ).onNotification(acp.methods.agent.session.cancel, (context2) => {
21093
+ implementation.cancel(context2.params);
21043
21094
  }).onConnect((connection) => {
21044
21095
  connection.signal.addEventListener(
21045
21096
  "abort",
@@ -21291,9 +21342,6 @@ function formatTokens2(value) {
21291
21342
  function percentage(value, total) {
21292
21343
  return `${(total > 0 ? value / total * 100 : 0).toFixed(1)}%`;
21293
21344
  }
21294
- function field(label, value) {
21295
- return ` ${`${label}:`.padEnd(28)}${value}`;
21296
- }
21297
21345
  function formatInteractionSummary(summary, endedAt = Date.now()) {
21298
21346
  const totalToolCalls = summary.successfulToolCalls + summary.failedToolCalls;
21299
21347
  const apiTimeMs = Math.max(0, summary.agentActiveMs - summary.toolTimeMs);
@@ -21301,37 +21349,16 @@ function formatInteractionSummary(summary, endedAt = Date.now()) {
21301
21349
  const promptTokens = summary.inputTokens + summary.cacheReadTokens + summary.cacheCreationTokens;
21302
21350
  const cacheHitRate = percentage(summary.cacheReadTokens, promptTokens);
21303
21351
  return [
21304
- " Interaction Summary",
21305
- field("Session ID", summary.sessionId),
21306
- field(
21307
- "Tool Calls",
21308
- `${String(totalToolCalls)} ( \u2713 ${String(summary.successfulToolCalls)} \u2717 ${String(summary.failedToolCalls)} )`
21309
- ),
21310
- field("Success Rate", `${successRate.toFixed(1)}%`),
21311
- "",
21312
- " Performance",
21313
- field("Wall Time", formatDuration(endedAt - summary.startedAt)),
21314
- field("Agent Active", formatDuration(summary.agentActiveMs)),
21315
- field(
21316
- " > API Time",
21317
- `${formatDuration(apiTimeMs)} (${percentage(apiTimeMs, summary.agentActiveMs)})`
21318
- ),
21319
- field(
21320
- " > Tool Time",
21321
- `${formatDuration(summary.toolTimeMs)} (${percentage(summary.toolTimeMs, summary.agentActiveMs)})`
21322
- ),
21323
- "",
21324
- " Tokens",
21325
- field("Input", formatTokens2(summary.inputTokens)),
21326
- field(" > Cache Read", formatTokens2(summary.cacheReadTokens)),
21327
- field(" > Cache Write", formatTokens2(summary.cacheCreationTokens)),
21328
- field("Output", formatTokens2(summary.outputTokens)),
21329
- field(
21330
- "Cache Hit",
21331
- `${cacheHitRate} (${formatTokens2(summary.cacheReadTokens)} of ${formatTokens2(promptTokens)} prompt)`
21332
- ),
21333
- "",
21334
- ` To resume this session: yukino --resume ${summary.sessionId}`
21352
+ `### Session \`${summary.sessionId}\``,
21353
+ [
21354
+ `**Tools** ${String(totalToolCalls)} calls \xB7 \u2713 ${String(summary.successfulToolCalls)} \xB7 \u2717 ${String(summary.failedToolCalls)} \xB7 ${successRate.toFixed(1)}% success`,
21355
+ `**Time** ${formatDuration(endedAt - summary.startedAt)} wall \xB7 ${formatDuration(summary.agentActiveMs)} active`,
21356
+ `**Breakdown** API ${formatDuration(apiTimeMs)} (${percentage(apiTimeMs, summary.agentActiveMs)}) \xB7 Tools ${formatDuration(summary.toolTimeMs)} (${percentage(summary.toolTimeMs, summary.agentActiveMs)})`,
21357
+ `**Tokens** \u2191 ${formatTokens2(summary.inputTokens)} input \xB7 \u2193 ${formatTokens2(summary.outputTokens)} output`,
21358
+ `**Cache** ${formatTokens2(summary.cacheReadTokens)} read \xB7 ${formatTokens2(summary.cacheCreationTokens)} write`,
21359
+ `**Cache hit** ${cacheHitRate} (${formatTokens2(summary.cacheReadTokens)} of ${formatTokens2(promptTokens)} prompt)`,
21360
+ `\`yukino --resume ${summary.sessionId}\``
21361
+ ].join(" \n")
21335
21362
  ].join("\n");
21336
21363
  }
21337
21364
 
@@ -21368,42 +21395,42 @@ var CodeReviewFormSchema = z20.object({
21368
21395
  to: z20.string(),
21369
21396
  commit: z20.string(),
21370
21397
  exclude: z20.string()
21371
- }).superRefine((values, context) => {
21398
+ }).superRefine((values, context2) => {
21372
21399
  const from = values.from.trim();
21373
21400
  const to = values.to.trim();
21374
21401
  const commit = values.commit.trim();
21375
21402
  if (from && !to) {
21376
- context.addIssue({
21403
+ context2.addIssue({
21377
21404
  code: "custom",
21378
21405
  path: ["to"],
21379
21406
  message: "To is required when From is set"
21380
21407
  });
21381
21408
  }
21382
21409
  if (to && !from) {
21383
- context.addIssue({
21410
+ context2.addIssue({
21384
21411
  code: "custom",
21385
21412
  path: ["from"],
21386
21413
  message: "From is required when To is set"
21387
21414
  });
21388
21415
  }
21389
21416
  if (commit && (from || to)) {
21390
- context.addIssue({
21417
+ context2.addIssue({
21391
21418
  code: "custom",
21392
21419
  path: ["commit"],
21393
21420
  message: "Commit cannot be combined with From/To"
21394
21421
  });
21395
21422
  }
21396
- const validateRef = (field2, value) => {
21423
+ const validateRef = (field, value) => {
21397
21424
  if (/\r|\n/u.test(value)) {
21398
- context.addIssue({
21425
+ context2.addIssue({
21399
21426
  code: "custom",
21400
- path: [field2],
21427
+ path: [field],
21401
21428
  message: "Git refs must be a single line"
21402
21429
  });
21403
21430
  } else if (value.startsWith("-")) {
21404
- context.addIssue({
21431
+ context2.addIssue({
21405
21432
  code: "custom",
21406
- path: [field2],
21433
+ path: [field],
21407
21434
  message: "Git refs must not start with '-'"
21408
21435
  });
21409
21436
  }
@@ -21441,7 +21468,7 @@ __export(usage_tracker_exports, {
21441
21468
  CommandUsageTracker: () => CommandUsageTracker
21442
21469
  });
21443
21470
  import { readFileSync as readFileSync13, writeFileSync as writeFileSync10, mkdirSync as mkdirSync11, existsSync as existsSync16 } from "fs";
21444
- import { join as join22, dirname as dirname9 } from "path";
21471
+ import { join as join21, dirname as dirname9 } from "path";
21445
21472
  import { safeParse as safeParse6, z as z21 } from "zod";
21446
21473
  var log29 = createChildLogger({ module: "commands" });
21447
21474
  var UsageEntrySchema = z21.object({
@@ -21451,9 +21478,9 @@ var UsageEntrySchema = z21.object({
21451
21478
  var CommandUsageTracker = class {
21452
21479
  usage = /* @__PURE__ */ new Map();
21453
21480
  filePath;
21454
- constructor(workDir) {
21455
- const dir = join22(workDir, ".yukino");
21456
- this.filePath = join22(dir, "command_usage.json");
21481
+ constructor() {
21482
+ const dir = getYukinoDir();
21483
+ this.filePath = join21(dir, "command_usage.json");
21457
21484
  if (!existsSync16(dir)) {
21458
21485
  mkdirSync11(dir, { recursive: true });
21459
21486
  }
@@ -21530,14 +21557,13 @@ import {
21530
21557
  rmSync as rmSync8,
21531
21558
  writeFileSync as writeFileSync11
21532
21559
  } from "fs";
21533
- import { join as join23 } from "path";
21534
21560
  import { parse as parse6, z as z22 } from "zod";
21535
21561
  var log30 = createChildLogger({ module: "history" });
21536
- var MAX_HISTORY_ENTRIES = 200;
21562
+ var MAX_HISTORY_ENTRIES = 1e4;
21537
21563
  var FILENAME = "prompt_history.jsonl";
21538
21564
  var JSONLSchema = z22.looseObject({ text: z22.string() });
21539
- function load(dir) {
21540
- const filePath = join23(dir, FILENAME);
21565
+ function load() {
21566
+ const filePath = yukinoPath(FILENAME);
21541
21567
  if (!existsSync17(filePath)) {
21542
21568
  return [];
21543
21569
  }
@@ -21558,11 +21584,11 @@ function load(dir) {
21558
21584
  return [];
21559
21585
  }
21560
21586
  }
21561
- function append(dir, text) {
21562
- const filePath = join23(dir, FILENAME);
21563
- mkdirSync12(dir, { recursive: true });
21587
+ function append(text) {
21588
+ const filePath = yukinoPath(FILENAME);
21589
+ mkdirSync12(getYukinoDir(), { recursive: true });
21564
21590
  return withFileSyncLock(filePath, () => {
21565
- const entries = load(dir);
21591
+ const entries = load();
21566
21592
  if (entries.length === 0 || entries[entries.length - 1] !== text) {
21567
21593
  entries.push(text);
21568
21594
  }
@@ -21799,7 +21825,8 @@ import {
21799
21825
  renameSync as renameSync7,
21800
21826
  rmSync as rmSync9
21801
21827
  } from "fs";
21802
- import { join as join24, resolve as resolve9 } from "path";
21828
+ import { homedir as homedir2 } from "os";
21829
+ import { join as join22, resolve as resolve9 } from "path";
21803
21830
  import yaml4 from "js-yaml";
21804
21831
  var log31 = createChildLogger({ module: "skills" });
21805
21832
  var MAX_SKILL_DOWNLOAD_BYTES = 1024 * 1024;
@@ -21840,18 +21867,18 @@ async function readSkillResponse(response, signal) {
21840
21867
  return Buffer.concat(chunks).toString("utf8");
21841
21868
  }
21842
21869
  var InstallSkillTool = class {
21843
- constructor(workDir, catalog, onInstalled, network = {}) {
21844
- this.workDir = workDir;
21870
+ constructor(cwd2, catalog, onInstalled, network = {}) {
21871
+ this.cwd = cwd2;
21845
21872
  this.catalog = catalog;
21846
21873
  this.onInstalled = onInstalled;
21847
21874
  this.network = network;
21848
21875
  }
21849
- workDir;
21876
+ cwd;
21850
21877
  catalog;
21851
21878
  onInstalled;
21852
21879
  network;
21853
21880
  name = "InstallSkill";
21854
- description = "Install a skill from a local file path or an http(s) URL into .agents/skills.";
21881
+ description = "Install a skill from a local file path or an http(s) URL into ~/.yukino/skills.";
21855
21882
  category = "write";
21856
21883
  schema() {
21857
21884
  return {
@@ -21911,7 +21938,7 @@ var InstallSkillTool = class {
21911
21938
  clearTimeout(timer);
21912
21939
  }
21913
21940
  } else {
21914
- content = readFileSync15(resolve9(this.workDir, source), "utf-8");
21941
+ content = readFileSync15(resolve9(this.cwd, source), "utf-8");
21915
21942
  }
21916
21943
  const parsed = parseSkillFile(content);
21917
21944
  if (!parsed) {
@@ -21935,9 +21962,9 @@ ${parsed.body}
21935
21962
  `;
21936
21963
  }
21937
21964
  ctx.abortSignal?.throwIfAborted();
21938
- let dir = realpathSync(this.workDir);
21939
- for (const segment of [".agents", "skills", name]) {
21940
- dir = join24(dir, segment);
21965
+ let dir = realpathSync(homedir2());
21966
+ for (const segment of [".yukino", "skills", name]) {
21967
+ dir = join22(dir, segment);
21941
21968
  const stat6 = lstatSync2(dir, { throwIfNoEntry: false });
21942
21969
  if (stat6) {
21943
21970
  if (stat6.isSymbolicLink() || !stat6.isDirectory()) {
@@ -21949,14 +21976,14 @@ ${parsed.body}
21949
21976
  mkdirSync13(dir);
21950
21977
  }
21951
21978
  }
21952
- const destination = join24(dir, "SKILL.md");
21979
+ const destination = join22(dir, "SKILL.md");
21953
21980
  const stat5 = lstatSync2(destination, { throwIfNoEntry: false });
21954
21981
  if (stat5 && (stat5.isSymbolicLink() || !stat5.isFile())) {
21955
21982
  throw new Error(
21956
21983
  `Installation target must be a regular file: ${destination}`
21957
21984
  );
21958
21985
  }
21959
- const temporary = join24(dir, `.SKILL-${randomUUID5()}.tmp`);
21986
+ const temporary = join22(dir, `.SKILL-${randomUUID5()}.tmp`);
21960
21987
  const fd = openSync2(temporary, "wx", stat5?.mode ?? 438);
21961
21988
  try {
21962
21989
  try {
@@ -21968,10 +21995,10 @@ ${parsed.body}
21968
21995
  } finally {
21969
21996
  rmSync9(temporary, { force: true });
21970
21997
  }
21971
- this.catalog.load(this.workDir);
21998
+ this.catalog.load(this.cwd);
21972
21999
  this.onInstalled?.();
21973
22000
  return {
21974
- output: `Skill '${name}' installed to .agents/skills/${name}/SKILL.md`,
22001
+ output: `Skill '${name}' installed to ${destination}`,
21975
22002
  isError: false
21976
22003
  };
21977
22004
  } catch (err) {
@@ -22005,6 +22032,7 @@ __export(tools_exports3, {
22005
22032
  Descriptions: () => descriptions_exports,
22006
22033
  Diff: () => diff_exports,
22007
22034
  EditFile: () => edit_file_exports,
22035
+ EditFileDiagnostics: () => edit_file_diagnostics_exports,
22008
22036
  EnterWorktree: () => enter_worktree_exports,
22009
22037
  ExitCodeHints: () => exit_code_hints_exports,
22010
22038
  ExitPlanMode: () => exit_plan_mode_exports,
@@ -22042,6 +22070,263 @@ function isDiffTool(toolName) {
22042
22070
  return toolName === "EditFile";
22043
22071
  }
22044
22072
 
22073
+ // src/update/index.ts
22074
+ var update_exports = {};
22075
+ __export(update_exports, {
22076
+ Install: () => install_exports,
22077
+ VersionCheck: () => version_check_exports,
22078
+ handleUpdateCommand: () => handleUpdateCommand
22079
+ });
22080
+
22081
+ // src/update/install.ts
22082
+ var install_exports = {};
22083
+ __export(install_exports, {
22084
+ getSelfUpdateCommand: () => getSelfUpdateCommand,
22085
+ packageManagerInvocation: () => packageManagerInvocation,
22086
+ runSelfUpdate: () => runSelfUpdate
22087
+ });
22088
+ import { execFile as execFile4, spawn as spawn6 } from "child_process";
22089
+ import { readFileSync as readFileSync16, realpathSync as realpathSync2 } from "fs";
22090
+ import { dirname as dirname10, isAbsolute as isAbsolute6, join as join23, relative as relative5, sep as sep3 } from "path";
22091
+ import { fileURLToPath } from "url";
22092
+ import { z as z25 } from "zod";
22093
+
22094
+ // src/update/version-check.ts
22095
+ var version_check_exports = {};
22096
+ __export(version_check_exports, {
22097
+ PACKAGE_NAME: () => PACKAGE_NAME,
22098
+ checkForUpdate: () => checkForUpdate,
22099
+ getLatestVersion: () => getLatestVersion,
22100
+ isNewerVersion: () => isNewerVersion
22101
+ });
22102
+ import { z as z24 } from "zod";
22103
+ var PACKAGE_NAME = "@yukino.js/yukino";
22104
+ var LATEST_VERSION_URL = "https://registry.npmjs.org/@yukino.js%2Fyukino/latest";
22105
+ var VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+[\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*)?$/u;
22106
+ function parseVersion(value) {
22107
+ const match = VERSION_PATTERN.exec(value);
22108
+ const prerelease = match?.[4]?.split(".") ?? [];
22109
+ if (!match || prerelease.some((part) => /^0\d+$/u.test(part))) {
22110
+ throw new Error(`Invalid package version: ${value}`);
22111
+ }
22112
+ return {
22113
+ core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])],
22114
+ prerelease
22115
+ };
22116
+ }
22117
+ function isNewerVersion(candidate, current) {
22118
+ const left = parseVersion(candidate);
22119
+ const right = parseVersion(current);
22120
+ for (let index = 0; index < left.core.length; index++) {
22121
+ if (left.core[index] !== right.core[index]) {
22122
+ return left.core[index] > right.core[index];
22123
+ }
22124
+ }
22125
+ if (left.prerelease.length === 0 || right.prerelease.length === 0) {
22126
+ return left.prerelease.length === 0 && right.prerelease.length > 0;
22127
+ }
22128
+ for (let index = 0; index < Math.max(left.prerelease.length, right.prerelease.length); index++) {
22129
+ const a = left.prerelease[index];
22130
+ const b = right.prerelease[index];
22131
+ if (a === b) {
22132
+ continue;
22133
+ }
22134
+ if (a === void 0 || b === void 0) {
22135
+ return b === void 0;
22136
+ }
22137
+ const aNumeric = /^\d+$/u.test(a);
22138
+ const bNumeric = /^\d+$/u.test(b);
22139
+ if (aNumeric && bNumeric) {
22140
+ return BigInt(a) > BigInt(b);
22141
+ }
22142
+ return aNumeric === bNumeric ? a > b : bNumeric;
22143
+ }
22144
+ return false;
22145
+ }
22146
+ async function getLatestVersion(signal) {
22147
+ const timeout = AbortSignal.timeout(1e4);
22148
+ const response = await fetch(LATEST_VERSION_URL, {
22149
+ headers: {
22150
+ accept: "application/json",
22151
+ "User-Agent": `yukino/${version} (${process.platform}; ${process.arch})`
22152
+ },
22153
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout
22154
+ });
22155
+ if (!response.ok) {
22156
+ throw new Error(
22157
+ `Could not check for Yukino updates: HTTP ${response.status}`
22158
+ );
22159
+ }
22160
+ const data = await response.json();
22161
+ const latest = z24.object({ version: z24.string() }).parse(data).version;
22162
+ parseVersion(latest);
22163
+ return latest;
22164
+ }
22165
+ async function checkForUpdate(signal) {
22166
+ if (process.env.YUKINO_SKIP_VERSION_CHECK === "1") {
22167
+ return void 0;
22168
+ }
22169
+ try {
22170
+ const latest = await getLatestVersion(signal);
22171
+ return isNewerVersion(latest, version) ? latest : void 0;
22172
+ } catch {
22173
+ return void 0;
22174
+ }
22175
+ }
22176
+
22177
+ // src/update/install.ts
22178
+ function packageManagerInvocation(command, args, platform2 = process.platform) {
22179
+ if (platform2 !== "win32") {
22180
+ return { command, args };
22181
+ }
22182
+ const invocation = [command, ...args].map((arg) => `'${arg.replaceAll("'", "''")}'`).join(" ");
22183
+ return {
22184
+ command: "powershell.exe",
22185
+ args: [
22186
+ "-NoProfile",
22187
+ "-NonInteractive",
22188
+ "-Command",
22189
+ `$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); & ${invocation}; exit $LASTEXITCODE`
22190
+ ]
22191
+ };
22192
+ }
22193
+ function getPackageDirectory() {
22194
+ let directory = dirname10(fileURLToPath(import.meta.url));
22195
+ while (true) {
22196
+ try {
22197
+ const data = JSON.parse(
22198
+ readFileSync16(join23(directory, "package.json"), "utf8")
22199
+ );
22200
+ if (z25.object({ name: z25.string() }).safeParse(data).data?.name === PACKAGE_NAME) {
22201
+ return directory;
22202
+ }
22203
+ } catch {
22204
+ }
22205
+ const parent = dirname10(directory);
22206
+ if (parent === directory) {
22207
+ throw new Error("Could not locate the Yukino installation.");
22208
+ }
22209
+ directory = parent;
22210
+ }
22211
+ }
22212
+ function isInside(directory, root) {
22213
+ try {
22214
+ const child = relative5(realpathSync2(root), realpathSync2(directory));
22215
+ return child !== "" && child !== ".." && !child.startsWith(`..${sep3}`) && !isAbsolute6(child);
22216
+ } catch {
22217
+ return false;
22218
+ }
22219
+ }
22220
+ async function getSelfUpdateCommand(latest, packageDirectory = getPackageDirectory()) {
22221
+ const normalized = packageDirectory.replaceAll("\\", "/").toLowerCase();
22222
+ const command = /\/(?:\.pnpm|pnpm)\//u.test(normalized) ? "pnpm" : /\/(?:\.yarn|yarn)\//u.test(normalized) ? "yarn" : "npm";
22223
+ const query = packageManagerInvocation(
22224
+ command,
22225
+ command === "yarn" ? ["global", "dir"] : ["root", "-g"]
22226
+ );
22227
+ let globalRoot = "";
22228
+ try {
22229
+ globalRoot = await new Promise((resolve11, reject) => {
22230
+ execFile4(
22231
+ query.command,
22232
+ query.args,
22233
+ {
22234
+ encoding: "utf8",
22235
+ timeout: 1e4,
22236
+ windowsHide: true
22237
+ },
22238
+ (error, stdout) => {
22239
+ if (error) {
22240
+ reject(new Error(error.message, { cause: error }));
22241
+ } else {
22242
+ resolve11(stdout.trim());
22243
+ }
22244
+ }
22245
+ );
22246
+ });
22247
+ } catch {
22248
+ }
22249
+ const npmRoot = dirname10(dirname10(packageDirectory));
22250
+ const inferredNpmPrefix = command === "npm" && normalized.endsWith(`/lib/node_modules/${PACKAGE_NAME}`) ? dirname10(dirname10(npmRoot)) : void 0;
22251
+ const roots = [globalRoot, ...inferredNpmPrefix ? [npmRoot] : []];
22252
+ if (command === "pnpm" && globalRoot) {
22253
+ roots.push(dirname10(globalRoot));
22254
+ }
22255
+ if (!roots.some((root) => root && isInside(packageDirectory, root))) {
22256
+ throw new Error(
22257
+ "This Yukino installation is not managed by global npm, yarn, or pnpm. Update the source checkout or reinstall using yukino-code/install.sh or yukino-code/install.ps1."
22258
+ );
22259
+ }
22260
+ return {
22261
+ command,
22262
+ args: [
22263
+ ...command === "yarn" ? ["global", "add"] : ["install", "-g"],
22264
+ ...inferredNpmPrefix ? ["--prefix", inferredNpmPrefix] : [],
22265
+ `${PACKAGE_NAME}@${latest}`,
22266
+ "--registry=https://registry.npmjs.org/"
22267
+ ]
22268
+ };
22269
+ }
22270
+ async function runSelfUpdate(update) {
22271
+ const invocation = packageManagerInvocation(update.command, update.args);
22272
+ await new Promise((resolve11, reject) => {
22273
+ const child = spawn6(invocation.command, invocation.args, {
22274
+ stdio: "inherit"
22275
+ });
22276
+ child.once("error", reject);
22277
+ child.once("close", (code, signal) => {
22278
+ if (code === 0) {
22279
+ resolve11();
22280
+ } else {
22281
+ reject(
22282
+ new Error(
22283
+ signal ? `${update.command} was terminated by ${signal}.` : `${update.command} exited with code ${code ?? "unknown"}.`
22284
+ )
22285
+ );
22286
+ }
22287
+ });
22288
+ });
22289
+ }
22290
+
22291
+ // src/update/index.ts
22292
+ async function handleUpdateCommand(args) {
22293
+ if (args.length === 1 && ["--version", "-v"].includes(args[0])) {
22294
+ console.log(version);
22295
+ return true;
22296
+ }
22297
+ if (args[0] !== "update") {
22298
+ return false;
22299
+ }
22300
+ if (args.length === 2 && ["--help", "-h"].includes(args[1])) {
22301
+ console.log(
22302
+ "Usage: yukino update\n\nUpdate Yukino to the latest npm release."
22303
+ );
22304
+ return true;
22305
+ }
22306
+ try {
22307
+ if (args.length !== 1) {
22308
+ throw new Error("Usage: yukino update");
22309
+ }
22310
+ const latest = await getLatestVersion();
22311
+ if (!isNewerVersion(latest, version)) {
22312
+ console.log(`Yukino is already up to date (v${version}).`);
22313
+ return true;
22314
+ }
22315
+ const command = await getSelfUpdateCommand(latest);
22316
+ console.log(
22317
+ `Updating Yukino from v${version} to v${latest} with ${command.command}...`
22318
+ );
22319
+ await runSelfUpdate(command);
22320
+ console.log(`Updated Yukino from v${version} to v${latest}.`);
22321
+ } catch (error) {
22322
+ console.error(
22323
+ `Update failed: ${error instanceof Error ? error.message : String(error)}`
22324
+ );
22325
+ process.exitCode = 1;
22326
+ }
22327
+ return true;
22328
+ }
22329
+
22045
22330
  // src/vscode/index.ts
22046
22331
  var vscode_exports = {};
22047
22332
  __export(vscode_exports, {
@@ -22057,7 +22342,7 @@ __export(ide_client_exports, {
22057
22342
  });
22058
22343
  import { setTimeout as delay2 } from "timers/promises";
22059
22344
  import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
22060
- import { z as z25 } from "zod";
22345
+ import { z as z27 } from "zod";
22061
22346
 
22062
22347
  // src/vscode/lockfile.ts
22063
22348
  var lockfile_exports = {};
@@ -22065,20 +22350,20 @@ __export(lockfile_exports, {
22065
22350
  detectIde: () => detectIde
22066
22351
  });
22067
22352
  import { readdir, readFile as readFile8 } from "fs/promises";
22068
- import { homedir as homedir7 } from "os";
22069
- import { join as join25, resolve as resolve10, sep as sep3 } from "path";
22070
- import { z as z24 } from "zod";
22353
+ import { homedir as homedir3 } from "os";
22354
+ import { join as join24, resolve as resolve10, sep as sep4 } from "path";
22355
+ import { z as z26 } from "zod";
22071
22356
  var log32 = createChildLogger({ module: "vscode" });
22072
- var LockfileSchema = z24.object({
22073
- workspaceFolders: z24.array(z24.string()).optional(),
22074
- pid: z24.number().optional(),
22075
- ideName: z24.string().optional(),
22076
- transport: z24.enum(["ws", "sse"]).optional(),
22077
- authToken: z24.string().optional()
22357
+ var LockfileSchema = z26.object({
22358
+ workspaceFolders: z26.array(z26.string()).optional(),
22359
+ pid: z26.number().optional(),
22360
+ ideName: z26.string().optional(),
22361
+ transport: z26.enum(["ws", "sse"]).optional(),
22362
+ authToken: z26.string().optional()
22078
22363
  });
22079
22364
  function ideLockDir() {
22080
- const configDir = process.env.CLAUDE_CONFIG_DIR ?? join25(homedir7(), ".claude");
22081
- return join25(configDir, "ide");
22365
+ const configDir = process.env.CLAUDE_CONFIG_DIR ?? join24(homedir3(), ".claude");
22366
+ return join24(configDir, "ide");
22082
22367
  }
22083
22368
  function cwdInWorkspace(cwd2, workspaceFolders) {
22084
22369
  const normalizedCwd = cwd2.normalize("NFC");
@@ -22087,7 +22372,7 @@ function cwdInWorkspace(cwd2, workspaceFolders) {
22087
22372
  return false;
22088
22373
  }
22089
22374
  const resolved = resolve10(folder).normalize("NFC");
22090
- return normalizedCwd === resolved || normalizedCwd.startsWith(resolved + sep3);
22375
+ return normalizedCwd === resolved || normalizedCwd.startsWith(resolved + sep4);
22091
22376
  });
22092
22377
  }
22093
22378
  async function readLockfile(dir, filename) {
@@ -22096,7 +22381,7 @@ async function readLockfile(dir, filename) {
22096
22381
  return null;
22097
22382
  }
22098
22383
  try {
22099
- const content = await readFile8(join25(dir, filename), "utf-8");
22384
+ const content = await readFile8(join24(dir, filename), "utf-8");
22100
22385
  const parsed = LockfileSchema.parse(JSON.parse(content));
22101
22386
  if (parsed.transport !== "ws") {
22102
22387
  return null;
@@ -22235,12 +22520,12 @@ var WebSocketTransport = class {
22235
22520
 
22236
22521
  // src/vscode/ide-client.ts
22237
22522
  var log33 = createChildLogger({ module: "vscode" });
22238
- var AtMentionedSchema = z25.object({
22239
- method: z25.literal("at_mentioned"),
22240
- params: z25.object({
22241
- filePath: z25.string(),
22242
- lineStart: z25.number().optional(),
22243
- lineEnd: z25.number().optional()
22523
+ var AtMentionedSchema = z27.object({
22524
+ method: z27.literal("at_mentioned"),
22525
+ params: z27.object({
22526
+ filePath: z27.string(),
22527
+ lineStart: z27.number().optional(),
22528
+ lineEnd: z27.number().optional()
22244
22529
  })
22245
22530
  });
22246
22531
  function inIdeTerminal() {
@@ -22357,7 +22642,7 @@ function parsePrintFlags(args) {
22357
22642
  }
22358
22643
  async function runPrintMode(args) {
22359
22644
  const startTime = Date.now();
22360
- const workDir = process.cwd();
22645
+ const cwd2 = process.cwd();
22361
22646
  const sessionId = newSessionId();
22362
22647
  const abortController = new AbortController();
22363
22648
  const onInterrupt = (code) => {
@@ -22373,10 +22658,10 @@ async function runPrintMode(args) {
22373
22658
  const onSigterm = () => {
22374
22659
  onInterrupt(143);
22375
22660
  };
22376
- const cfg = withProjectMcpServers(loadConfig(), workDir);
22661
+ const cfg = withProjectMcpServers(loadConfig(), cwd2);
22377
22662
  const provider = resolveDefaultProvider(cfg.providers, cfg.default_provider);
22378
22663
  let prompt = args.prompt;
22379
- const goalManager = new GoalManager(workDir, sessionId);
22664
+ const goalManager = new GoalManager(cwd2, sessionId);
22380
22665
  const command = parse2(prompt);
22381
22666
  if (command?.name === "goal") {
22382
22667
  const result = handleGoalCommand(goalManager, command.args);
@@ -22416,19 +22701,19 @@ async function runPrintMode(args) {
22416
22701
  }
22417
22702
  prompt = result.prompt;
22418
22703
  }
22419
- const env = detectEnvironment(workDir);
22704
+ const env = detectEnvironment(cwd2);
22420
22705
  env.model = provider.model;
22421
22706
  const systemPrompt = buildSystemPrompt(env);
22422
22707
  const client = await createClient(provider, systemPrompt);
22423
22708
  const conv = new ConversationManager();
22424
22709
  conv.addUserMessage(prompt);
22425
- const checker = new PermissionChecker(workDir, "bypassPermissions");
22710
+ const checker = new PermissionChecker(cwd2, "bypassPermissions");
22426
22711
  const taskList = new TaskList();
22427
- const registry = createToolRegistry(workDir, taskList, {
22712
+ const registry = createToolRegistry(cwd2, taskList, {
22428
22713
  lspServers: cfg.lsp_servers
22429
22714
  });
22430
- await configureBashSandbox(registry, workDir, cfg.sandbox, checker);
22431
- const teamManager = new TeamManager(workDir);
22715
+ await configureBashSandbox(registry, cwd2, cfg.sandbox, checker);
22716
+ const teamManager = new TeamManager(cwd2);
22432
22717
  registerLeaderTaskTools(registry, teamManager, taskList);
22433
22718
  teamManager.setPermissionChecker(checker);
22434
22719
  const backgroundTaskManager = new TaskManager();
@@ -22439,42 +22724,42 @@ async function runPrintMode(args) {
22439
22724
  registry.register(new TaskStopTool(teamManager, backgroundTaskManager));
22440
22725
  registry.register(new SyntheticOutputTool());
22441
22726
  const agentTool = new AgentTool(
22442
- workDir,
22727
+ cwd2,
22443
22728
  registry,
22444
- (def, prompt2, background, modelOverride, workDirOverride, context) => spawnSubagent(
22729
+ (def, prompt2, background, modelOverride, cwdOverride, context2) => spawnSubagent(
22445
22730
  def,
22446
22731
  prompt2,
22447
22732
  client,
22448
22733
  registry,
22449
22734
  provider,
22450
- workDirOverride ?? workDir,
22735
+ cwdOverride ?? cwd2,
22451
22736
  void 0,
22452
22737
  void 0,
22453
22738
  modelOverride,
22454
- workDirOverride ? context?.permissionChecker?.forWorkDir(workDirOverride) : context?.permissionChecker,
22739
+ cwdOverride ? context2?.permissionChecker?.forCwd(cwdOverride) : context2?.permissionChecker,
22455
22740
  {
22456
- abortSignal: context?.abortSignal,
22741
+ abortSignal: context2?.abortSignal,
22457
22742
  background,
22458
- onPermissionRequest: context?.onPermissionRequest,
22459
- permissionMode: context?.permissionChecker?.mode
22743
+ onPermissionRequest: context2?.onPermissionRequest,
22744
+ permissionMode: context2?.permissionChecker?.mode
22460
22745
  }
22461
22746
  ),
22462
22747
  conv,
22463
- (prompt2, conversation, forkRegistry, modelOverride, context) => spawnSubagent(
22748
+ (prompt2, conversation, forkRegistry, modelOverride, context2) => spawnSubagent(
22464
22749
  BUILTIN_AGENTS[0],
22465
22750
  prompt2,
22466
22751
  client,
22467
22752
  forkRegistry,
22468
22753
  provider,
22469
- context?.workDir ?? workDir,
22754
+ context2?.cwd ?? cwd2,
22470
22755
  void 0,
22471
22756
  void 0,
22472
22757
  modelOverride,
22473
- context?.permissionChecker,
22758
+ context2?.permissionChecker,
22474
22759
  {
22475
22760
  conversation,
22476
- abortSignal: context?.abortSignal,
22477
- onPermissionRequest: context?.onPermissionRequest
22761
+ abortSignal: context2?.abortSignal,
22762
+ onPermissionRequest: context2?.onPermissionRequest
22478
22763
  }
22479
22764
  ),
22480
22765
  backgroundTaskManager
@@ -22482,7 +22767,7 @@ async function runPrintMode(args) {
22482
22767
  agentTool.forkDisabled = !forkEnabled(cfg);
22483
22768
  agentTool.setTeamManager(
22484
22769
  teamManager,
22485
- (teamRegistry, teamChecker, memberWorkDir = workDir, options) => {
22770
+ (teamRegistry, teamChecker, memberCwd = cwd2, options) => {
22486
22771
  const conversation = new ConversationManager();
22487
22772
  return (task, onEvent, abortSignal) => spawnSubagent(
22488
22773
  options?.definition ?? BUILTIN_AGENTS[0],
@@ -22490,7 +22775,7 @@ async function runPrintMode(args) {
22490
22775
  client,
22491
22776
  teamRegistry,
22492
22777
  provider,
22493
- memberWorkDir,
22778
+ memberCwd,
22494
22779
  void 0,
22495
22780
  onEvent,
22496
22781
  options?.modelOverride,
@@ -22530,14 +22815,14 @@ async function runPrintMode(args) {
22530
22815
  registry,
22531
22816
  checker,
22532
22817
  conversation: conv,
22533
- workDir,
22818
+ cwd: cwd2,
22534
22819
  sessionId,
22535
22820
  goalManager,
22536
22821
  abortSignal: abortController.signal,
22537
22822
  fileStateCache: new FileStateCache(),
22538
22823
  contextWindow: getContextWindow(provider),
22539
22824
  maxOutput: getMaxOutputTokens(provider),
22540
- instructions: loadInstructions(workDir),
22825
+ instructions: loadInstructions(cwd2),
22541
22826
  // Completion reports are drained each turn as system reminders delivered to the Leader.
22542
22827
  notificationFn: () => [
22543
22828
  ...teamManager.drainLeaderMailbox(),
@@ -22654,7 +22939,7 @@ Error: ${event.error.message}`);
22654
22939
  } catch {
22655
22940
  }
22656
22941
  }
22657
- rmSync10(getSessionArtifactsDir(workDir, sessionId), {
22942
+ rmSync10(getSessionArtifactsDir(sessionId), {
22658
22943
  recursive: true,
22659
22944
  force: true
22660
22945
  });
@@ -22729,20 +23014,21 @@ __export(recover_exports, {
22729
23014
  recover: () => recover
22730
23015
  });
22731
23016
  import { appendFileSync, mkdirSync as mkdirSync14 } from "fs";
22732
- import { join as join26 } from "path";
22733
- var LOG_DIR = ".yukino";
22734
- var LOG_PATH = join26(LOG_DIR, "crash.log");
22735
23017
  function record(text) {
22736
23018
  try {
22737
- mkdirSync14(LOG_DIR, { recursive: true });
22738
- appendFileSync(LOG_PATH, `[${(/* @__PURE__ */ new Date()).toISOString()}] ${text}
22739
- `, "utf8");
23019
+ mkdirSync14(getYukinoDir(), { recursive: true });
23020
+ appendFileSync(
23021
+ yukinoPath("crash.log"),
23022
+ `[${(/* @__PURE__ */ new Date()).toISOString()}] ${text}
23023
+ `,
23024
+ "utf8"
23025
+ );
22740
23026
  } catch {
22741
23027
  }
22742
23028
  }
22743
- function recordError(context, error) {
23029
+ function recordError(context2, error) {
22744
23030
  const stack = error instanceof Error ? error.stack ?? error.message : String(error);
22745
- record(`crash [${context}] ${stack}`);
23031
+ record(`crash [${context2}] ${stack}`);
22746
23032
  }
22747
23033
  var TERMINAL_GONE_CODES = /* @__PURE__ */ new Set(["EIO", "EPIPE", "ERR_STREAM_DESTROYED"]);
22748
23034
  function isTerminalGone(err) {
@@ -22753,11 +23039,11 @@ function isTerminalGone(err) {
22753
23039
  return typeof code === "string" && TERMINAL_GONE_CODES.has(code);
22754
23040
  }
22755
23041
  var terminalGoneRecorded = false;
22756
- function exitForTerminalGone(context, error) {
23042
+ function exitForTerminalGone(context2, error) {
22757
23043
  if (!terminalGoneRecorded) {
22758
23044
  terminalGoneRecorded = true;
22759
23045
  const detail = error instanceof Error ? error.message : String(error);
22760
- record(`terminal closed [${context}] ${detail}`);
23046
+ record(`terminal closed [${context2}] ${detail}`);
22761
23047
  }
22762
23048
  runExitCleanups();
22763
23049
  process.exit(0);
@@ -22818,13 +23104,13 @@ __export(teammate_exports, {
22818
23104
  parseTeammateFlags: () => parseTeammateFlags,
22819
23105
  runTeammate: () => runTeammate
22820
23106
  });
22821
- import { basename as basename6, dirname as dirname10, join as join27 } from "path";
23107
+ import { basename as basename6, dirname as dirname11, join as join25 } from "path";
22822
23108
  function parseTeammateFlags(args) {
22823
23109
  if (!args.includes("--teammate")) {
22824
23110
  return null;
22825
23111
  }
22826
23112
  let teamDir2 = "";
22827
- let teamWorkDir;
23113
+ let teamCwd;
22828
23114
  let teamName = "";
22829
23115
  let memberName = "";
22830
23116
  let initialTask = "";
@@ -22835,8 +23121,8 @@ function parseTeammateFlags(args) {
22835
23121
  for (let i = 0; i < args.length; i++) {
22836
23122
  if (args[i] === "--team-dir" && args[i + 1]) {
22837
23123
  teamDir2 = args[++i];
22838
- } else if (args[i] === "--team-work-dir" && args[i + 1]) {
22839
- teamWorkDir = args[++i];
23124
+ } else if (args[i] === "--team-cwd" && args[i + 1]) {
23125
+ teamCwd = args[++i];
22840
23126
  } else if (args[i] === "--agent-type" && args[i + 1]) {
22841
23127
  agentType = args[++i];
22842
23128
  } else if (args[i] === "--model" && args[i + 1]) {
@@ -22862,11 +23148,11 @@ function parseTeammateFlags(args) {
22862
23148
  }
22863
23149
  if (!teamName) {
22864
23150
  const leaf = basename6(teamDir2);
22865
- teamName = leaf === "inboxes" ? basename6(dirname10(teamDir2)) : leaf;
23151
+ teamName = leaf === "inboxes" ? basename6(dirname11(teamDir2)) : leaf;
22866
23152
  }
22867
23153
  return {
22868
23154
  teamDir: teamDir2,
22869
- ...teamWorkDir ? { teamWorkDir } : {},
23155
+ ...teamCwd ? { teamCwd } : {},
22870
23156
  ...agentType ? { agentType } : {},
22871
23157
  ...model ? { model } : {},
22872
23158
  teamName,
@@ -22897,14 +23183,14 @@ async function buildTeammateRegistry(opts) {
22897
23183
  "A teammate host must own the MCP manager and disconnect it on exit"
22898
23184
  );
22899
23185
  }
22900
- const registry = createToolRegistry(opts.workDir, new TaskList(), {
23186
+ const registry = createToolRegistry(opts.cwd, new TaskList(), {
22901
23187
  lspServers: opts.lspServers
22902
23188
  });
22903
- await configureBashSandbox(registry, opts.workDir, opts.sandboxConfig);
23189
+ await configureBashSandbox(registry, opts.cwd, opts.sandboxConfig);
22904
23190
  registry.register(new SyntheticOutputTool());
22905
23191
  registry.register(new LoadSkillTool(opts.catalog, opts.skillHost));
22906
- registry.register(new InstallSkillTool(opts.workDir, opts.catalog));
22907
- const teamManager = new TeamManager(opts.teamWorkDir ?? opts.workDir, {
23192
+ registry.register(new InstallSkillTool(opts.cwd, opts.catalog));
23193
+ const teamManager = new TeamManager(opts.teamCwd ?? opts.cwd, {
22908
23194
  // This process is a teammate, not the leader: leave the recorded
22909
23195
  // leaderPid in config.json alone so other teammates (and this one) can
22910
23196
  // keep using it for liveness checks.
@@ -22971,7 +23257,7 @@ async function runTeammate(args) {
22971
23257
  initLogger({
22972
23258
  sessionId: `teammate-${safeMemberName}-${Date.now().toString(36)}`,
22973
23259
  mode: "teammate",
22974
- logDir: join27(dirname10(args.teamDir), "logs"),
23260
+ logDir: join25(dirname11(args.teamDir), "logs"),
22975
23261
  skipCleanup: true
22976
23262
  });
22977
23263
  process.on("exit", closeLogger);
@@ -22981,7 +23267,7 @@ async function runTeammate(args) {
22981
23267
  let shutdownReply;
22982
23268
  let failureReported = false;
22983
23269
  let failure;
22984
- const configPath = join27(dirname10(args.teamDir), "config.json");
23270
+ const configPath = join25(dirname11(args.teamDir), "config.json");
22985
23271
  let hadTeamConfig = readTeamFileAtPath(configPath) !== null;
22986
23272
  const controller = new AbortController();
22987
23273
  const abort = () => {
@@ -22992,19 +23278,19 @@ async function runTeammate(args) {
22992
23278
  process.on("SIGHUP", abort);
22993
23279
  try {
22994
23280
  registerTeammateProcess(
22995
- join27(dirname10(args.teamDir), "config.json"),
23281
+ join25(dirname11(args.teamDir), "config.json"),
22996
23282
  args.memberName,
22997
23283
  process.pid
22998
23284
  );
22999
- const workDir = process.cwd();
23000
- const cfg = withProjectMcpServers(loadConfig(), workDir);
23285
+ const cwd2 = process.cwd();
23286
+ const cfg = withProjectMcpServers(loadConfig(), cwd2);
23001
23287
  const configuredProvider = args.providerIndex === void 0 ? resolveDefaultProvider(cfg.providers, cfg.default_provider) : cfg.providers[args.providerIndex];
23002
23288
  if (!configuredProvider) {
23003
23289
  throw new Error(
23004
23290
  `Provider at index ${args.providerIndex} is not configured.`
23005
23291
  );
23006
23292
  }
23007
- const definition = loadAgentDefinitions(args.teamWorkDir ?? workDir).find(
23293
+ const definition = loadAgentDefinitions().find(
23008
23294
  (entry) => entry.name === (args.agentType ?? "general-purpose")
23009
23295
  );
23010
23296
  if (!definition) {
@@ -23017,7 +23303,7 @@ async function runTeammate(args) {
23017
23303
  const conversation = new ConversationManager();
23018
23304
  conversation.addSystemReminder(buildSubagentInstructions(definition));
23019
23305
  const catalog = new SkillCatalog();
23020
- catalog.load(workDir);
23306
+ catalog.load(cwd2);
23021
23307
  const skillHost = {
23022
23308
  activateSkill: (name, body) => {
23023
23309
  conversation.addSystemReminder(
@@ -23026,7 +23312,7 @@ ${body}`
23026
23312
  );
23027
23313
  }
23028
23314
  };
23029
- const env = detectEnvironment(workDir);
23315
+ const env = detectEnvironment(cwd2);
23030
23316
  env.model = provider.model;
23031
23317
  const systemPrompt = definition.systemPromptOverride ?? buildSystemPrompt(env);
23032
23318
  const client = await createClient(provider, systemPrompt);
@@ -23034,8 +23320,8 @@ ${body}`
23034
23320
  mcpManager = new MCPManager();
23035
23321
  }
23036
23322
  registry = await buildTeammateRegistry({
23037
- workDir,
23038
- teamWorkDir: args.teamWorkDir,
23323
+ cwd: cwd2,
23324
+ teamCwd: args.teamCwd,
23039
23325
  definition,
23040
23326
  teamName: args.teamName,
23041
23327
  memberName: args.memberName,
@@ -23050,9 +23336,9 @@ ${body}`
23050
23336
  contextWindow: getContextWindow(provider)
23051
23337
  });
23052
23338
  const checker = new PermissionChecker(
23053
- workDir,
23339
+ cwd2,
23054
23340
  args.permissionMode,
23055
- () => readTeamFileAtPath(join27(dirname10(args.teamDir), "config.json"))?.permissionMode ?? args.permissionMode
23341
+ () => readTeamFileAtPath(join25(dirname11(args.teamDir), "config.json"))?.permissionMode ?? args.permissionMode
23056
23342
  );
23057
23343
  checker.teammate = true;
23058
23344
  checker.sandboxEnabled = cfg.sandbox?.enabled ?? false;
@@ -23063,10 +23349,10 @@ ${body}`
23063
23349
  registry,
23064
23350
  checker,
23065
23351
  conversation,
23066
- workDir,
23352
+ cwd: cwd2,
23067
23353
  fileStateCache: new FileStateCache(),
23068
- skillSection: buildSkillSection(catalog, workDir),
23069
- instructions: loadInstructions(workDir),
23354
+ skillSection: buildSkillSection(catalog),
23355
+ instructions: loadInstructions(cwd2),
23070
23356
  contextWindow: getContextWindow(provider),
23071
23357
  maxOutput: getMaxOutputTokens(provider),
23072
23358
  maxIterations: definition.maxTurns ?? 200,
@@ -23208,7 +23494,7 @@ ${body}`
23208
23494
  if (configExists) {
23209
23495
  try {
23210
23496
  const released = new SharedTaskStore(
23211
- join27(dirname10(args.teamDir), "tasks.json")
23497
+ join25(dirname11(args.teamDir), "tasks.json")
23212
23498
  ).releaseOwner(args.memberName);
23213
23499
  if (released.length) {
23214
23500
  releaseSummary = `; unassigned tasks: ${released.map((task) => `#${task.id}`).join(", ")}`;
@@ -23269,6 +23555,7 @@ export {
23269
23555
  todo_exports as Todo,
23270
23556
  tool_result_exports as ToolResult,
23271
23557
  tools_exports3 as Tools,
23558
+ update_exports as Update,
23272
23559
  utils_exports as Utils,
23273
23560
  vscode_exports as VSCode,
23274
23561
  version_exports as Version,