fluxflow-cli 1.17.3 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/fluxflow.js +1969 -376
  2. package/package.json +4 -4
package/dist/fluxflow.js CHANGED
@@ -1,13 +1,42 @@
1
1
  #!/usr/bin/env node
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
4
14
  var __esm = (fn, res) => function __init() {
5
15
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
16
  };
17
+ var __commonJS = (cb, mod) => function __require2() {
18
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
+ };
7
20
  var __export = (target, all) => {
8
21
  for (var name in all)
9
22
  __defProp(target, name, { get: all[name], enumerable: true });
10
23
  };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") {
26
+ for (let key of __getOwnPropNames(from))
27
+ if (!__hasOwnProp.call(to, key) && key !== except)
28
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
29
+ }
30
+ return to;
31
+ };
32
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
33
+ // If the importer is in node compatibility mode or this is not an ESM
34
+ // file that has been converted to a CommonJS file using a Babel-
35
+ // compatible transform (i.e. "__esModule" has not been set), then set
36
+ // "default" to the CommonJS "module.exports" for node compatibility.
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
11
40
 
12
41
  // src/components/MultilineInput.jsx
13
42
  import React, { useState, useEffect, useMemo, useCallback, useRef } from "react";
@@ -97,7 +126,7 @@ var init_MultilineInput = __esm({
97
126
  };
98
127
  }
99
128
  return {
100
- preCursor: [{ value: " ", type: "cursor" }],
129
+ preCursor: [{ value: showCursor && focus ? "\u2502" : "", type: "cursor" }],
101
130
  postCursor: []
102
131
  };
103
132
  }
@@ -119,7 +148,7 @@ var init_MultilineInput = __esm({
119
148
  preCursor: [
120
149
  { value: formattedBefore.slice(0, lineStart) },
121
150
  { value: formattedBefore.slice(lineStart), type: "highlight" },
122
- { value: showCursor && focus ? " " : "", type: "cursor" }
151
+ { value: showCursor && focus ? "\u2502" : "", type: "cursor" }
123
152
  ],
124
153
  postCursor: [
125
154
  { value: formattedAfter.slice(0, lineEnd), type: "highlight" },
@@ -135,7 +164,7 @@ var init_MultilineInput = __esm({
135
164
  type: "highlight"
136
165
  },
137
166
  { value: formatText(textBefore.slice(highlight.end)) },
138
- { value: " ", type: "cursor" }
167
+ { value: showCursor && focus ? "\u2502" : "", type: "cursor" }
139
168
  ],
140
169
  postCursor: [
141
170
  {
@@ -188,8 +217,10 @@ var init_MultilineInput = __esm({
188
217
  return highlightStyle ?? textStyle;
189
218
  case "cursor":
190
219
  return {
191
- ...highlightStyle ?? textStyle,
192
- inverse: showCursor && focus
220
+ ...textStyle,
221
+ color: "cyan",
222
+ bold: true,
223
+ inverse: false
193
224
  };
194
225
  default:
195
226
  return textStyle;
@@ -207,6 +238,7 @@ var init_MultilineInput = __esm({
207
238
  showCursor = true,
208
239
  highlightPastedText = false,
209
240
  focus = true,
241
+ columns = 80,
210
242
  useCustomInput = (inputHandler, isActive) => useInput(inputHandler, { isActive }),
211
243
  ...controlledProps
212
244
  }) => {
@@ -217,6 +249,49 @@ var init_MultilineInput = __esm({
217
249
  setCursorIndex(value.length);
218
250
  }
219
251
  }, [value, cursorIndex]);
252
+ const getVisualPosition = useCallback((index) => {
253
+ const text = normalizeLineEndings(value);
254
+ const lines = text.split("\n");
255
+ const wrapWidth = Math.max(20, columns - 10);
256
+ let visualLine = 0;
257
+ let visualCol = 0;
258
+ let currentIdx = 0;
259
+ for (let i = 0; i < lines.length; i++) {
260
+ const line = lines[i];
261
+ const lineLen = line.length;
262
+ if (index >= currentIdx && index <= currentIdx + lineLen) {
263
+ const offsetInLine = index - currentIdx;
264
+ visualLine += Math.floor(offsetInLine / wrapWidth);
265
+ visualCol = offsetInLine % wrapWidth;
266
+ return { visualLine, visualCol };
267
+ }
268
+ const numVisualLines = Math.max(1, Math.ceil(lineLen / wrapWidth));
269
+ visualLine += numVisualLines;
270
+ currentIdx += lineLen + 1;
271
+ }
272
+ return { visualLine, visualCol };
273
+ }, [value, columns]);
274
+ const getIndexFromVisual = useCallback((targetLine, targetCol) => {
275
+ const text = normalizeLineEndings(value);
276
+ const lines = text.split("\n");
277
+ const wrapWidth = Math.max(20, columns - 10);
278
+ let currentVisualLine = 0;
279
+ let currentIdx = 0;
280
+ for (let i = 0; i < lines.length; i++) {
281
+ const line = lines[i];
282
+ const lineLen = line.length;
283
+ const numVisualLines = Math.max(1, Math.ceil(lineLen / wrapWidth));
284
+ if (targetLine >= currentVisualLine && targetLine < currentVisualLine + numVisualLines) {
285
+ const lineOffset = (targetLine - currentVisualLine) * wrapWidth;
286
+ const colInLine = Math.min(targetCol, lineLen - lineOffset);
287
+ const finalCol = Math.max(0, colInLine);
288
+ return Math.min(currentIdx + lineOffset + finalCol, currentIdx + lineLen);
289
+ }
290
+ currentVisualLine += numVisualLines;
291
+ currentIdx += lineLen + 1;
292
+ }
293
+ return value.length;
294
+ }, [value, columns]);
220
295
  useCustomInput((input, key) => {
221
296
  const submitKey = keyBindings?.submit ?? ((key2) => key2.return && key2.ctrl);
222
297
  const newlineKey = keyBindings?.newline ?? ((key2) => key2.return);
@@ -233,83 +308,26 @@ var init_MultilineInput = __esm({
233
308
  if (key.tab || key.shift && key.tab || key.ctrl && input === "c") {
234
309
  return;
235
310
  }
236
- if (keyBindings?.newline?.(key)) {
237
- const newValue = value.slice(0, cursorIndex) + "\n" + value.slice(cursorIndex);
238
- onChange(newValue);
239
- setCursorIndex(cursorIndex + 1);
240
- setPasteLength(0);
241
- return;
242
- }
243
311
  let nextPasteLength = 0;
244
312
  if (input.length > 1) {
245
313
  nextPasteLength = input.length;
246
314
  }
247
315
  if (key.upArrow) {
248
316
  if (showCursor) {
249
- const lines = normalizeLineEndings(value).split("\n");
250
- let currentLineIndex = 0;
251
- let currentPos = 0;
252
- let col = 0;
253
- for (let i = 0; i < lines.length; i++) {
254
- const line = lines[i];
255
- if (line === void 0) continue;
256
- const lineLen = line.length;
257
- const lineEnd = currentPos + lineLen;
258
- if (cursorIndex >= currentPos && cursorIndex <= lineEnd) {
259
- currentLineIndex = i;
260
- col = cursorIndex - currentPos;
261
- break;
262
- }
263
- currentPos = lineEnd + 1;
264
- }
265
- if (currentLineIndex > 0) {
266
- const targetLineIndex = currentLineIndex - 1;
267
- const targetLine = lines[targetLineIndex];
268
- if (targetLine !== void 0) {
269
- const targetLineLen = targetLine.length;
270
- const newCol = Math.min(col, targetLineLen);
271
- let newIndex = 0;
272
- for (let i = 0; i < targetLineIndex; i++) {
273
- newIndex += lines[i].length + 1;
274
- }
275
- newIndex += newCol;
276
- setCursorIndex(newIndex);
277
- setPasteLength(0);
278
- }
317
+ const { visualLine, visualCol } = getVisualPosition(cursorIndex);
318
+ if (visualLine > 0) {
319
+ const newIndex = getIndexFromVisual(visualLine - 1, visualCol);
320
+ setCursorIndex(newIndex);
321
+ setPasteLength(0);
279
322
  }
280
323
  }
281
324
  } else if (key.downArrow) {
282
325
  if (showCursor) {
283
- const lines = normalizeLineEndings(value).split("\n");
284
- let currentLineIndex = 0;
285
- let currentPos = 0;
286
- let col = 0;
287
- for (let i = 0; i < lines.length; i++) {
288
- const line = lines[i];
289
- if (line === void 0) continue;
290
- const lineLen = line.length;
291
- const lineEnd = currentPos + lineLen;
292
- if (cursorIndex >= currentPos && cursorIndex <= lineEnd) {
293
- currentLineIndex = i;
294
- col = cursorIndex - currentPos;
295
- break;
296
- }
297
- currentPos = lineEnd + 1;
298
- }
299
- if (currentLineIndex < lines.length - 1) {
300
- const targetLineIndex = currentLineIndex + 1;
301
- const targetLine = lines[targetLineIndex];
302
- if (targetLine !== void 0) {
303
- const targetLineLen = targetLine.length;
304
- const newCol = Math.min(col, targetLineLen);
305
- let newIndex = 0;
306
- for (let i = 0; i < targetLineIndex; i++) {
307
- newIndex += lines[i].length + 1;
308
- }
309
- newIndex += newCol;
310
- setCursorIndex(newIndex);
311
- setPasteLength(0);
312
- }
326
+ const { visualLine, visualCol } = getVisualPosition(cursorIndex);
327
+ const newIndex = getIndexFromVisual(visualLine + 1, visualCol);
328
+ if (newIndex !== cursorIndex) {
329
+ setCursorIndex(newIndex);
330
+ setPasteLength(0);
313
331
  }
314
332
  }
315
333
  } else if (key.leftArrow) {
@@ -374,66 +392,53 @@ var init_text = __esm({
374
392
  "src/utils/text.js"() {
375
393
  wrapText = (text, width) => {
376
394
  if (!text) return "";
377
- const sourceLines = text.split(/\r?\n/);
395
+ const ansiRegex = /\x1B\[[0-?]*[ -/]*[@-~]/g;
396
+ const sourceLines = text.split("\n");
378
397
  let finalLines = [];
379
398
  if (width <= 5) return text;
399
+ const getVisibleLength = (str) => str.replace(ansiRegex, "").length;
380
400
  sourceLines.forEach((sLine) => {
381
- if (sLine.length <= width) {
401
+ const visibleLength = getVisibleLength(sLine);
402
+ if (visibleLength <= width) {
382
403
  finalLines.push(sLine);
383
404
  return;
384
405
  }
385
406
  const tokens = sLine.split(/(\s+)/);
386
407
  let currentLine = "";
387
- let originalXPos = 0;
388
- let lastSignificantGap = 0;
408
+ let currentVisibleLength = 0;
389
409
  const leadingSpaceMatch = sLine.match(/^(\s*)/);
390
- if (leadingSpaceMatch) {
391
- lastSignificantGap = leadingSpaceMatch[1].length;
392
- }
393
- const listMatch = sLine.match(/^\s*([-*]|\d+\.)\s+/);
394
- if (listMatch) {
395
- lastSignificantGap = listMatch[0].length;
396
- }
410
+ const indent = leadingSpaceMatch ? leadingSpaceMatch[1] : "";
397
411
  tokens.forEach((token, idx) => {
398
412
  if (token.length === 0) return;
399
- const isWhitespace = token.trim().length === 0;
400
- if (isWhitespace) {
401
- if (token.length >= 2) {
402
- lastSignificantGap = originalXPos + token.length;
403
- }
404
- if (currentLine.length > 0) {
405
- currentLine += token;
406
- }
407
- } else {
408
- if (token.includes("|") || token.includes("\u2502")) {
409
- const pipeIdx = token.includes("|") ? token.indexOf("|") : token.indexOf("\u2502");
410
- lastSignificantGap = originalXPos + pipeIdx + 1;
411
- }
412
- if ((currentLine + token).length > width) {
413
- if (currentLine.trim().length > 0) {
414
- finalLines.push(currentLine.replace(/\s+$/, ""));
415
- const safeIndent = Math.min(lastSignificantGap, Math.max(0, width - 12));
416
- const indent = " ".repeat(safeIndent);
417
- currentLine = indent + token;
418
- while (currentLine.length > width && width > 20) {
419
- finalLines.push(currentLine.substring(0, width));
420
- currentLine = indent + currentLine.substring(width);
421
- }
413
+ const tokenVisibleLength = getVisibleLength(token);
414
+ if (currentVisibleLength + tokenVisibleLength > width) {
415
+ if (currentLine.trim().length > 0) {
416
+ finalLines.push(currentLine.trimEnd());
417
+ currentLine = indent + token;
418
+ currentVisibleLength = getVisibleLength(currentLine);
419
+ } else {
420
+ if (ansiRegex.test(token)) {
421
+ finalLines.push(token);
422
+ currentLine = indent;
423
+ currentVisibleLength = getVisibleLength(currentLine);
422
424
  } else {
423
425
  let word = token;
424
- while (word.length > width && width > 5) {
426
+ while (getVisibleLength(word) > width && width > 10) {
425
427
  finalLines.push(word.substring(0, width));
426
428
  word = word.substring(width);
427
429
  }
428
430
  currentLine = word;
431
+ currentVisibleLength = getVisibleLength(currentLine);
429
432
  }
430
- } else {
431
- currentLine += token;
432
433
  }
434
+ } else {
435
+ currentLine += token;
436
+ currentVisibleLength += tokenVisibleLength;
433
437
  }
434
- originalXPos += token.length;
435
438
  });
436
- if (currentLine) finalLines.push(currentLine.replace(/\s+$/, ""));
439
+ if (currentLine.trimEnd().length > 0 || currentLine === indent) {
440
+ finalLines.push(currentLine.trimEnd());
441
+ }
437
442
  });
438
443
  return finalLines.join("\n");
439
444
  };
@@ -463,10 +468,14 @@ var TerminalBox;
463
468
  var init_TerminalBox = __esm({
464
469
  "src/components/TerminalBox.jsx"() {
465
470
  init_text();
466
- TerminalBox = React2.memo(({ command, output, completed = false, isFocused = false, columns = 80 }) => {
467
- const cleanOutput = (output || "").replace(/\r/g, "").trim();
468
- const wrappedOutput = cleanOutput ? wrapText(cleanOutput, columns - 6) : "";
469
- return /* @__PURE__ */ React2.createElement(Box2, { flexDirection: "column", borderStyle: isFocused ? "double" : "round", borderColor: completed ? "#334155" : isFocused ? "yellow" : "cyan", paddingX: 2, paddingY: completed ? 0 : 1, width: "100%" }, /* @__PURE__ */ React2.createElement(Box2, { marginBottom: 1 }, /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "gray" : isFocused ? "yellow" : "cyan", bold: true }, completed ? "\u{1F3C1} FINISHED:" : "\u26A1 EXECUTING:", " "), /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "gray" : "white" }, command)), wrappedOutput ? /* @__PURE__ */ React2.createElement(Box2, { marginTop: completed ? 0 : 1, backgroundColor: "#0a0a0a", paddingX: 1 }, /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "gray" : "green" }, wrappedOutput)) : !completed && /* @__PURE__ */ React2.createElement(Box2, { marginTop: 1, backgroundColor: "#0a0a0a", paddingX: 1 }, /* @__PURE__ */ React2.createElement(Text2, { color: "gray", italic: true }, "Waiting for output...")), /* @__PURE__ */ React2.createElement(Box2, { justifyContent: "space-between", marginTop: 1 }, !completed ? /* @__PURE__ */ React2.createElement(Text2, { color: "gray", dimColor: true, italic: true }, "Double-press ESC to terminate if hanging.") : /* @__PURE__ */ React2.createElement(Box2, null), /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "#475569" : isFocused ? "yellow" : "cyan", bold: true }, completed ? "\u25CF ARCHIVED" : isFocused ? "\u25B6 TERMINAL FOCUSED" : "\u25CF LIVE (Press TAB to focus)")));
471
+ TerminalBox = React2.memo(({ command, output, completed = false, isFocused = false, columns = 80, isPty = false }) => {
472
+ const processOutput = (text) => {
473
+ if (!text) return "";
474
+ return text.split(/\r\n|\r|\n/).map((line) => line.trimEnd()).join("\n").replace(/^\n+|\n+$/g, "");
475
+ };
476
+ const cleanOutput = processOutput(output);
477
+ const displayOutput = isPty ? cleanOutput : cleanOutput ? wrapText(cleanOutput, columns - 6) : "";
478
+ return /* @__PURE__ */ React2.createElement(Box2, { flexDirection: "column", borderStyle: isFocused ? "double" : "round", borderColor: completed ? "#334155" : isFocused ? "yellow" : "cyan", paddingX: 2, paddingY: completed ? 0 : 1, width: "100%" }, /* @__PURE__ */ React2.createElement(Box2, { marginBottom: 1, justifyContent: "space-between", width: "100%" }, /* @__PURE__ */ React2.createElement(Box2, { flexShrink: 1, paddingRight: 2 }, /* @__PURE__ */ React2.createElement(Text2, null, /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "gray" : isFocused ? "yellow" : "cyan", bold: true }, completed ? "\u{1F3C1} FINISHED:" : "\u26A1 EXECUTING:", " "), /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "gray" : "white" }, command))), isPty && /* @__PURE__ */ React2.createElement(Box2, { flexShrink: 0, paddingX: 1 }, /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "gray" : "magenta", bold: true }, "ADVANCE"))), displayOutput ? /* @__PURE__ */ React2.createElement(Box2, { marginTop: completed ? 0 : 1, backgroundColor: isPty ? void 0 : "#0a0a0a", paddingX: 1 }, /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "gray" : void 0 }, displayOutput)) : !completed && /* @__PURE__ */ React2.createElement(Box2, { marginTop: 1, backgroundColor: isPty ? void 0 : "#0a0a0a", paddingX: 1 }, /* @__PURE__ */ React2.createElement(Text2, { color: "gray", italic: true }, "Waiting for output...")), /* @__PURE__ */ React2.createElement(Box2, { justifyContent: "space-between", marginTop: 1 }, !completed ? /* @__PURE__ */ React2.createElement(Text2, { color: "gray", dimColor: true, italic: true }, "Double-press ESC to terminate if hanging.") : /* @__PURE__ */ React2.createElement(Box2, null), /* @__PURE__ */ React2.createElement(Text2, { color: completed ? "#475569" : isFocused ? "yellow" : "cyan", bold: true }, completed ? "\u25CF ARCHIVED" : isFocused ? "\u25B6 TERMINAL FOCUSED" : "\u25CF LIVE (Press TAB to focus)")));
470
479
  });
471
480
  }
472
481
  });
@@ -510,7 +519,7 @@ var init_ChatLayout = __esm({
510
519
  "exec_command": "ExecuteCommand",
511
520
  "web_search": "WebSearch",
512
521
  "web_scrape": "ReadSite",
513
- "search_keyword": "FindFiles",
522
+ "search_keyword": "SearchKeyword",
514
523
  "write_pdf": "CreatePDF",
515
524
  "write_docx": "CreateDocument",
516
525
  "generate_image": "GenerateImage",
@@ -744,20 +753,26 @@ var init_ChatLayout = __esm({
744
753
  DiffLine = React3.memo(({ line, columns = 80 }) => {
745
754
  const isContext = line.includes("[UI_CONTEXT]");
746
755
  const cleanLine = line.replace("[UI_CONTEXT]", "");
756
+ if (isContext && cleanLine.includes("\u2550")) {
757
+ return /* @__PURE__ */ React3.createElement(Box3, { backgroundColor: "#1a1a1a", paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(Text3, { color: "gray", dimColor: true }, "\u2550".repeat(Math.max(10, columns - 4))));
758
+ }
747
759
  const isRemoval = cleanLine.startsWith("-");
748
760
  const isAddition = cleanLine.startsWith("+");
749
- const parts = cleanLine.substring(1).split("|");
750
- const lineNum = parts[0]?.trim() || "";
751
- const content = parts.slice(1).join("|");
761
+ const prefixChar = cleanLine[0];
762
+ const rest = cleanLine.substring(1);
763
+ const splitIdx = rest.indexOf("|");
764
+ const lineNum = splitIdx !== -1 ? rest.substring(0, splitIdx).trim() : "";
765
+ const content = splitIdx !== -1 ? rest.substring(splitIdx + 1) : rest;
752
766
  const bgColor = isRemoval ? "#3a0c0c" : isAddition ? "#0c3a1a" : "#1a1a1a";
753
- const textColor = isRemoval ? "#ff4d4d" : isAddition ? "#4dff88" : "white";
754
- return /* @__PURE__ */ React3.createElement(Box3, { backgroundColor: bgColor, paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { width: 5, flexShrink: 0 }, /* @__PURE__ */ React3.createElement(Text3, { color: isRemoval ? "#cf3a3a" : isAddition ? "#3acf65" : "gray", dimColor: true }, lineNum)), /* @__PURE__ */ React3.createElement(Box3, { width: 2, flexShrink: 0, marginLeft: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: textColor, bold: true }, isRemoval ? "-" : isAddition ? "+" : " ")), /* @__PURE__ */ React3.createElement(Box3, { flexGrow: 1, marginLeft: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: textColor }, wrapText(content, columns - 10))));
767
+ const textColor = isRemoval ? "#ff4d4d" : isAddition ? "#4dff88" : isContext ? "gray" : "white";
768
+ const numColor = isRemoval ? "#cf3a3a" : isAddition ? "#3acf65" : "gray";
769
+ return /* @__PURE__ */ React3.createElement(Box3, { backgroundColor: bgColor, paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { width: 5, flexShrink: 0 }, /* @__PURE__ */ React3.createElement(Text3, { color: numColor, dimColor: isContext }, lineNum)), /* @__PURE__ */ React3.createElement(Box3, { width: 2, flexShrink: 0, marginLeft: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: textColor, bold: true }, isRemoval ? "-" : isAddition ? "+" : " ")), /* @__PURE__ */ React3.createElement(Box3, { flexGrow: 1, marginLeft: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: textColor, dimColor: isContext }, wrapText(content, columns - 14))));
755
770
  });
756
771
  DiffBlock = React3.memo(({ text, columns = 80 }) => {
757
772
  const match = text.match(/\[DIFF_START\]([\s\S]*?)\[DIFF_END\]/);
758
773
  const diffBody = match ? match[1].trim() : "";
759
774
  const diffLines = diffBody.split("\n");
760
- return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", width: "100%", marginBottom: 0 }, /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", backgroundColor: "#1a1a1a", paddingY: 0, width: "100%" }, diffLines.map((line, i) => /* @__PURE__ */ React3.createElement(DiffLine, { key: i, line, columns }))));
775
+ return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", width: columns - 3, marginBottom: 0 }, /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", backgroundColor: "#1a1a1a", paddingY: 0, width: "100%" }, diffLines.map((line, i) => /* @__PURE__ */ React3.createElement(DiffLine, { key: i, line, columns: columns - 3 }))));
761
776
  });
762
777
  CodeRenderer = React3.memo(({ text, columns = 80 }) => {
763
778
  if (!text) return null;
@@ -774,11 +789,11 @@ var init_ChatLayout = __esm({
774
789
  const footer = contentAndFooter[1] ? `${footerMarker}${contentAndFooter[1]}` : "";
775
790
  const codeLines = content.split("\n");
776
791
  const gutterWidth = String(codeLines.length).length;
777
- return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", borderStyle: "round", borderColor: "#444", paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { alignSelf: "flex-end", marginTop: -1, marginRight: 1 }, /* @__PURE__ */ React3.createElement(Text3, { backgroundColor: "#444", color: "white" }, " FILE SNAPSHOT ")), /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", paddingY: 1, width: "100%" }, codeLines.map((line, idx) => /* @__PURE__ */ React3.createElement(Box3, { key: idx, width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { width: gutterWidth + 2, flexShrink: 0 }, /* @__PURE__ */ React3.createElement(Text3, { color: "gray", dimColor: true }, String(idx + 1).padStart(gutterWidth, " "), " ")), /* @__PURE__ */ React3.createElement(Box3, { flexGrow: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: "white" }, line)))))));
792
+ return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", width: columns - 3 }, /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", borderStyle: "round", borderColor: "#444", paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { alignSelf: "flex-end", marginTop: -1, marginRight: 1 }, /* @__PURE__ */ React3.createElement(Text3, { backgroundColor: "#444", color: "white" }, " FILE SNAPSHOT ")), /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", paddingY: 1, width: "100%" }, codeLines.map((line, idx) => /* @__PURE__ */ React3.createElement(Box3, { key: idx, width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { width: gutterWidth + 2, flexShrink: 0 }, /* @__PURE__ */ React3.createElement(Text3, { color: "gray", dimColor: true }, String(idx + 1).padStart(gutterWidth, " "), " ")), /* @__PURE__ */ React3.createElement(Box3, { flexGrow: 1 }, /* @__PURE__ */ React3.createElement(Text3, { color: "white" }, line)))))));
778
793
  }
779
794
  if (text.includes("```")) {
780
795
  const parts = text.split(/(```\w*\n?[\s\S]*?(?:```|$))/g);
781
- return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", width: "100%" }, parts.map((part, i) => {
796
+ return /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", width: columns - 3 }, parts.map((part, i) => {
782
797
  if (part.startsWith("```")) {
783
798
  const match = part.match(/```(\w*)\n?([\s\S]*?)(?:```|$)/);
784
799
  const lang = match ? match[1] : "code";
@@ -795,10 +810,10 @@ var init_ChatLayout = __esm({
795
810
  cleanPart = cleanPart.replace(/[\r\n]+$/, "");
796
811
  }
797
812
  if (!cleanPart) return null;
798
- return /* @__PURE__ */ React3.createElement(MarkdownText, { key: i, text: cleanPart, columns });
813
+ return /* @__PURE__ */ React3.createElement(MarkdownText, { key: i, text: cleanPart, columns: columns - 3 });
799
814
  }));
800
815
  }
801
- return /* @__PURE__ */ React3.createElement(MarkdownText, { text, columns });
816
+ return /* @__PURE__ */ React3.createElement(MarkdownText, { text, columns: columns - 3 });
802
817
  });
803
818
  formatThinkingDuration = (ms) => {
804
819
  const totalSecs = Math.round(ms / 1e3);
@@ -876,12 +891,14 @@ var init_ChatLayout = __esm({
876
891
  ];
877
892
  return /* @__PURE__ */ React3.createElement(Box3, { marginBottom: 1, paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", borderStyle: "round", borderColor: "magenta", paddingX: 2, paddingY: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(Text3, { color: "magenta", bold: true, underline: true }, "\u{1F4DC} COMMAND REFERENCE"), /* @__PURE__ */ React3.createElement(Box3, { flexDirection: "column", marginTop: 1 }, commandList.map((c, i) => /* @__PURE__ */ React3.createElement(Box3, { key: i, flexDirection: "row" }, /* @__PURE__ */ React3.createElement(Box3, { width: 15 }, /* @__PURE__ */ React3.createElement(Text3, { color: "cyan", bold: true }, c.cmd)), /* @__PURE__ */ React3.createElement(Text3, { color: "gray" }, " - ", c.desc))))));
878
893
  }
879
- if (isTerminalRecord) {
880
- const cmdMatch = msg.text.match(/COMMAND: (.*)\n/);
881
- const outputMatch = msg.text.match(/OUTPUT: ([\s\S]*)$/);
894
+ if (msg.isTerminalRecord) {
895
+ const cmdMatch = msg.text.match(/COMMAND: (.*)/);
896
+ const ptyMatch = msg.text.match(/PTY: (true|false)/);
897
+ const outputMatch = msg.text.match(/OUTPUT: ([\s\S]*)/);
882
898
  const cmd = cmdMatch ? cmdMatch[1] : "Unknown";
899
+ const isPty = ptyMatch ? ptyMatch[1] === "true" : false;
883
900
  const outputList = outputMatch ? outputMatch[1] : "";
884
- return /* @__PURE__ */ React3.createElement(Box3, { marginBottom: 1, paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(TerminalBox, { command: cmd, output: outputList, completed: true, columns }));
901
+ return /* @__PURE__ */ React3.createElement(Box3, { marginBottom: 1, paddingX: 1, width: "100%" }, /* @__PURE__ */ React3.createElement(TerminalBox, { command: cmd, output: outputList, completed: true, columns, isPty }));
885
902
  }
886
903
  const [animationDone, setAnimationDone] = React3.useState(!msg.isStreaming);
887
904
  const content = React3.useMemo(() => cleanSignals(msg.text), [msg.text]);
@@ -1648,9 +1665,22 @@ var init_secrets = __esm({
1648
1665
  });
1649
1666
 
1650
1667
  // src/data/main_tools.js
1651
- var TOOL_PROTOCOL;
1668
+ import { execSync } from "child_process";
1669
+ var _isPsAvailable, isPsAvailable, TOOL_PROTOCOL;
1652
1670
  var init_main_tools = __esm({
1653
1671
  "src/data/main_tools.js"() {
1672
+ _isPsAvailable = null;
1673
+ isPsAvailable = () => {
1674
+ if (process.platform !== "win32") return false;
1675
+ if (_isPsAvailable !== null) return _isPsAvailable;
1676
+ try {
1677
+ execSync('powershell.exe -NoProfile -Command "exit"', { stdio: "ignore" });
1678
+ _isPsAvailable = true;
1679
+ } catch (e) {
1680
+ _isPsAvailable = false;
1681
+ }
1682
+ return _isPsAvailable;
1683
+ };
1654
1684
  TOOL_PROTOCOL = (mode, osDetected) => `
1655
1685
  -- TOOL DEFINITIONS --
1656
1686
  Access to internal tools. To call a tool, MUST use the exact syntax on a new line: [tool:functions.ToolName(args)]
@@ -1668,10 +1698,10 @@ Suggest best options; don't ask for preferences
1668
1698
  ${mode === "Flux" ? `- PROJECT TOOLS (path = relative to CWD) -
1669
1699
  1. [tool:functions.ReadFile(path="...", startLine=number, endLine=number)]. Supports images/docs. User gives image/doc: VIEW FIRST
1670
1700
  2. [tool:functions.ReadFolder(path="...")]. Detailed DIR stats
1671
- 3. [tool:functions.PatchFile(path="...", replaceContent="exact old content", newContent="new content")]. Surgical patching. Unsure replaceContent? ReadFile > guessing
1701
+ 3. [tool:functions.PatchFile(path="...", replaceContent1="exact string", newContent1="...", ...MAX 8)]. Surgical Patch. Unsure? ReadFile > guessing. Multiple blocks same file? Use replaceContent2, newContent2 etc.
1672
1702
  4. [tool:functions.WriteFile(path="...", content="...")]. Creates/Overwrites. File Exist? PatchFile >> WriteFile. Verify Imports
1673
- 5. [tool:functions.SearchKeyword(keyword="...")]. Global project search. Finds definitions/logic without reading every file
1674
- 6. [tool:functions.Run(command="...")]. Runs a ${osDetected === "Windows" ? "Windows CMD" : "Bash"} command. Destructive/Irreversible ops -> Ask user
1703
+ 5. [tool:functions.SearchKeyword(keyword="...", file="path/to/file")]. Global project search. If 'file' is provided, searches only that file. Finds definitions/logic without reading every file
1704
+ 6. [tool:functions.Run(command="...")]. Runs a ${osDetected === "Windows" ? isPsAvailable() ? "Windows Powershell" : "Windows CMD" : "Bash"} command. Destructive/Irreversible ops -> Ask user
1675
1705
  7. [tool:functions.GenerateImage(path="... png", prompt="detailed", ratio="16:9, 9:16, 1:1")]. Usage: Mockups, PDF thumbnails, any visual content
1676
1706
  8. [tool:functions.WritePDF(path="...", content="...", orientation="...")]. PROACTIVE A4 PAGE BREAKS MUST IN CSS. HTML/CSS for PREMIUM layout (100vh/vw)
1677
1707
  9. [tool:functions.WriteDoc(path="...", content="...")]. A4 Word document
@@ -3223,14 +3253,24 @@ var init_update_file = __esm({
3223
3253
  update_file = async (args) => {
3224
3254
  const parsed = parseArgs(args);
3225
3255
  const targetPath = parsed.path;
3226
- let content_to_replace = parsed.content_to_replace !== void 0 ? parsed.content_to_replace : parsed.replaceContent;
3227
- let content_to_add = parsed.content_to_add !== void 0 ? parsed.content_to_add : parsed.newContent;
3228
3256
  if (!targetPath) return 'ERROR: Missing "path" argument for update_file.';
3229
- if (content_to_replace === void 0) return 'ERROR: Missing "replaceContent" argument.';
3230
- if (content_to_add === void 0) return 'ERROR: Missing "newContent" argument.';
3257
+ const patchPairs = [];
3258
+ const legacyReplace = parsed.content_to_replace !== void 0 ? parsed.content_to_replace : parsed.replaceContent;
3259
+ const legacyNew = parsed.content_to_add !== void 0 ? parsed.content_to_add : parsed.newContent;
3260
+ if (legacyReplace !== void 0 && legacyNew !== void 0) {
3261
+ patchPairs.push({ replace: legacyReplace, new: legacyNew });
3262
+ }
3263
+ for (let i = 1; i <= 10; i++) {
3264
+ const r = parsed[`replaceContent${i}`];
3265
+ const n = parsed[`newContent${i}`];
3266
+ if (r !== void 0 && n !== void 0 && r !== legacyReplace) {
3267
+ patchPairs.push({ replace: r, new: n });
3268
+ }
3269
+ }
3270
+ if (patchPairs.length === 0) {
3271
+ return "ERROR: No valid replacement pairs found. Use replaceContent1, newContent1, etc.";
3272
+ }
3231
3273
  const strip = (t) => t.replace(/^```[\w]*\n?/, "").replace(/```\s*$/, "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3232
- content_to_replace = strip(content_to_replace);
3233
- content_to_add = strip(content_to_add);
3234
3274
  const absolutePath = path9.resolve(process.cwd(), targetPath);
3235
3275
  try {
3236
3276
  if (!fs10.existsSync(absolutePath)) {
@@ -3238,141 +3278,1497 @@ var init_update_file = __esm({
3238
3278
  }
3239
3279
  await RevertManager.recordFileChange(absolutePath);
3240
3280
  let diskContent = fs10.readFileSync(absolutePath, "utf8");
3241
- if (diskContent.startsWith("\uFEFF")) {
3242
- diskContent = diskContent.slice(1);
3243
- }
3244
- const normalizedDisk = diskContent.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3245
- if (diskContent !== normalizedDisk) {
3246
- fs10.writeFileSync(absolutePath, normalizedDisk, "utf8");
3247
- diskContent = normalizedDisk;
3248
- }
3249
- const currentContent = diskContent;
3250
- const adjustIndentation = (newText, originalMatch, leadingContext = "") => {
3251
- if (!newText || originalMatch === void 0) return newText;
3252
- const getIndent = (line) => line.match(/^\s*/)[0];
3253
- const getMinIndent = (text) => {
3254
- const lines = text.split("\n").filter((l) => l.trim() !== "");
3255
- if (lines.length === 0) return "";
3256
- let min = getIndent(lines[0]);
3257
- for (const line of lines) {
3258
- const indent = getIndent(line);
3259
- if (indent.length < min.length) min = indent;
3260
- }
3261
- return min;
3281
+ if (diskContent.startsWith("\uFEFF")) diskContent = diskContent.slice(1);
3282
+ let currentFileContent = diskContent.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3283
+ const results = [];
3284
+ let totalInstances = 0;
3285
+ for (let i = 0; i < patchPairs.length; i++) {
3286
+ const pair = patchPairs[i];
3287
+ const content_to_replace = strip(pair.replace);
3288
+ const content_to_add = strip(pair.new);
3289
+ const adjustIndentation = (newText, originalMatch, leadingContext2 = "") => {
3290
+ if (!newText || originalMatch === void 0) return newText;
3291
+ const getIndent = (line) => line.match(/^\s*/)[0];
3292
+ const getMinIndent = (text) => {
3293
+ const lines = text.split("\n").filter((l) => l.trim() !== "");
3294
+ if (lines.length === 0) return "";
3295
+ let min = getIndent(lines[0]);
3296
+ for (const line of lines) {
3297
+ const indent = getIndent(line);
3298
+ if (indent.length < min.length) min = indent;
3299
+ }
3300
+ return min;
3301
+ };
3302
+ const matchBaseIndent = getMinIndent(originalMatch);
3303
+ const targetBaseIndent = leadingContext2.match(/^\s*/)[0] + matchBaseIndent;
3304
+ const newBaseIndent = getMinIndent(newText);
3305
+ const delta = targetBaseIndent.length - newBaseIndent.length;
3306
+ const indentChar = (targetBaseIndent.match(/\s/) || originalMatch.match(/\s/) || [" "])[0];
3307
+ const newLines = newText.split("\n");
3308
+ return newLines.map((line, i2) => {
3309
+ if (line.trim() === "" && i2 !== 0) return "";
3310
+ const currentLineIndent = getIndent(line).length;
3311
+ const shiftedIndentLength = Math.max(0, currentLineIndent + delta);
3312
+ const prependedIndentLength = i2 === 0 ? Math.max(0, shiftedIndentLength - leadingContext2.length) : shiftedIndentLength;
3313
+ return indentChar.repeat(prependedIndentLength) + line.trimStart();
3314
+ }).join("\n");
3262
3315
  };
3263
- const matchBaseIndent = getMinIndent(originalMatch);
3264
- const targetBaseIndent = leadingContext.match(/^\s*/)[0] + matchBaseIndent;
3265
- const newBaseIndent = getMinIndent(newText);
3266
- const delta = targetBaseIndent.length - newBaseIndent.length;
3267
- const indentChar = (targetBaseIndent.match(/\s/) || originalMatch.match(/\s/) || [" "])[0];
3268
- const newLines = newText.split("\n");
3269
- return newLines.map((line, i) => {
3270
- if (line.trim() === "" && i !== 0) return "";
3271
- const currentLineIndent = getIndent(line).length;
3272
- const shiftedIndentLength = Math.max(0, currentLineIndent + delta);
3273
- const prependedIndentLength = i === 0 ? Math.max(0, shiftedIndentLength - leadingContext.length) : shiftedIndentLength;
3274
- return indentChar.repeat(prependedIndentLength) + line.trimStart();
3275
- }).join("\n");
3276
- };
3277
- let instances = 0;
3278
- let startPos = -1;
3279
- let matchRegex = null;
3280
- const exactPattern = content_to_replace.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3281
- if (content_to_replace !== "" && currentContent.includes(content_to_replace)) {
3282
- matchRegex = new RegExp(exactPattern, "g");
3283
- } else {
3284
- const fuzzyLines = content_to_replace.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => line.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "\\s*"));
3285
- if (fuzzyLines.length > 0) {
3286
- const fuzzyPattern = fuzzyLines.join("\\s*");
3287
- try {
3288
- matchRegex = new RegExp(fuzzyPattern, "g");
3289
- } catch (e) {
3316
+ const exactPattern = content_to_replace.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3317
+ let matchRegex = null;
3318
+ if (content_to_replace !== "" && currentFileContent.includes(content_to_replace)) {
3319
+ matchRegex = new RegExp(exactPattern, "g");
3320
+ } else {
3321
+ const fuzzyLines = content_to_replace.split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => line.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "\\s*"));
3322
+ if (fuzzyLines.length > 0) {
3323
+ const fuzzyPattern = fuzzyLines.join("\\s*");
3324
+ try {
3325
+ matchRegex = new RegExp(fuzzyPattern, "g");
3326
+ } catch (e) {
3327
+ matchRegex = new RegExp(exactPattern, "g");
3328
+ }
3329
+ } else {
3290
3330
  matchRegex = new RegExp(exactPattern, "g");
3291
3331
  }
3332
+ }
3333
+ const matches = [...currentFileContent.matchAll(matchRegex)];
3334
+ if (matches.length === 0) {
3335
+ results.push({ success: false, error: `Block ${i + 1}: Could not find match.` });
3336
+ continue;
3337
+ }
3338
+ if (matches.length > 1) {
3339
+ results.push({ success: false, error: `Block ${i + 1}: Found ${matches.length} matches (must be unique).` });
3340
+ continue;
3341
+ }
3342
+ const startPos = matches[0].index;
3343
+ const firstMatchContent = matches[0][0];
3344
+ const lineStart = currentFileContent.lastIndexOf("\n", startPos) + 1;
3345
+ const leadingContext = currentFileContent.substring(lineStart, startPos);
3346
+ const finalReplacement = adjustIndentation(content_to_add, firstMatchContent, leadingContext);
3347
+ const allOriginalLines = currentFileContent.split("\n");
3348
+ const patchStartLine = currentFileContent.substring(0, startPos).split("\n").length;
3349
+ const patchOldLines = firstMatchContent.split("\n");
3350
+ const contextBefore = [];
3351
+ for (let j = Math.max(0, patchStartLine - 4); j < patchStartLine - 1; j++) {
3352
+ contextBefore.push({ num: j + 1, text: allOriginalLines[j] });
3353
+ }
3354
+ const contextAfter = [];
3355
+ const patchEndLineIdx = patchStartLine + patchOldLines.length - 1;
3356
+ for (let j = patchEndLineIdx; j < Math.min(allOriginalLines.length, patchEndLineIdx + 3); j++) {
3357
+ contextAfter.push({ num: j + 1, text: allOriginalLines[j] });
3358
+ }
3359
+ results.push({
3360
+ success: true,
3361
+ startPos,
3362
+ oldContent: firstMatchContent,
3363
+ newContent: finalReplacement,
3364
+ originalStartLine: patchStartLine,
3365
+ contextBefore,
3366
+ contextAfter
3367
+ });
3368
+ currentFileContent = currentFileContent.substring(0, startPos) + finalReplacement + currentFileContent.substring(startPos + firstMatchContent.length);
3369
+ totalInstances++;
3370
+ }
3371
+ if (totalInstances === 0) {
3372
+ return `ERROR: Failed to apply any patches to [${targetPath}].
3373
+ ${results.map((r) => r.error).join("\n")}`;
3374
+ }
3375
+ fs10.writeFileSync(absolutePath, currentFileContent, "utf8");
3376
+ let diffText = `SUCCESS: File [${targetPath}] updated. [${totalInstances}/${patchPairs.length}] blocks applied.
3377
+
3378
+ `;
3379
+ diffText += `[DIFF_START]
3380
+ `;
3381
+ const terminalWidth = process.stdout.columns || 100;
3382
+ const separatorLine = "\u2550".repeat(Math.max(20, terminalWidth - 12));
3383
+ const allLinesFinal = currentFileContent.split("\n");
3384
+ const successfulPatches = results.filter((r) => r.success);
3385
+ successfulPatches.forEach((res, idx) => {
3386
+ if (idx === 0) {
3387
+ res.contextBefore.forEach((ctx) => {
3388
+ diffText += `[UI_CONTEXT] ${ctx.num} |${ctx.text}
3389
+ `;
3390
+ });
3391
+ } else {
3392
+ const prev = successfulPatches[idx - 1];
3393
+ const prevLinesCount = prev.newContent.split("\n").length;
3394
+ const prevEndLine = prev.originalStartLine + prevLinesCount - 1;
3395
+ const gap = res.originalStartLine - prevEndLine - 1;
3396
+ if (gap >= 1 && gap < 12) {
3397
+ for (let j = prevEndLine; j < res.originalStartLine - 1; j++) {
3398
+ diffText += `[UI_CONTEXT] ${j + 1} |${allLinesFinal[j]}
3399
+ `;
3400
+ }
3401
+ } else if (gap >= 12) {
3402
+ prev.contextAfter.forEach((ctx) => {
3403
+ diffText += `[UI_CONTEXT] ${ctx.num} |${ctx.text}
3404
+ `;
3405
+ });
3406
+ diffText += `[UI_CONTEXT] ${separatorLine}
3407
+ `;
3408
+ res.contextBefore.forEach((ctx) => {
3409
+ diffText += `[UI_CONTEXT] ${ctx.num} |${ctx.text}
3410
+ `;
3411
+ });
3412
+ }
3413
+ }
3414
+ const oldLines = res.oldContent.split("\n");
3415
+ const newLines = res.newContent.split("\n");
3416
+ oldLines.forEach((line, i) => {
3417
+ diffText += `-${res.originalStartLine + i}|${line}
3418
+ `;
3419
+ });
3420
+ newLines.forEach((line, i) => {
3421
+ diffText += `+${res.originalStartLine + i}|${line}
3422
+ `;
3423
+ });
3424
+ if (idx === successfulPatches.length - 1) {
3425
+ res.contextAfter.forEach((ctx) => {
3426
+ diffText += `[UI_CONTEXT] ${ctx.num} |${ctx.text}
3427
+ `;
3428
+ });
3429
+ }
3430
+ });
3431
+ diffText += `[DIFF_END]`;
3432
+ const errors = results.filter((r) => !r.success);
3433
+ if (errors.length > 0) {
3434
+ diffText += `
3435
+
3436
+ \u26A0\uFE0F WARNING: Some blocks failed:
3437
+ ${errors.map((e) => ` \u2022 ${e.error}`).join("\n")}`;
3438
+ }
3439
+ return diffText;
3440
+ } catch (err) {
3441
+ return `ERROR: Failed to update file [${targetPath}]: ${err.message}`;
3442
+ }
3443
+ };
3444
+ }
3445
+ });
3446
+
3447
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/utils.js
3448
+ var require_utils = __commonJS({
3449
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/utils.js"(exports) {
3450
+ "use strict";
3451
+ Object.defineProperty(exports, "__esModule", { value: true });
3452
+ exports.loadNativeModule = exports.assign = void 0;
3453
+ function assign(target) {
3454
+ var sources = [];
3455
+ for (var _i = 1; _i < arguments.length; _i++) {
3456
+ sources[_i - 1] = arguments[_i];
3457
+ }
3458
+ sources.forEach(function(source) {
3459
+ return Object.keys(source).forEach(function(key) {
3460
+ return target[key] = source[key];
3461
+ });
3462
+ });
3463
+ return target;
3464
+ }
3465
+ exports.assign = assign;
3466
+ function loadNativeModule(name) {
3467
+ var dirs = ["build/Release", "build/Debug", "prebuilds/" + process.platform + "-" + process.arch];
3468
+ var relative = ["..", "."];
3469
+ var lastError;
3470
+ for (var _i = 0, dirs_1 = dirs; _i < dirs_1.length; _i++) {
3471
+ var d = dirs_1[_i];
3472
+ for (var _a = 0, relative_1 = relative; _a < relative_1.length; _a++) {
3473
+ var r = relative_1[_a];
3474
+ var dir = r + "/" + d + "/";
3475
+ try {
3476
+ return { dir, module: __require(dir + "/" + name + ".node") };
3477
+ } catch (e) {
3478
+ lastError = e;
3479
+ }
3480
+ }
3481
+ }
3482
+ throw new Error("Failed to load native module: " + name + ".node, checked: " + dirs.join(", ") + ": " + lastError);
3483
+ }
3484
+ exports.loadNativeModule = loadNativeModule;
3485
+ }
3486
+ });
3487
+
3488
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/eventEmitter2.js
3489
+ var require_eventEmitter2 = __commonJS({
3490
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/eventEmitter2.js"(exports) {
3491
+ "use strict";
3492
+ Object.defineProperty(exports, "__esModule", { value: true });
3493
+ exports.EventEmitter2 = void 0;
3494
+ var EventEmitter2 = (
3495
+ /** @class */
3496
+ (function() {
3497
+ function EventEmitter22() {
3498
+ this._listeners = [];
3499
+ }
3500
+ Object.defineProperty(EventEmitter22.prototype, "event", {
3501
+ get: function() {
3502
+ var _this = this;
3503
+ if (!this._event) {
3504
+ this._event = function(listener) {
3505
+ _this._listeners.push(listener);
3506
+ var disposable = {
3507
+ dispose: function() {
3508
+ for (var i = 0; i < _this._listeners.length; i++) {
3509
+ if (_this._listeners[i] === listener) {
3510
+ _this._listeners.splice(i, 1);
3511
+ return;
3512
+ }
3513
+ }
3514
+ }
3515
+ };
3516
+ return disposable;
3517
+ };
3518
+ }
3519
+ return this._event;
3520
+ },
3521
+ enumerable: false,
3522
+ configurable: true
3523
+ });
3524
+ EventEmitter22.prototype.fire = function(data) {
3525
+ var queue = [];
3526
+ for (var i = 0; i < this._listeners.length; i++) {
3527
+ queue.push(this._listeners[i]);
3528
+ }
3529
+ for (var i = 0; i < queue.length; i++) {
3530
+ queue[i].call(void 0, data);
3531
+ }
3532
+ };
3533
+ return EventEmitter22;
3534
+ })()
3535
+ );
3536
+ exports.EventEmitter2 = EventEmitter2;
3537
+ }
3538
+ });
3539
+
3540
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/terminal.js
3541
+ var require_terminal = __commonJS({
3542
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/terminal.js"(exports) {
3543
+ "use strict";
3544
+ Object.defineProperty(exports, "__esModule", { value: true });
3545
+ exports.Terminal = exports.DEFAULT_ROWS = exports.DEFAULT_COLS = void 0;
3546
+ var events_1 = __require("events");
3547
+ var eventEmitter2_1 = require_eventEmitter2();
3548
+ exports.DEFAULT_COLS = 80;
3549
+ exports.DEFAULT_ROWS = 24;
3550
+ var FLOW_CONTROL_PAUSE = "";
3551
+ var FLOW_CONTROL_RESUME = "";
3552
+ var Terminal = (
3553
+ /** @class */
3554
+ (function() {
3555
+ function Terminal2(opt) {
3556
+ this._pid = 0;
3557
+ this._fd = 0;
3558
+ this._cols = 0;
3559
+ this._rows = 0;
3560
+ this._readable = false;
3561
+ this._writable = false;
3562
+ this._onData = new eventEmitter2_1.EventEmitter2();
3563
+ this._onExit = new eventEmitter2_1.EventEmitter2();
3564
+ this._internalee = new events_1.EventEmitter();
3565
+ this.handleFlowControl = !!(opt === null || opt === void 0 ? void 0 : opt.handleFlowControl);
3566
+ this._flowControlPause = (opt === null || opt === void 0 ? void 0 : opt.flowControlPause) || FLOW_CONTROL_PAUSE;
3567
+ this._flowControlResume = (opt === null || opt === void 0 ? void 0 : opt.flowControlResume) || FLOW_CONTROL_RESUME;
3568
+ if (!opt) {
3569
+ return;
3570
+ }
3571
+ this._checkType("name", opt.name ? opt.name : void 0, "string");
3572
+ this._checkType("cols", opt.cols ? opt.cols : void 0, "number");
3573
+ this._checkType("rows", opt.rows ? opt.rows : void 0, "number");
3574
+ this._checkType("cwd", opt.cwd ? opt.cwd : void 0, "string");
3575
+ this._checkType("env", opt.env ? opt.env : void 0, "object");
3576
+ this._checkType("uid", opt.uid ? opt.uid : void 0, "number");
3577
+ this._checkType("gid", opt.gid ? opt.gid : void 0, "number");
3578
+ this._checkType("encoding", opt.encoding ? opt.encoding : void 0, "string");
3579
+ }
3580
+ Object.defineProperty(Terminal2.prototype, "onData", {
3581
+ get: function() {
3582
+ return this._onData.event;
3583
+ },
3584
+ enumerable: false,
3585
+ configurable: true
3586
+ });
3587
+ Object.defineProperty(Terminal2.prototype, "onExit", {
3588
+ get: function() {
3589
+ return this._onExit.event;
3590
+ },
3591
+ enumerable: false,
3592
+ configurable: true
3593
+ });
3594
+ Object.defineProperty(Terminal2.prototype, "pid", {
3595
+ get: function() {
3596
+ return this._pid;
3597
+ },
3598
+ enumerable: false,
3599
+ configurable: true
3600
+ });
3601
+ Object.defineProperty(Terminal2.prototype, "cols", {
3602
+ get: function() {
3603
+ return this._cols;
3604
+ },
3605
+ enumerable: false,
3606
+ configurable: true
3607
+ });
3608
+ Object.defineProperty(Terminal2.prototype, "rows", {
3609
+ get: function() {
3610
+ return this._rows;
3611
+ },
3612
+ enumerable: false,
3613
+ configurable: true
3614
+ });
3615
+ Terminal2.prototype.write = function(data) {
3616
+ if (this.handleFlowControl) {
3617
+ if (data === this._flowControlPause) {
3618
+ this.pause();
3619
+ return;
3620
+ }
3621
+ if (data === this._flowControlResume) {
3622
+ this.resume();
3623
+ return;
3624
+ }
3625
+ }
3626
+ this._write(data);
3627
+ };
3628
+ Terminal2.prototype._forwardEvents = function() {
3629
+ var _this = this;
3630
+ this.on("data", function(e) {
3631
+ return _this._onData.fire(e);
3632
+ });
3633
+ this.on("exit", function(exitCode, signal) {
3634
+ return _this._onExit.fire({ exitCode, signal });
3635
+ });
3636
+ };
3637
+ Terminal2.prototype._checkType = function(name, value, type, allowArray) {
3638
+ if (allowArray === void 0) {
3639
+ allowArray = false;
3640
+ }
3641
+ if (value === void 0) {
3642
+ return;
3643
+ }
3644
+ if (allowArray) {
3645
+ if (Array.isArray(value)) {
3646
+ value.forEach(function(v, i) {
3647
+ if (typeof v !== type) {
3648
+ throw new Error(name + "[" + i + "] must be a " + type + " (not a " + typeof v[i] + ")");
3649
+ }
3650
+ });
3651
+ return;
3652
+ }
3653
+ }
3654
+ if (typeof value !== type) {
3655
+ throw new Error(name + " must be a " + type + " (not a " + typeof value + ")");
3656
+ }
3657
+ };
3658
+ Terminal2.prototype.end = function(data) {
3659
+ this._socket.end(data);
3660
+ };
3661
+ Terminal2.prototype.pipe = function(dest, options) {
3662
+ return this._socket.pipe(dest, options);
3663
+ };
3664
+ Terminal2.prototype.pause = function() {
3665
+ return this._socket.pause();
3666
+ };
3667
+ Terminal2.prototype.resume = function() {
3668
+ return this._socket.resume();
3669
+ };
3670
+ Terminal2.prototype.setEncoding = function(encoding) {
3671
+ if (this._socket._decoder) {
3672
+ delete this._socket._decoder;
3673
+ }
3674
+ if (encoding) {
3675
+ this._socket.setEncoding(encoding);
3676
+ }
3677
+ };
3678
+ Terminal2.prototype.addListener = function(eventName, listener) {
3679
+ this.on(eventName, listener);
3680
+ };
3681
+ Terminal2.prototype.on = function(eventName, listener) {
3682
+ if (eventName === "close") {
3683
+ this._internalee.on("close", listener);
3684
+ return;
3685
+ }
3686
+ this._socket.on(eventName, listener);
3687
+ };
3688
+ Terminal2.prototype.emit = function(eventName) {
3689
+ var args = [];
3690
+ for (var _i = 1; _i < arguments.length; _i++) {
3691
+ args[_i - 1] = arguments[_i];
3692
+ }
3693
+ if (eventName === "close") {
3694
+ return this._internalee.emit.apply(this._internalee, arguments);
3695
+ }
3696
+ return this._socket.emit.apply(this._socket, arguments);
3697
+ };
3698
+ Terminal2.prototype.listeners = function(eventName) {
3699
+ return this._socket.listeners(eventName);
3700
+ };
3701
+ Terminal2.prototype.removeListener = function(eventName, listener) {
3702
+ this._socket.removeListener(eventName, listener);
3703
+ };
3704
+ Terminal2.prototype.removeAllListeners = function(eventName) {
3705
+ this._socket.removeAllListeners(eventName);
3706
+ };
3707
+ Terminal2.prototype.once = function(eventName, listener) {
3708
+ this._socket.once(eventName, listener);
3709
+ };
3710
+ Terminal2.prototype._close = function() {
3711
+ this._socket.readable = false;
3712
+ this.write = function() {
3713
+ };
3714
+ this.end = function() {
3715
+ };
3716
+ this._writable = false;
3717
+ this._readable = false;
3718
+ };
3719
+ Terminal2.prototype._parseEnv = function(env) {
3720
+ var keys = Object.keys(env || {});
3721
+ var pairs = [];
3722
+ for (var i = 0; i < keys.length; i++) {
3723
+ if (keys[i] === void 0) {
3724
+ continue;
3725
+ }
3726
+ pairs.push(keys[i] + "=" + env[keys[i]]);
3727
+ }
3728
+ return pairs;
3729
+ };
3730
+ return Terminal2;
3731
+ })()
3732
+ );
3733
+ exports.Terminal = Terminal;
3734
+ }
3735
+ });
3736
+
3737
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/shared/conout.js
3738
+ var require_conout = __commonJS({
3739
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/shared/conout.js"(exports) {
3740
+ "use strict";
3741
+ Object.defineProperty(exports, "__esModule", { value: true });
3742
+ exports.getWorkerPipeName = void 0;
3743
+ function getWorkerPipeName(conoutPipeName) {
3744
+ return conoutPipeName + "-worker";
3745
+ }
3746
+ exports.getWorkerPipeName = getWorkerPipeName;
3747
+ }
3748
+ });
3749
+
3750
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsConoutConnection.js
3751
+ var require_windowsConoutConnection = __commonJS({
3752
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsConoutConnection.js"(exports) {
3753
+ "use strict";
3754
+ var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
3755
+ function adopt(value) {
3756
+ return value instanceof P ? value : new P(function(resolve) {
3757
+ resolve(value);
3758
+ });
3759
+ }
3760
+ return new (P || (P = Promise))(function(resolve, reject) {
3761
+ function fulfilled(value) {
3762
+ try {
3763
+ step(generator.next(value));
3764
+ } catch (e) {
3765
+ reject(e);
3766
+ }
3767
+ }
3768
+ function rejected(value) {
3769
+ try {
3770
+ step(generator["throw"](value));
3771
+ } catch (e) {
3772
+ reject(e);
3773
+ }
3774
+ }
3775
+ function step(result) {
3776
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
3777
+ }
3778
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
3779
+ });
3780
+ };
3781
+ var __generator = exports && exports.__generator || function(thisArg, body) {
3782
+ var _ = { label: 0, sent: function() {
3783
+ if (t[0] & 1) throw t[1];
3784
+ return t[1];
3785
+ }, trys: [], ops: [] }, f, y, t, g;
3786
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
3787
+ return this;
3788
+ }), g;
3789
+ function verb(n) {
3790
+ return function(v) {
3791
+ return step([n, v]);
3792
+ };
3793
+ }
3794
+ function step(op) {
3795
+ if (f) throw new TypeError("Generator is already executing.");
3796
+ while (_) try {
3797
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
3798
+ if (y = 0, t) op = [op[0] & 2, t.value];
3799
+ switch (op[0]) {
3800
+ case 0:
3801
+ case 1:
3802
+ t = op;
3803
+ break;
3804
+ case 4:
3805
+ _.label++;
3806
+ return { value: op[1], done: false };
3807
+ case 5:
3808
+ _.label++;
3809
+ y = op[1];
3810
+ op = [0];
3811
+ continue;
3812
+ case 7:
3813
+ op = _.ops.pop();
3814
+ _.trys.pop();
3815
+ continue;
3816
+ default:
3817
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
3818
+ _ = 0;
3819
+ continue;
3820
+ }
3821
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
3822
+ _.label = op[1];
3823
+ break;
3824
+ }
3825
+ if (op[0] === 6 && _.label < t[1]) {
3826
+ _.label = t[1];
3827
+ t = op;
3828
+ break;
3829
+ }
3830
+ if (t && _.label < t[2]) {
3831
+ _.label = t[2];
3832
+ _.ops.push(op);
3833
+ break;
3834
+ }
3835
+ if (t[2]) _.ops.pop();
3836
+ _.trys.pop();
3837
+ continue;
3838
+ }
3839
+ op = body.call(thisArg, _);
3840
+ } catch (e) {
3841
+ op = [6, e];
3842
+ y = 0;
3843
+ } finally {
3844
+ f = t = 0;
3845
+ }
3846
+ if (op[0] & 5) throw op[1];
3847
+ return { value: op[0] ? op[1] : void 0, done: true };
3848
+ }
3849
+ };
3850
+ Object.defineProperty(exports, "__esModule", { value: true });
3851
+ exports.ConoutConnection = void 0;
3852
+ var worker_threads_1 = __require("worker_threads");
3853
+ var conout_1 = require_conout();
3854
+ var path_1 = __require("path");
3855
+ var eventEmitter2_1 = require_eventEmitter2();
3856
+ var FLUSH_DATA_INTERVAL = 1e3;
3857
+ var ConoutConnection = (
3858
+ /** @class */
3859
+ (function() {
3860
+ function ConoutConnection2(_conoutPipeName, _useConptyDll) {
3861
+ var _this = this;
3862
+ this._conoutPipeName = _conoutPipeName;
3863
+ this._useConptyDll = _useConptyDll;
3864
+ this._isDisposed = false;
3865
+ this._onReady = new eventEmitter2_1.EventEmitter2();
3866
+ var workerData = {
3867
+ conoutPipeName: _conoutPipeName
3868
+ };
3869
+ var scriptPath = __dirname.replace("node_modules.asar", "node_modules.asar.unpacked");
3870
+ this._worker = new worker_threads_1.Worker(path_1.join(scriptPath, "worker/conoutSocketWorker.js"), { workerData });
3871
+ this._worker.on("message", function(message) {
3872
+ switch (message) {
3873
+ case 1:
3874
+ _this._onReady.fire();
3875
+ return;
3876
+ default:
3877
+ console.warn("Unexpected ConoutWorkerMessage", message);
3878
+ }
3879
+ });
3880
+ }
3881
+ Object.defineProperty(ConoutConnection2.prototype, "onReady", {
3882
+ get: function() {
3883
+ return this._onReady.event;
3884
+ },
3885
+ enumerable: false,
3886
+ configurable: true
3887
+ });
3888
+ ConoutConnection2.prototype.dispose = function() {
3889
+ if (!this._useConptyDll && this._isDisposed) {
3890
+ return;
3891
+ }
3892
+ this._isDisposed = true;
3893
+ this._drainDataAndClose();
3894
+ };
3895
+ ConoutConnection2.prototype.connectSocket = function(socket) {
3896
+ socket.connect(conout_1.getWorkerPipeName(this._conoutPipeName));
3897
+ };
3898
+ ConoutConnection2.prototype._drainDataAndClose = function() {
3899
+ var _this = this;
3900
+ if (this._drainTimeout) {
3901
+ clearTimeout(this._drainTimeout);
3902
+ }
3903
+ this._drainTimeout = setTimeout(function() {
3904
+ return _this._destroySocket();
3905
+ }, FLUSH_DATA_INTERVAL);
3906
+ };
3907
+ ConoutConnection2.prototype._destroySocket = function() {
3908
+ return __awaiter(this, void 0, void 0, function() {
3909
+ return __generator(this, function(_a) {
3910
+ switch (_a.label) {
3911
+ case 0:
3912
+ return [4, this._worker.terminate()];
3913
+ case 1:
3914
+ _a.sent();
3915
+ return [
3916
+ 2
3917
+ /*return*/
3918
+ ];
3919
+ }
3920
+ });
3921
+ });
3922
+ };
3923
+ return ConoutConnection2;
3924
+ })()
3925
+ );
3926
+ exports.ConoutConnection = ConoutConnection;
3927
+ }
3928
+ });
3929
+
3930
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsPtyAgent.js
3931
+ var require_windowsPtyAgent = __commonJS({
3932
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsPtyAgent.js"(exports) {
3933
+ "use strict";
3934
+ Object.defineProperty(exports, "__esModule", { value: true });
3935
+ exports.argsToCommandLine = exports.WindowsPtyAgent = void 0;
3936
+ var fs19 = __require("fs");
3937
+ var os5 = __require("os");
3938
+ var path17 = __require("path");
3939
+ var child_process_1 = __require("child_process");
3940
+ var net_1 = __require("net");
3941
+ var windowsConoutConnection_1 = require_windowsConoutConnection();
3942
+ var utils_1 = require_utils();
3943
+ var conptyNative;
3944
+ var winptyNative;
3945
+ var FLUSH_DATA_INTERVAL = 1e3;
3946
+ var WindowsPtyAgent = (
3947
+ /** @class */
3948
+ (function() {
3949
+ function WindowsPtyAgent2(file, args, env, cwd, cols, rows, debug, _useConpty, _useConptyDll, conptyInheritCursor) {
3950
+ var _this = this;
3951
+ if (_useConptyDll === void 0) {
3952
+ _useConptyDll = false;
3953
+ }
3954
+ if (conptyInheritCursor === void 0) {
3955
+ conptyInheritCursor = false;
3956
+ }
3957
+ this._useConpty = _useConpty;
3958
+ this._useConptyDll = _useConptyDll;
3959
+ this._pid = 0;
3960
+ this._innerPid = 0;
3961
+ if (this._useConpty === void 0 || this._useConpty === true) {
3962
+ this._useConpty = this._getWindowsBuildNumber() >= 18309;
3963
+ }
3964
+ if (this._useConpty) {
3965
+ if (!conptyNative) {
3966
+ conptyNative = utils_1.loadNativeModule("conpty").module;
3967
+ }
3968
+ } else {
3969
+ if (!winptyNative) {
3970
+ winptyNative = utils_1.loadNativeModule("pty").module;
3971
+ }
3972
+ }
3973
+ this._ptyNative = this._useConpty ? conptyNative : winptyNative;
3974
+ cwd = path17.resolve(cwd);
3975
+ var commandLine = argsToCommandLine(file, args);
3976
+ var term;
3977
+ if (this._useConpty) {
3978
+ term = this._ptyNative.startProcess(file, cols, rows, debug, this._generatePipeName(), conptyInheritCursor, this._useConptyDll);
3979
+ } else {
3980
+ term = this._ptyNative.startProcess(file, commandLine, env, cwd, cols, rows, debug);
3981
+ this._pid = term.pid;
3982
+ this._innerPid = term.innerPid;
3983
+ }
3984
+ this._fd = term.fd;
3985
+ this._pty = term.pty;
3986
+ this._outSocket = new net_1.Socket();
3987
+ this._outSocket.setEncoding("utf8");
3988
+ this._conoutSocketWorker = new windowsConoutConnection_1.ConoutConnection(term.conout, this._useConptyDll);
3989
+ this._conoutSocketWorker.onReady(function() {
3990
+ _this._conoutSocketWorker.connectSocket(_this._outSocket);
3991
+ });
3992
+ this._outSocket.on("connect", function() {
3993
+ _this._outSocket.emit("ready_datapipe");
3994
+ });
3995
+ var inSocketFD = fs19.openSync(term.conin, "w");
3996
+ this._inSocket = new net_1.Socket({
3997
+ fd: inSocketFD,
3998
+ readable: false,
3999
+ writable: true
4000
+ });
4001
+ this._inSocket.setEncoding("utf8");
4002
+ if (this._useConpty) {
4003
+ var connect = this._ptyNative.connect(this._pty, commandLine, cwd, env, this._useConptyDll, function(c) {
4004
+ return _this._$onProcessExit(c);
4005
+ });
4006
+ this._innerPid = connect.pid;
4007
+ }
4008
+ }
4009
+ Object.defineProperty(WindowsPtyAgent2.prototype, "inSocket", {
4010
+ get: function() {
4011
+ return this._inSocket;
4012
+ },
4013
+ enumerable: false,
4014
+ configurable: true
4015
+ });
4016
+ Object.defineProperty(WindowsPtyAgent2.prototype, "outSocket", {
4017
+ get: function() {
4018
+ return this._outSocket;
4019
+ },
4020
+ enumerable: false,
4021
+ configurable: true
4022
+ });
4023
+ Object.defineProperty(WindowsPtyAgent2.prototype, "fd", {
4024
+ get: function() {
4025
+ return this._fd;
4026
+ },
4027
+ enumerable: false,
4028
+ configurable: true
4029
+ });
4030
+ Object.defineProperty(WindowsPtyAgent2.prototype, "innerPid", {
4031
+ get: function() {
4032
+ return this._innerPid;
4033
+ },
4034
+ enumerable: false,
4035
+ configurable: true
4036
+ });
4037
+ Object.defineProperty(WindowsPtyAgent2.prototype, "pty", {
4038
+ get: function() {
4039
+ return this._pty;
4040
+ },
4041
+ enumerable: false,
4042
+ configurable: true
4043
+ });
4044
+ WindowsPtyAgent2.prototype.resize = function(cols, rows) {
4045
+ if (this._useConpty) {
4046
+ if (this._exitCode !== void 0) {
4047
+ throw new Error("Cannot resize a pty that has already exited");
4048
+ }
4049
+ this._ptyNative.resize(this._pty, cols, rows, this._useConptyDll);
4050
+ return;
4051
+ }
4052
+ this._ptyNative.resize(this._pid, cols, rows);
4053
+ };
4054
+ WindowsPtyAgent2.prototype.clear = function() {
4055
+ if (this._useConpty) {
4056
+ this._ptyNative.clear(this._pty, this._useConptyDll);
4057
+ }
4058
+ };
4059
+ WindowsPtyAgent2.prototype.kill = function() {
4060
+ var _this = this;
4061
+ if (this._useConpty) {
4062
+ if (!this._useConptyDll) {
4063
+ this._inSocket.readable = false;
4064
+ this._outSocket.readable = false;
4065
+ this._getConsoleProcessList().then(function(consoleProcessList) {
4066
+ consoleProcessList.forEach(function(pid) {
4067
+ try {
4068
+ process.kill(pid);
4069
+ } catch (e) {
4070
+ }
4071
+ });
4072
+ });
4073
+ this._ptyNative.kill(this._pty, this._useConptyDll);
4074
+ this._conoutSocketWorker.dispose();
4075
+ } else {
4076
+ this._inSocket.destroy();
4077
+ this._ptyNative.kill(this._pty, this._useConptyDll);
4078
+ this._outSocket.on("data", function() {
4079
+ _this._conoutSocketWorker.dispose();
4080
+ });
4081
+ }
4082
+ } else {
4083
+ var processList = this._ptyNative.getProcessList(this._pid);
4084
+ this._ptyNative.kill(this._pid, this._innerPid);
4085
+ processList.forEach(function(pid) {
4086
+ try {
4087
+ process.kill(pid);
4088
+ } catch (e) {
4089
+ }
4090
+ });
4091
+ }
4092
+ };
4093
+ WindowsPtyAgent2.prototype._getConsoleProcessList = function() {
4094
+ var _this = this;
4095
+ return new Promise(function(resolve) {
4096
+ var agent = child_process_1.fork(path17.join(__dirname, "conpty_console_list_agent"), [_this._innerPid.toString()]);
4097
+ agent.on("message", function(message) {
4098
+ clearTimeout(timeout);
4099
+ resolve(message.consoleProcessList);
4100
+ });
4101
+ var timeout = setTimeout(function() {
4102
+ agent.kill();
4103
+ resolve([_this._innerPid]);
4104
+ }, 5e3);
4105
+ });
4106
+ };
4107
+ Object.defineProperty(WindowsPtyAgent2.prototype, "exitCode", {
4108
+ get: function() {
4109
+ if (this._useConpty) {
4110
+ return this._exitCode;
4111
+ }
4112
+ var winptyExitCode = this._ptyNative.getExitCode(this._innerPid);
4113
+ return winptyExitCode === -1 ? void 0 : winptyExitCode;
4114
+ },
4115
+ enumerable: false,
4116
+ configurable: true
4117
+ });
4118
+ WindowsPtyAgent2.prototype._getWindowsBuildNumber = function() {
4119
+ var osVersion = /(\d+)\.(\d+)\.(\d+)/g.exec(os5.release());
4120
+ var buildNumber = 0;
4121
+ if (osVersion && osVersion.length === 4) {
4122
+ buildNumber = parseInt(osVersion[3]);
4123
+ }
4124
+ return buildNumber;
4125
+ };
4126
+ WindowsPtyAgent2.prototype._generatePipeName = function() {
4127
+ return "conpty-" + Math.random() * 1e7;
4128
+ };
4129
+ WindowsPtyAgent2.prototype._$onProcessExit = function(exitCode) {
4130
+ var _this = this;
4131
+ this._exitCode = exitCode;
4132
+ if (!this._useConptyDll) {
4133
+ this._flushDataAndCleanUp();
4134
+ this._outSocket.on("data", function() {
4135
+ return _this._flushDataAndCleanUp();
4136
+ });
4137
+ }
4138
+ };
4139
+ WindowsPtyAgent2.prototype._flushDataAndCleanUp = function() {
4140
+ var _this = this;
4141
+ if (this._useConptyDll) {
4142
+ return;
4143
+ }
4144
+ if (this._closeTimeout) {
4145
+ clearTimeout(this._closeTimeout);
4146
+ }
4147
+ this._closeTimeout = setTimeout(function() {
4148
+ return _this._cleanUpProcess();
4149
+ }, FLUSH_DATA_INTERVAL);
4150
+ };
4151
+ WindowsPtyAgent2.prototype._cleanUpProcess = function() {
4152
+ if (this._useConptyDll) {
4153
+ return;
4154
+ }
4155
+ this._inSocket.readable = false;
4156
+ this._outSocket.readable = false;
4157
+ this._outSocket.destroy();
4158
+ };
4159
+ return WindowsPtyAgent2;
4160
+ })()
4161
+ );
4162
+ exports.WindowsPtyAgent = WindowsPtyAgent;
4163
+ function argsToCommandLine(file, args) {
4164
+ if (isCommandLine(args)) {
4165
+ if (args.length === 0) {
4166
+ return file;
4167
+ }
4168
+ return argsToCommandLine(file, []) + " " + args;
4169
+ }
4170
+ var argv = [file];
4171
+ Array.prototype.push.apply(argv, args);
4172
+ var result = "";
4173
+ for (var argIndex = 0; argIndex < argv.length; argIndex++) {
4174
+ if (argIndex > 0) {
4175
+ result += " ";
4176
+ }
4177
+ var arg = argv[argIndex];
4178
+ var hasLopsidedEnclosingQuote = xOr(arg[0] !== '"', arg[arg.length - 1] !== '"');
4179
+ var hasNoEnclosingQuotes = arg[0] !== '"' && arg[arg.length - 1] !== '"';
4180
+ var quote = arg === "" || (arg.indexOf(" ") !== -1 || arg.indexOf(" ") !== -1) && (arg.length > 1 && (hasLopsidedEnclosingQuote || hasNoEnclosingQuotes));
4181
+ if (quote) {
4182
+ result += '"';
4183
+ }
4184
+ var bsCount = 0;
4185
+ for (var i = 0; i < arg.length; i++) {
4186
+ var p = arg[i];
4187
+ if (p === "\\") {
4188
+ bsCount++;
4189
+ } else if (p === '"') {
4190
+ result += repeatText("\\", bsCount * 2 + 1);
4191
+ result += '"';
4192
+ bsCount = 0;
3292
4193
  } else {
3293
- matchRegex = new RegExp(exactPattern, "g");
4194
+ result += repeatText("\\", bsCount);
4195
+ bsCount = 0;
4196
+ result += p;
3294
4197
  }
3295
4198
  }
3296
- const matches = matchRegex ? [...currentContent.matchAll(matchRegex)] : [];
3297
- instances = matches.length;
3298
- if (instances === 0) {
3299
- return `ERROR: Could not find match for "content_to_replace" in [${targetPath}]. Check for whitespace discrepancies or ReadFile to get exact content.`;
4199
+ if (quote) {
4200
+ result += repeatText("\\", bsCount * 2);
4201
+ result += '"';
4202
+ } else {
4203
+ result += repeatText("\\", bsCount);
3300
4204
  }
3301
- if (instances > 1) {
3302
- return `ERROR: Unable to find unique match. [${instances}] instances of the specified "content_to_replace" were found in [${targetPath}]. Try providing more context (surrounding lines) to make the match unique.`;
4205
+ }
4206
+ return result;
4207
+ }
4208
+ exports.argsToCommandLine = argsToCommandLine;
4209
+ function isCommandLine(args) {
4210
+ return typeof args === "string";
4211
+ }
4212
+ function repeatText(text, count) {
4213
+ var result = "";
4214
+ for (var i = 0; i < count; i++) {
4215
+ result += text;
4216
+ }
4217
+ return result;
4218
+ }
4219
+ function xOr(arg1, arg2) {
4220
+ return arg1 && !arg2 || !arg1 && arg2;
4221
+ }
4222
+ }
4223
+ });
4224
+
4225
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsTerminal.js
4226
+ var require_windowsTerminal = __commonJS({
4227
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/windowsTerminal.js"(exports) {
4228
+ "use strict";
4229
+ var __extends = exports && exports.__extends || /* @__PURE__ */ (function() {
4230
+ var extendStatics = function(d, b) {
4231
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
4232
+ d2.__proto__ = b2;
4233
+ } || function(d2, b2) {
4234
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
4235
+ };
4236
+ return extendStatics(d, b);
4237
+ };
4238
+ return function(d, b) {
4239
+ extendStatics(d, b);
4240
+ function __() {
4241
+ this.constructor = d;
3303
4242
  }
3304
- startPos = matches[0].index;
3305
- const firstMatchContent = matches[0][0];
3306
- const newFileContent = currentContent.replace(matchRegex, (match, offset) => {
3307
- const lineStart = currentContent.lastIndexOf("\n", offset) + 1;
3308
- const leadingContext = currentContent.substring(lineStart, offset);
3309
- return adjustIndentation(content_to_add, match, leadingContext);
4243
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4244
+ };
4245
+ })();
4246
+ Object.defineProperty(exports, "__esModule", { value: true });
4247
+ exports.WindowsTerminal = void 0;
4248
+ var terminal_1 = require_terminal();
4249
+ var windowsPtyAgent_1 = require_windowsPtyAgent();
4250
+ var utils_1 = require_utils();
4251
+ var DEFAULT_FILE = "cmd.exe";
4252
+ var DEFAULT_NAME = "Windows Shell";
4253
+ var WindowsTerminal = (
4254
+ /** @class */
4255
+ (function(_super) {
4256
+ __extends(WindowsTerminal2, _super);
4257
+ function WindowsTerminal2(file, args, opt) {
4258
+ var _this = _super.call(this, opt) || this;
4259
+ _this._checkType("args", args, "string", true);
4260
+ args = args || [];
4261
+ file = file || DEFAULT_FILE;
4262
+ opt = opt || {};
4263
+ opt.env = opt.env || process.env;
4264
+ if (opt.encoding) {
4265
+ console.warn("Setting encoding on Windows is not supported");
4266
+ }
4267
+ var env = utils_1.assign({}, opt.env);
4268
+ _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
4269
+ _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
4270
+ var cwd = opt.cwd || process.cwd();
4271
+ var name = opt.name || env.TERM || DEFAULT_NAME;
4272
+ var parsedEnv = _this._parseEnv(env);
4273
+ _this._isReady = false;
4274
+ _this._deferreds = [];
4275
+ _this._agent = new windowsPtyAgent_1.WindowsPtyAgent(file, args, parsedEnv, cwd, _this._cols, _this._rows, false, opt.useConpty, opt.useConptyDll, opt.conptyInheritCursor);
4276
+ _this._socket = _this._agent.outSocket;
4277
+ _this._pid = _this._agent.innerPid;
4278
+ _this._fd = _this._agent.fd;
4279
+ _this._pty = _this._agent.pty;
4280
+ _this._socket.on("ready_datapipe", function() {
4281
+ _this._socket.once("data", function() {
4282
+ if (!_this._isReady) {
4283
+ _this._isReady = true;
4284
+ _this._deferreds.forEach(function(fn) {
4285
+ fn.run();
4286
+ });
4287
+ _this._deferreds = [];
4288
+ }
4289
+ });
4290
+ _this._socket.on("error", function(err) {
4291
+ _this._close();
4292
+ if (err.code) {
4293
+ if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO"))
4294
+ return;
4295
+ }
4296
+ if (_this.listeners("error").length < 2) {
4297
+ throw err;
4298
+ }
4299
+ });
4300
+ _this._socket.on("close", function() {
4301
+ _this.emit("exit", _this._agent.exitCode);
4302
+ _this._close();
4303
+ });
4304
+ });
4305
+ _this._file = file;
4306
+ _this._name = name;
4307
+ _this._readable = true;
4308
+ _this._writable = true;
4309
+ _this._forwardEvents();
4310
+ return _this;
4311
+ }
4312
+ WindowsTerminal2.prototype._write = function(data) {
4313
+ this._defer(this._doWrite, data);
4314
+ };
4315
+ WindowsTerminal2.prototype._doWrite = function(data) {
4316
+ this._agent.inSocket.write(data);
4317
+ };
4318
+ WindowsTerminal2.open = function(options) {
4319
+ throw new Error("open() not supported on windows, use Fork() instead.");
4320
+ };
4321
+ WindowsTerminal2.prototype.resize = function(cols, rows) {
4322
+ var _this = this;
4323
+ if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
4324
+ throw new Error("resizing must be done using positive cols and rows");
4325
+ }
4326
+ this._deferNoArgs(function() {
4327
+ _this._agent.resize(cols, rows);
4328
+ _this._cols = cols;
4329
+ _this._rows = rows;
4330
+ });
4331
+ };
4332
+ WindowsTerminal2.prototype.clear = function() {
4333
+ var _this = this;
4334
+ this._deferNoArgs(function() {
4335
+ _this._agent.clear();
4336
+ });
4337
+ };
4338
+ WindowsTerminal2.prototype.destroy = function() {
4339
+ var _this = this;
4340
+ this._deferNoArgs(function() {
4341
+ _this.kill();
4342
+ });
4343
+ };
4344
+ WindowsTerminal2.prototype.kill = function(signal) {
4345
+ var _this = this;
4346
+ this._deferNoArgs(function() {
4347
+ if (signal) {
4348
+ throw new Error("Signals not supported on windows.");
4349
+ }
4350
+ _this._close();
4351
+ _this._agent.kill();
4352
+ });
4353
+ };
4354
+ WindowsTerminal2.prototype._deferNoArgs = function(deferredFn) {
4355
+ var _this = this;
4356
+ if (this._isReady) {
4357
+ deferredFn.call(this);
4358
+ return;
4359
+ }
4360
+ this._deferreds.push({
4361
+ run: function() {
4362
+ return deferredFn.call(_this);
4363
+ }
4364
+ });
4365
+ };
4366
+ WindowsTerminal2.prototype._defer = function(deferredFn, arg) {
4367
+ var _this = this;
4368
+ if (this._isReady) {
4369
+ deferredFn.call(this, arg);
4370
+ return;
4371
+ }
4372
+ this._deferreds.push({
4373
+ run: function() {
4374
+ return deferredFn.call(_this, arg);
4375
+ }
4376
+ });
4377
+ };
4378
+ Object.defineProperty(WindowsTerminal2.prototype, "process", {
4379
+ get: function() {
4380
+ return this._name;
4381
+ },
4382
+ enumerable: false,
4383
+ configurable: true
4384
+ });
4385
+ Object.defineProperty(WindowsTerminal2.prototype, "master", {
4386
+ get: function() {
4387
+ throw new Error("master is not supported on Windows");
4388
+ },
4389
+ enumerable: false,
4390
+ configurable: true
4391
+ });
4392
+ Object.defineProperty(WindowsTerminal2.prototype, "slave", {
4393
+ get: function() {
4394
+ throw new Error("slave is not supported on Windows");
4395
+ },
4396
+ enumerable: false,
4397
+ configurable: true
3310
4398
  });
3311
- const firstLineStart = currentContent.lastIndexOf("\n", startPos) + 1;
3312
- const firstLeadingContext = currentContent.substring(firstLineStart, startPos);
3313
- const finalContentToAdd = adjustIndentation(content_to_add, firstMatchContent, firstLeadingContext);
3314
- const finalContentToReplace = firstMatchContent;
3315
- fs10.writeFileSync(absolutePath, newFileContent, "utf8");
3316
- const allOriginalLines = currentContent.split(/\r?\n/);
3317
- const startLine = currentContent.substring(0, startPos).split(/\r?\n/).length;
3318
- const oldLines = content_to_replace.split(/\r?\n/);
3319
- const endLine = startLine + oldLines.length - 1;
3320
- let diffText = `SUCCESS: File [${targetPath}] updated. [${instances}] instances replaced.
4399
+ return WindowsTerminal2;
4400
+ })(terminal_1.Terminal)
4401
+ );
4402
+ exports.WindowsTerminal = WindowsTerminal;
4403
+ }
4404
+ });
3321
4405
 
3322
- `;
3323
- diffText += `[DIFF_START]
3324
- `;
3325
- const contextStart = Math.max(0, startLine - 16);
3326
- for (let i = contextStart; i < startLine - 1; i++) {
3327
- diffText += `[UI_CONTEXT] ${i + 1}|${allOriginalLines[i]}
3328
- `;
4406
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/unixTerminal.js
4407
+ var require_unixTerminal = __commonJS({
4408
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/unixTerminal.js"(exports) {
4409
+ "use strict";
4410
+ var __extends = exports && exports.__extends || /* @__PURE__ */ (function() {
4411
+ var extendStatics = function(d, b) {
4412
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
4413
+ d2.__proto__ = b2;
4414
+ } || function(d2, b2) {
4415
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
4416
+ };
4417
+ return extendStatics(d, b);
4418
+ };
4419
+ return function(d, b) {
4420
+ extendStatics(d, b);
4421
+ function __() {
4422
+ this.constructor = d;
3329
4423
  }
3330
- const lineStartPos = currentContent.lastIndexOf("\n", startPos) + 1;
3331
- const affectedEndPos = startPos + content_to_replace.length;
3332
- const lineEndPos = currentContent.indexOf("\n", affectedEndPos);
3333
- const actualEndPos = lineEndPos === -1 ? currentContent.length : lineEndPos;
3334
- const fullOldLines = currentContent.substring(lineStartPos, actualEndPos).split("\n");
3335
- const newAffectedEndPos = startPos + finalContentToAdd.length;
3336
- const newLineEndPos = newFileContent.indexOf("\n", newAffectedEndPos);
3337
- const actualNewEndPos = newLineEndPos === -1 ? newFileContent.length : newLineEndPos;
3338
- const fullNewLines = newFileContent.substring(lineStartPos, actualNewEndPos).split("\n");
3339
- fullOldLines.forEach((line, i) => {
3340
- diffText += `-${startLine + i}|${line}
3341
- `;
4424
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4425
+ };
4426
+ })();
4427
+ Object.defineProperty(exports, "__esModule", { value: true });
4428
+ exports.UnixTerminal = void 0;
4429
+ var fs19 = __require("fs");
4430
+ var path17 = __require("path");
4431
+ var tty = __require("tty");
4432
+ var terminal_1 = require_terminal();
4433
+ var utils_1 = require_utils();
4434
+ var native = utils_1.loadNativeModule("pty");
4435
+ var pty3 = native.module;
4436
+ var helperPath = native.dir + "/spawn-helper";
4437
+ helperPath = path17.resolve(__dirname, helperPath);
4438
+ helperPath = helperPath.replace("app.asar", "app.asar.unpacked");
4439
+ helperPath = helperPath.replace("node_modules.asar", "node_modules.asar.unpacked");
4440
+ var DEFAULT_FILE = "sh";
4441
+ var DEFAULT_NAME = "xterm";
4442
+ var DESTROY_SOCKET_TIMEOUT_MS = 200;
4443
+ var UnixTerminal = (
4444
+ /** @class */
4445
+ (function(_super) {
4446
+ __extends(UnixTerminal2, _super);
4447
+ function UnixTerminal2(file, args, opt) {
4448
+ var _a, _b;
4449
+ var _this = _super.call(this, opt) || this;
4450
+ _this._boundClose = false;
4451
+ _this._emittedClose = false;
4452
+ if (typeof args === "string") {
4453
+ throw new Error("args as a string is not supported on unix.");
4454
+ }
4455
+ args = args || [];
4456
+ file = file || DEFAULT_FILE;
4457
+ opt = opt || {};
4458
+ opt.env = opt.env || process.env;
4459
+ _this._cols = opt.cols || terminal_1.DEFAULT_COLS;
4460
+ _this._rows = opt.rows || terminal_1.DEFAULT_ROWS;
4461
+ var uid = (_a = opt.uid) !== null && _a !== void 0 ? _a : -1;
4462
+ var gid = (_b = opt.gid) !== null && _b !== void 0 ? _b : -1;
4463
+ var env = utils_1.assign({}, opt.env);
4464
+ if (opt.env === process.env) {
4465
+ _this._sanitizeEnv(env);
4466
+ }
4467
+ var cwd = opt.cwd || process.cwd();
4468
+ env.PWD = cwd;
4469
+ var name = opt.name || env.TERM || DEFAULT_NAME;
4470
+ env.TERM = name;
4471
+ var parsedEnv = _this._parseEnv(env);
4472
+ var encoding = opt.encoding === void 0 ? "utf8" : opt.encoding;
4473
+ var onexit = function(code, signal) {
4474
+ if (!_this._emittedClose) {
4475
+ if (_this._boundClose) {
4476
+ return;
4477
+ }
4478
+ _this._boundClose = true;
4479
+ var timeout_1 = setTimeout(function() {
4480
+ timeout_1 = null;
4481
+ _this._socket.destroy();
4482
+ }, DESTROY_SOCKET_TIMEOUT_MS);
4483
+ _this.once("close", function() {
4484
+ if (timeout_1 !== null) {
4485
+ clearTimeout(timeout_1);
4486
+ }
4487
+ _this.emit("exit", code, signal);
4488
+ });
4489
+ return;
4490
+ }
4491
+ _this.emit("exit", code, signal);
4492
+ };
4493
+ var term = pty3.fork(file, args, parsedEnv, cwd, _this._cols, _this._rows, uid, gid, encoding === "utf8", helperPath, onexit);
4494
+ _this._socket = new tty.ReadStream(term.fd);
4495
+ if (encoding !== null) {
4496
+ _this._socket.setEncoding(encoding);
4497
+ }
4498
+ _this._writeStream = new CustomWriteStream(term.fd, encoding || void 0);
4499
+ _this._socket.on("error", function(err) {
4500
+ if (err.code) {
4501
+ if (~err.code.indexOf("EAGAIN")) {
4502
+ return;
4503
+ }
4504
+ }
4505
+ _this._close();
4506
+ if (!_this._emittedClose) {
4507
+ _this._emittedClose = true;
4508
+ _this.emit("close");
4509
+ }
4510
+ if (err.code) {
4511
+ if (~err.code.indexOf("errno 5") || ~err.code.indexOf("EIO")) {
4512
+ return;
4513
+ }
4514
+ }
4515
+ if (_this.listeners("error").length < 2) {
4516
+ throw err;
4517
+ }
4518
+ });
4519
+ _this._pid = term.pid;
4520
+ _this._fd = term.fd;
4521
+ _this._pty = term.pty;
4522
+ _this._file = file;
4523
+ _this._name = name;
4524
+ _this._readable = true;
4525
+ _this._writable = true;
4526
+ _this._socket.on("close", function() {
4527
+ if (_this._emittedClose) {
4528
+ return;
4529
+ }
4530
+ _this._emittedClose = true;
4531
+ _this._close();
4532
+ _this.emit("close");
4533
+ });
4534
+ _this._forwardEvents();
4535
+ return _this;
4536
+ }
4537
+ Object.defineProperty(UnixTerminal2.prototype, "master", {
4538
+ get: function() {
4539
+ return this._master;
4540
+ },
4541
+ enumerable: false,
4542
+ configurable: true
3342
4543
  });
3343
- let currentNewLine = startLine;
3344
- fullNewLines.forEach((line) => {
3345
- diffText += `+${currentNewLine}|${line}
3346
- `;
3347
- currentNewLine++;
4544
+ Object.defineProperty(UnixTerminal2.prototype, "slave", {
4545
+ get: function() {
4546
+ return this._slave;
4547
+ },
4548
+ enumerable: false,
4549
+ configurable: true
3348
4550
  });
3349
- const linesAffected = fullOldLines.length;
3350
- const originalContextIdx = startLine + linesAffected - 1;
3351
- for (let i = originalContextIdx; i < Math.min(allOriginalLines.length, originalContextIdx + 15); i++) {
3352
- diffText += `[UI_CONTEXT] ${currentNewLine}|${allOriginalLines[i]}
3353
- `;
3354
- currentNewLine++;
3355
- }
3356
- diffText += `[DIFF_END]`;
3357
- return diffText;
3358
- } catch (err) {
3359
- return `ERROR: Failed to update file [${targetPath}]: ${err.message}`;
3360
- }
3361
- };
4551
+ UnixTerminal2.prototype._write = function(data) {
4552
+ this._writeStream.write(data);
4553
+ };
4554
+ Object.defineProperty(UnixTerminal2.prototype, "fd", {
4555
+ /* Accessors */
4556
+ get: function() {
4557
+ return this._fd;
4558
+ },
4559
+ enumerable: false,
4560
+ configurable: true
4561
+ });
4562
+ Object.defineProperty(UnixTerminal2.prototype, "ptsName", {
4563
+ get: function() {
4564
+ return this._pty;
4565
+ },
4566
+ enumerable: false,
4567
+ configurable: true
4568
+ });
4569
+ UnixTerminal2.open = function(opt) {
4570
+ var self = Object.create(UnixTerminal2.prototype);
4571
+ opt = opt || {};
4572
+ if (arguments.length > 1) {
4573
+ opt = {
4574
+ cols: arguments[1],
4575
+ rows: arguments[2]
4576
+ };
4577
+ }
4578
+ var cols = opt.cols || terminal_1.DEFAULT_COLS;
4579
+ var rows = opt.rows || terminal_1.DEFAULT_ROWS;
4580
+ var encoding = opt.encoding === void 0 ? "utf8" : opt.encoding;
4581
+ var term = pty3.open(cols, rows);
4582
+ self._master = new tty.ReadStream(term.master);
4583
+ if (encoding !== null) {
4584
+ self._master.setEncoding(encoding);
4585
+ }
4586
+ self._master.resume();
4587
+ self._slave = new tty.ReadStream(term.slave);
4588
+ if (encoding !== null) {
4589
+ self._slave.setEncoding(encoding);
4590
+ }
4591
+ self._slave.resume();
4592
+ self._socket = self._master;
4593
+ self._pid = -1;
4594
+ self._fd = term.master;
4595
+ self._pty = term.pty;
4596
+ self._file = process.argv[0] || "node";
4597
+ self._name = process.env.TERM || "";
4598
+ self._readable = true;
4599
+ self._writable = true;
4600
+ self._socket.on("error", function(err) {
4601
+ self._close();
4602
+ if (self.listeners("error").length < 2) {
4603
+ throw err;
4604
+ }
4605
+ });
4606
+ self._socket.on("close", function() {
4607
+ self._close();
4608
+ });
4609
+ return self;
4610
+ };
4611
+ UnixTerminal2.prototype.destroy = function() {
4612
+ var _this = this;
4613
+ this._close();
4614
+ this._socket.once("close", function() {
4615
+ _this.kill("SIGHUP");
4616
+ });
4617
+ this._socket.destroy();
4618
+ this._writeStream.dispose();
4619
+ };
4620
+ UnixTerminal2.prototype.kill = function(signal) {
4621
+ try {
4622
+ process.kill(this.pid, signal || "SIGHUP");
4623
+ } catch (e) {
4624
+ }
4625
+ };
4626
+ Object.defineProperty(UnixTerminal2.prototype, "process", {
4627
+ /**
4628
+ * Gets the name of the process.
4629
+ */
4630
+ get: function() {
4631
+ if (process.platform === "darwin") {
4632
+ var title = pty3.process(this._fd);
4633
+ return title !== "kernel_task" ? title : this._file;
4634
+ }
4635
+ return pty3.process(this._fd, this._pty) || this._file;
4636
+ },
4637
+ enumerable: false,
4638
+ configurable: true
4639
+ });
4640
+ UnixTerminal2.prototype.resize = function(cols, rows) {
4641
+ if (cols <= 0 || rows <= 0 || isNaN(cols) || isNaN(rows) || cols === Infinity || rows === Infinity) {
4642
+ throw new Error("resizing must be done using positive cols and rows");
4643
+ }
4644
+ pty3.resize(this._fd, cols, rows);
4645
+ this._cols = cols;
4646
+ this._rows = rows;
4647
+ };
4648
+ UnixTerminal2.prototype.clear = function() {
4649
+ };
4650
+ UnixTerminal2.prototype._sanitizeEnv = function(env) {
4651
+ delete env["TMUX"];
4652
+ delete env["TMUX_PANE"];
4653
+ delete env["STY"];
4654
+ delete env["WINDOW"];
4655
+ delete env["WINDOWID"];
4656
+ delete env["TERMCAP"];
4657
+ delete env["COLUMNS"];
4658
+ delete env["LINES"];
4659
+ };
4660
+ return UnixTerminal2;
4661
+ })(terminal_1.Terminal)
4662
+ );
4663
+ exports.UnixTerminal = UnixTerminal;
4664
+ var CustomWriteStream = (
4665
+ /** @class */
4666
+ (function() {
4667
+ function CustomWriteStream2(_fd, _encoding) {
4668
+ this._fd = _fd;
4669
+ this._encoding = _encoding;
4670
+ this._writeQueue = [];
4671
+ }
4672
+ CustomWriteStream2.prototype.dispose = function() {
4673
+ clearImmediate(this._writeImmediate);
4674
+ this._writeImmediate = void 0;
4675
+ };
4676
+ CustomWriteStream2.prototype.write = function(data) {
4677
+ var buffer = typeof data === "string" ? Buffer.from(data, this._encoding) : Buffer.from(data);
4678
+ if (buffer.byteLength !== 0) {
4679
+ this._writeQueue.push({ buffer, offset: 0 });
4680
+ if (this._writeQueue.length === 1) {
4681
+ this._processWriteQueue();
4682
+ }
4683
+ }
4684
+ };
4685
+ CustomWriteStream2.prototype._processWriteQueue = function() {
4686
+ var _this = this;
4687
+ this._writeImmediate = void 0;
4688
+ if (this._writeQueue.length === 0) {
4689
+ return;
4690
+ }
4691
+ var task = this._writeQueue[0];
4692
+ fs19.write(this._fd, task.buffer, task.offset, function(err, written) {
4693
+ if (err) {
4694
+ if ("code" in err && err.code === "EAGAIN") {
4695
+ _this._writeImmediate = setImmediate(function() {
4696
+ return _this._processWriteQueue();
4697
+ });
4698
+ } else {
4699
+ _this._writeQueue.length = 0;
4700
+ console.error("Unhandled pty write error", err);
4701
+ }
4702
+ return;
4703
+ }
4704
+ task.offset += written;
4705
+ if (task.offset >= task.buffer.byteLength) {
4706
+ _this._writeQueue.shift();
4707
+ }
4708
+ _this._processWriteQueue();
4709
+ });
4710
+ };
4711
+ return CustomWriteStream2;
4712
+ })()
4713
+ );
4714
+ }
4715
+ });
4716
+
4717
+ // node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/index.js
4718
+ var require_lib = __commonJS({
4719
+ "node_modules/.pnpm/node-pty@1.1.0/node_modules/node-pty/lib/index.js"(exports) {
4720
+ "use strict";
4721
+ Object.defineProperty(exports, "__esModule", { value: true });
4722
+ exports.native = exports.open = exports.createTerminal = exports.fork = exports.spawn = void 0;
4723
+ var utils_1 = require_utils();
4724
+ var terminalCtor;
4725
+ if (process.platform === "win32") {
4726
+ terminalCtor = require_windowsTerminal().WindowsTerminal;
4727
+ } else {
4728
+ terminalCtor = require_unixTerminal().UnixTerminal;
4729
+ }
4730
+ function spawn4(file, args, opt) {
4731
+ return new terminalCtor(file, args, opt);
4732
+ }
4733
+ exports.spawn = spawn4;
4734
+ function fork(file, args, opt) {
4735
+ return new terminalCtor(file, args, opt);
4736
+ }
4737
+ exports.fork = fork;
4738
+ function createTerminal(file, args, opt) {
4739
+ return new terminalCtor(file, args, opt);
4740
+ }
4741
+ exports.createTerminal = createTerminal;
4742
+ function open(options) {
4743
+ return terminalCtor.open(options);
4744
+ }
4745
+ exports.open = open;
4746
+ exports.native = process.platform !== "win32" ? utils_1.loadNativeModule("pty").module : null;
3362
4747
  }
3363
4748
  });
3364
4749
 
3365
4750
  // src/tools/exec_command.js
3366
4751
  import { spawn } from "child_process";
3367
- var activeChildProcess, writeToActiveCommand, terminateActiveCommand, adjustWindowsCommand, exec_command;
4752
+ var pty, activeChildProcess, isActiveCommandPty, writeToActiveCommand, terminateActiveCommand, adjustWindowsCommand, exec_command, runStandardSpawn;
3368
4753
  var init_exec_command = __esm({
3369
- "src/tools/exec_command.js"() {
4754
+ async "src/tools/exec_command.js"() {
3370
4755
  init_arg_parser();
4756
+ pty = null;
4757
+ try {
4758
+ const ptyModule = await Promise.resolve().then(() => __toESM(require_lib(), 1));
4759
+ pty = ptyModule.default || ptyModule;
4760
+ } catch (err) {
4761
+ }
3371
4762
  activeChildProcess = null;
4763
+ isActiveCommandPty = false;
3372
4764
  writeToActiveCommand = (data) => {
3373
4765
  try {
3374
- if (activeChildProcess && activeChildProcess.stdin && activeChildProcess.stdin.writable) {
3375
- activeChildProcess.stdin.write(data);
4766
+ if (activeChildProcess) {
4767
+ if (isActiveCommandPty && typeof activeChildProcess.write === "function") {
4768
+ activeChildProcess.write(data);
4769
+ } else if (activeChildProcess.stdin && activeChildProcess.stdin.writable) {
4770
+ activeChildProcess.stdin.write(data);
4771
+ }
3376
4772
  }
3377
4773
  } catch (err) {
3378
4774
  }
@@ -3380,13 +4776,18 @@ var init_exec_command = __esm({
3380
4776
  terminateActiveCommand = () => {
3381
4777
  if (activeChildProcess) {
3382
4778
  try {
3383
- activeChildProcess.kill("SIGKILL");
4779
+ if (isActiveCommandPty && typeof activeChildProcess.destroy === "function") {
4780
+ activeChildProcess.destroy();
4781
+ } else if (typeof activeChildProcess.kill === "function") {
4782
+ activeChildProcess.kill("SIGKILL");
4783
+ }
3384
4784
  } catch (err) {
3385
4785
  }
3386
4786
  activeChildProcess = null;
4787
+ isActiveCommandPty = false;
3387
4788
  }
3388
4789
  };
3389
- adjustWindowsCommand = (command) => {
4790
+ adjustWindowsCommand = (command, usePowerShell = false) => {
3390
4791
  if (process.platform !== "win32") return command;
3391
4792
  const tokens = [];
3392
4793
  let current = "";
@@ -3423,7 +4824,7 @@ var init_exec_command = __esm({
3423
4824
  tokens.push(current);
3424
4825
  current = "";
3425
4826
  }
3426
- tokens.push("&");
4827
+ tokens.push(usePowerShell ? ";" : "&");
3427
4828
  } else if (char === "|" && !current.includes("://")) {
3428
4829
  if (current.length > 0) {
3429
4830
  tokens.push(current);
@@ -3516,7 +4917,7 @@ var init_exec_command = __esm({
3516
4917
  const { command: rawCommand } = parseArgs(args);
3517
4918
  const { onChunk } = options;
3518
4919
  if (!rawCommand) return 'ERROR: Missing "command" argument for exec_command.';
3519
- const command = adjustWindowsCommand(rawCommand);
4920
+ const isWin = process.platform === "win32";
3520
4921
  const systemSettings = options.systemSettings || {};
3521
4922
  const netEnv = {};
3522
4923
  if (systemSettings.networkAccess === false) {
@@ -3529,58 +4930,127 @@ var init_exec_command = __esm({
3529
4930
  netEnv.NO_PROXY = "localhost,127.0.0.1";
3530
4931
  }
3531
4932
  return new Promise((resolve) => {
3532
- const child = spawn(command, {
3533
- shell: true,
3534
- cwd: process.cwd(),
3535
- env: {
3536
- ...process.env,
3537
- CI: "false",
3538
- TERM: "xterm-256color",
3539
- FORCE_COLOR: "1",
3540
- ...netEnv
4933
+ const attempt = (usePowerShell) => {
4934
+ const command = adjustWindowsCommand(rawCommand, usePowerShell);
4935
+ const shell = isWin ? usePowerShell ? "powershell.exe" : "cmd.exe" : process.env.SHELL || "bash";
4936
+ const shellArgs = isWin ? usePowerShell ? ["-NoProfile", "-Command", command] : ["/c", command] : ["-c", command];
4937
+ if (pty) {
4938
+ try {
4939
+ const ptyProcess = pty.spawn(shell, shellArgs, {
4940
+ name: "xterm-256color",
4941
+ cols: options.cols || 120,
4942
+ rows: options.rows || 30,
4943
+ cwd: process.cwd(),
4944
+ env: {
4945
+ ...process.env,
4946
+ CI: "false",
4947
+ TERM: "xterm-256color",
4948
+ FORCE_COLOR: "1",
4949
+ ...netEnv
4950
+ }
4951
+ });
4952
+ activeChildProcess = ptyProcess;
4953
+ isActiveCommandPty = true;
4954
+ let output = "";
4955
+ ptyProcess.onData((data) => {
4956
+ output += data;
4957
+ if (onChunk) onChunk(data);
4958
+ });
4959
+ ptyProcess.onExit(({ exitCode }) => {
4960
+ activeChildProcess = null;
4961
+ const finalOutput = output || "Command executed with no output.";
4962
+ if (exitCode !== 0) {
4963
+ resolve(`ERROR: Command [${rawCommand}] failed with exit code [${exitCode}].
4964
+
4965
+ ${finalOutput}`);
4966
+ } else {
4967
+ resolve(`SUCCESS: Command [${rawCommand}] completed.
4968
+
4969
+ ${finalOutput}`);
4970
+ }
4971
+ });
4972
+ return true;
4973
+ } catch (err) {
4974
+ if (isWin && usePowerShell && err.code === "ENOENT") {
4975
+ return false;
4976
+ }
4977
+ runStandardSpawn(resolve, command, rawCommand, netEnv, onChunk, usePowerShell);
4978
+ return true;
4979
+ }
4980
+ } else {
4981
+ runStandardSpawn(resolve, command, rawCommand, netEnv, onChunk, usePowerShell);
4982
+ return true;
3541
4983
  }
3542
- });
3543
- activeChildProcess = child;
3544
- if (child.stdin) {
3545
- child.stdin.on("error", () => {
3546
- activeChildProcess = null;
3547
- });
4984
+ };
4985
+ if (isWin) {
4986
+ if (!attempt(true)) {
4987
+ attempt(false);
4988
+ }
4989
+ } else {
4990
+ attempt(false);
3548
4991
  }
3549
- let stdout = "";
3550
- let stderr = "";
3551
- child.stdout.on("data", (data) => {
3552
- const chunk = data.toString();
3553
- stdout += chunk;
3554
- if (onChunk) onChunk(chunk);
3555
- });
3556
- child.stderr.on("data", (data) => {
3557
- const chunk = data.toString();
3558
- stderr += chunk;
3559
- if (onChunk) onChunk(chunk);
3560
- });
3561
- child.on("close", (code) => {
4992
+ });
4993
+ };
4994
+ runStandardSpawn = (resolve, command, rawCommand, netEnv, onChunk, usePowerShell = true) => {
4995
+ const isWin = process.platform === "win32";
4996
+ const shell = isWin ? usePowerShell ? "powershell.exe" : "cmd.exe" : process.env.SHELL || "bash";
4997
+ const shellArgs = isWin ? usePowerShell ? ["-NoProfile", "-Command", command] : ["/c", command] : ["-c", command];
4998
+ const child = isWin ? spawn(shell, shellArgs, { cwd: process.cwd(), env: { ...process.env, ...netEnv } }) : spawn(command, {
4999
+ shell: true,
5000
+ cwd: process.cwd(),
5001
+ env: {
5002
+ ...process.env,
5003
+ CI: "false",
5004
+ TERM: "xterm-256color",
5005
+ FORCE_COLOR: "1",
5006
+ ...netEnv
5007
+ }
5008
+ });
5009
+ activeChildProcess = child;
5010
+ isActiveCommandPty = false;
5011
+ if (child.stdin) {
5012
+ child.stdin.on("error", () => {
3562
5013
  activeChildProcess = null;
3563
- const result = [];
3564
- if (stdout) result.push(`STDOUT:
5014
+ });
5015
+ }
5016
+ let stdout = "";
5017
+ let stderr = "";
5018
+ child.stdout.on("data", (data) => {
5019
+ const chunk = data.toString();
5020
+ stdout += chunk;
5021
+ if (onChunk) onChunk(chunk);
5022
+ });
5023
+ child.stderr.on("data", (data) => {
5024
+ const chunk = data.toString();
5025
+ stderr += chunk;
5026
+ if (onChunk) onChunk(chunk);
5027
+ });
5028
+ child.on("close", (code) => {
5029
+ activeChildProcess = null;
5030
+ const result = [];
5031
+ if (stdout) result.push(`STDOUT:
3565
5032
  ${stdout}`);
3566
- if (stderr) result.push(`STDERR:
5033
+ if (stderr) result.push(`STDERR:
3567
5034
  ${stderr}`);
3568
- if (code !== 0) result.push(`EXIT CODE: ${code}`);
3569
- const finalOutput = result.join("\n\n") || "Command executed with no output.";
3570
- if (code !== 0) {
3571
- resolve(`ERROR: Command [${rawCommand}] failed with exit code [${code}].
5035
+ if (code !== 0) result.push(`EXIT CODE: ${code}`);
5036
+ const finalOutput = result.join("\n\n") || "Command executed with no output.";
5037
+ if (code !== 0) {
5038
+ resolve(`ERROR: Command [${rawCommand}] failed with exit code [${code}].
3572
5039
 
3573
5040
  ${finalOutput}`);
3574
- } else {
3575
- resolve(`SUCCESS: Command [${rawCommand}] completed.
5041
+ } else {
5042
+ resolve(`SUCCESS: Command [${rawCommand}] completed.
3576
5043
 
3577
5044
  ${finalOutput}`);
3578
- }
3579
- });
3580
- child.on("error", (err) => {
3581
- activeChildProcess = null;
3582
- resolve(`ERROR: Failed to start command [${rawCommand}]: ${err.message}`);
3583
- });
5045
+ }
5046
+ });
5047
+ child.on("error", (err) => {
5048
+ if (isWin && usePowerShell && err.code === "ENOENT") {
5049
+ const cmdCommand = adjustWindowsCommand(rawCommand, false);
5050
+ return runStandardSpawn(resolve, cmdCommand, rawCommand, netEnv, onChunk, false);
5051
+ }
5052
+ activeChildProcess = null;
5053
+ resolve(`ERROR: Failed to start command [${rawCommand}]: ${err.message}`);
3584
5054
  });
3585
5055
  };
3586
5056
  }
@@ -3916,33 +5386,44 @@ var init_search_keyword = __esm({
3916
5386
  "src/tools/search_keyword.js"() {
3917
5387
  init_arg_parser();
3918
5388
  search_keyword = async (args) => {
3919
- const { keyword } = parseArgs(args);
5389
+ const { keyword, file } = parseArgs(args);
3920
5390
  if (!keyword) return 'ERROR: Missing "keyword" argument.';
3921
5391
  const isWindows = process.platform === "win32";
3922
5392
  const excludes = ["node_modules", ".git", "dist", ".next", ".gemini"];
3923
5393
  let command = "";
3924
- if (isWindows) {
3925
- const excludePattern = excludes.join("|").replace(/\./g, "\\.");
3926
- command = `powershell -Command "Get-ChildItem -Path . -Recurse -File | Where-Object { $_.FullName -notmatch '${excludePattern}' } | Select-String -Pattern '${keyword}' | Select-Object -First 150 | ForEach-Object { $rel = Resolve-Path $_.Path -Relative; '{0}:{1}:' -f $rel, $_.LineNumber }"`;
5394
+ if (file) {
5395
+ if (isWindows) {
5396
+ command = `powershell -Command "if (Test-Path '${file}') { Select-String -Path '${file}' -Pattern '${keyword}' | Select-Object -First 150 | ForEach-Object { $rel = Resolve-Path $_.Path -Relative; '{0}:{1}:' -f $rel, $_.LineNumber } } else { Write-Error 'File not found: ${file}' }"`;
5397
+ } else {
5398
+ command = `grep -HnI "${keyword}" "${file}" | head -n 150`;
5399
+ }
3927
5400
  } else {
3928
- const excludeDirArgs = excludes.map((d) => `--exclude-dir="${d}"`).join(" ");
3929
- command = `grep -rnI ${excludeDirArgs} "${keyword}" . | head -n 150`;
5401
+ if (isWindows) {
5402
+ const excludePattern = excludes.join("|").replace(/\./g, "\\.");
5403
+ command = `powershell -Command "Get-ChildItem -Path . -Recurse -File | Where-Object { $_.FullName -notmatch '${excludePattern}' } | Select-String -Pattern '${keyword}' | Select-Object -First 150 | ForEach-Object { $rel = Resolve-Path $_.Path -Relative; '{0}:{1}:' -f $rel, $_.LineNumber }"`;
5404
+ } else {
5405
+ const excludeDirArgs = excludes.map((d) => `--exclude-dir="${d}"`).join(" ");
5406
+ command = `grep -rnI ${excludeDirArgs} "${keyword}" . | head -n 150`;
5407
+ }
3930
5408
  }
3931
5409
  return new Promise((resolve) => {
3932
5410
  exec(command, { cwd: process.cwd(), maxBuffer: 15 * 1024 * 1024 }, (error, stdout, stderr) => {
5411
+ if (error && stderr && stderr.includes("File not found")) {
5412
+ return resolve(`ERROR: File not found: ${file}`);
5413
+ }
3933
5414
  if (error && error.code === 1 && !stdout) {
3934
- return resolve(`Found 0 matches for keyword: "${keyword}"`);
5415
+ return resolve(`Found 0 matches for keyword: "${keyword}"${file ? ` in file: ${file}` : ""}`);
3935
5416
  }
3936
5417
  if (error && !stdout) {
3937
5418
  return resolve(`ERROR: ${stderr || error.message}`);
3938
5419
  }
3939
5420
  const rawLines = stdout.trim().split("\n").filter((l) => l.trim() !== "");
3940
- if (rawLines.length === 0) return resolve(`Found 0 matches for keyword: "${keyword}"`);
5421
+ if (rawLines.length === 0) return resolve(`Found 0 matches for keyword: "${keyword}"${file ? ` in file: ${file}` : ""}`);
3941
5422
  const filteredLines = rawLines.filter((line) => {
3942
5423
  const lower = line.toLowerCase();
3943
5424
  return !lower.includes("node_modules") && !lower.includes(".git") && !lower.includes("dist") && !lower.includes(".next") && !lower.includes(".gemini");
3944
5425
  });
3945
- if (filteredLines.length === 0) return resolve(`Found 0 matches for keyword: "${keyword}"`);
5426
+ if (filteredLines.length === 0) return resolve(`Found 0 matches for keyword: "${keyword}"${file ? ` in file: ${file}` : ""}`);
3946
5427
  const matches = filteredLines.slice(0, 150).map((line) => {
3947
5428
  const firstColon = line.indexOf(":");
3948
5429
  const secondColon = line.indexOf(":", firstColon + 1);
@@ -4385,7 +5866,7 @@ var init_addMemScore = __esm({
4385
5866
  // src/utils/tools.js
4386
5867
  var TOOL_MAP, dispatchTool;
4387
5868
  var init_tools = __esm({
4388
- "src/utils/tools.js"() {
5869
+ async "src/utils/tools.js"() {
4389
5870
  init_web_search();
4390
5871
  init_web_scrape();
4391
5872
  init_memory();
@@ -4393,7 +5874,7 @@ var init_tools = __esm({
4393
5874
  init_view_file();
4394
5875
  init_write_file();
4395
5876
  init_update_file();
4396
- init_exec_command();
5877
+ await init_exec_command();
4397
5878
  init_read_folder();
4398
5879
  init_ask_user();
4399
5880
  init_write_pdf();
@@ -4462,11 +5943,11 @@ import path15 from "path";
4462
5943
  import fs16 from "fs";
4463
5944
  var client, TERMINATION_SIGNAL, signalTermination, TOOL_LABELS2, getToolDetail, runJanitorTask, getActiveToolContext, getContextSafeText, contextSafeReplace, getSanitizedText, detectToolCalls, initAI, consolidatePastMemories, getAIStream;
4464
5945
  var init_ai = __esm({
4465
- "src/utils/ai.js"() {
5946
+ async "src/utils/ai.js"() {
4466
5947
  init_prompts();
4467
5948
  init_history();
4468
5949
  init_usage();
4469
- init_tools();
5950
+ await init_tools();
4470
5951
  init_crypto();
4471
5952
  init_arg_parser();
4472
5953
  init_terminal();
@@ -5015,7 +6496,7 @@ ${newMemoryListStr}
5015
6496
  const isContext32k = (sessionStats?.tokens || 0) >= 32e3;
5016
6497
  const memoryPrompt = getMemoryPrompt(otherMemories, mainUserMemories, isMemoryEnabled, isContext32k);
5017
6498
  const dateTimeStr = (/* @__PURE__ */ new Date()).toLocaleString([], { year: "numeric", month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: true });
5018
- const getDirTree = (dir, prefix = "") => {
6499
+ const getDirTree = (dir, prefix = "", depth = 1) => {
5019
6500
  try {
5020
6501
  const files = fs16.readdirSync(dir);
5021
6502
  const sep = path15.sep;
@@ -5052,13 +6533,13 @@ ${newMemoryListStr}
5052
6533
  const stat = fs16.statSync(filePath);
5053
6534
  if (stat.isDirectory()) {
5054
6535
  const subFiles = fs16.readdirSync(filePath);
5055
- if (subFiles.length > 80) {
6536
+ if (subFiles.length > 80 || depth >= 7) {
5056
6537
  result += `${prefix}${connector}${file}${sep}...
5057
6538
  `;
5058
6539
  } else {
5059
6540
  result += `${prefix}${connector}${file}${sep}
5060
6541
  `;
5061
- result += getDirTree(filePath, childPrefix);
6542
+ result += getDirTree(filePath, childPrefix, depth + 1);
5062
6543
  }
5063
6544
  } else {
5064
6545
  result += `${prefix}${connector}${file}
@@ -5076,7 +6557,7 @@ ${newMemoryListStr}
5076
6557
  };
5077
6558
  yield { type: "status", content: "Gathering Context..." };
5078
6559
  let dirStructure = process.cwd() + "\n" + getDirTree(process.cwd());
5079
- const firstUserMsg = `[METADATA (PRIORITY: DYNAMIC)] Time: ${dateTimeStr} | v${versionFluxflow2}
6560
+ const firstUserMsg = `[SYSTEM METADATA (PRIORITY: DYNAMIC)] Time: ${dateTimeStr} | v${versionFluxflow2}
5080
6561
  CWD: ${process.cwd()}
5081
6562
  **DIRECTORY STRUCTURE**
5082
6563
  ${dirStructure}
@@ -5178,8 +6659,7 @@ ${thinkingLevel != "Fast" ? "[SYSTEM] **STRICTLY FOLLOW THINKING POLICY AS CRITI
5178
6659
  }
5179
6660
  const currentSystemInstruction = getSystemInstruction(profile, thinkingLevel, mode, systemSettings, isMemoryEnabled, MAX_LOOPS, loop + 1);
5180
6661
  const jitInstruction = `
5181
-
5182
- [SYSTEM] Tool result received. Analyze output and proceed with your turn.${thinkingLevel != "Fast" ? "**STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**" : ""}`;
6662
+ [SYSTEM] Tool result received. Analyze output and proceed with your turn${thinkingLevel != "Fast" ? ". **STRICTLY MAINTAIN THINKING POLICY. DO NOT START A RESPONSE WITHOUT <think> ... </think>**" : ""}`;
5183
6663
  const lastUserMsg = contents[contents.length - 1];
5184
6664
  let addedMarker = false;
5185
6665
  if (lastUserMsg && lastUserMsg.role === "user" && lastUserMsg.parts?.[0]?.text?.startsWith("[TOOL RESULT]")) {
@@ -5800,7 +7280,7 @@ ${boxBottom}` };
5800
7280
  const waitTime = Math.min(1e3 * Math.pow(2, inStreamRetryCount - 1), 24e3);
5801
7281
  if (turnText.trim().length > 0) {
5802
7282
  modifiedHistory.push({ role: "agent", text: turnText });
5803
- const recoveryText = "[SYSTEM: STREAM RECOVERY]\n- SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption.\n- NO REPETITION: Do not repeat any text already written.\n- NO RE-THINK: Do not restart or open <think> if reasoning already started.\n- MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start.\n- STEALTH: Do not mention/apologize for cutoff.\n- KEEP LENGTH: Maintain standard depth/length.";
7283
+ const recoveryText = "[SYSTEM]\n- SEAMLESS CONTINUATION: Resume immediately. Pick up from last words with zero gap/disruption\n- NO REPETITION: Do not repeat any text already written\n- NO RE-THINK: Do not restart or open <think> if reasoning already started. Continue the thinking and close thinking block with </think> if opened\n- MID-TOOL SAFETY: If cutoff was mid-tool call, restart that tool call from start\n- STEALTH: Do not mention/apologize for cutoff";
5804
7284
  if (toolResults.length > 0) {
5805
7285
  toolResults.forEach((tr, idx) => {
5806
7286
  if (idx === toolResults.length - 1) {
@@ -5820,7 +7300,7 @@ ${recoveryText}`
5820
7300
  accumulatedContext += turnText;
5821
7301
  }
5822
7302
  for (let i = waitTime / 1e3; i > 0; i--) {
5823
- yield { type: "status", content: `Error Occured. Recovering Stream (${inStreamRetryCount}/${MAX_RETRIES}) [${i}s]...` };
7303
+ yield { type: "status", content: `Error Occured. Recovering Stream (${inStreamRetryCount}/${MAX_RETRIES}) [Retrying in ${i}s]...` };
5824
7304
  await new Promise((resolve) => setTimeout(resolve, 1e3));
5825
7305
  }
5826
7306
  yield { type: "status", content: `Error Occured. Recovering Stream...` };
@@ -5835,14 +7315,14 @@ Error Log can be found in ${path15.join(LOGS_DIR, "agent", "error.log")}`);
5835
7315
  accumulatedContext = "";
5836
7316
  const waitTime = Math.min(1e3 * Math.pow(2, retryCount - 1), 32e3);
5837
7317
  isInitialAttempt = true;
5838
- yield { type: "status", content: `Retrying Connection (${retryCount}/${MAX_RETRIES}) [${(waitTime / 1e3).toFixed(0)}s]...` };
7318
+ yield { type: "status", content: `Trying to reach ${modelName} (${retryCount}/${MAX_RETRIES}) [Retrying in ${(waitTime / 1e3).toFixed(0)}s]...` };
5839
7319
  for (let i = waitTime / 1e3; i > 0; i--) {
5840
- yield { type: "status", content: `Retrying Connection (${retryCount}/${MAX_RETRIES}) [${i}s]...` };
7320
+ yield { type: "status", content: `Trying to reach ${modelName} (${retryCount}/${MAX_RETRIES}) [Retrying in ${i}s]...` };
5841
7321
  await new Promise((resolve) => setTimeout(resolve, 1e3));
5842
7322
  }
5843
- yield { type: "status", content: `Retrying Connection...` };
7323
+ yield { type: "status", content: `Trying to reach ${modelName}...` };
5844
7324
  } else {
5845
- throw new Error(`Model cannot be reached. (Failed ${MAX_RETRIES} times)
7325
+ throw new Error(`Model ${modelName} cannot be reached. (Failed ${MAX_RETRIES} times)
5846
7326
  Error Log can be found in ${path15.join(LOGS_DIR, "agent", "error.log")}`);
5847
7327
  }
5848
7328
  }
@@ -6092,15 +7572,28 @@ var init_MemoryModal = __esm({
6092
7572
  // src/components/UpdateProcessor.jsx
6093
7573
  import React11, { useState as useState8, useEffect as useEffect6 } from "react";
6094
7574
  import { Box as Box11, Text as Text11 } from "ink";
6095
- import Spinner from "ink-spinner";
6096
- import { exec as exec2 } from "child_process";
6097
- var UpdateProcessor, UpdateProcessor_default;
7575
+ import { spawn as spawn2 } from "child_process";
7576
+ var pty2, SPINNER_FRAMES, UpdateProcessor, UpdateProcessor_default;
6098
7577
  var init_UpdateProcessor = __esm({
6099
- "src/components/UpdateProcessor.jsx"() {
7578
+ async "src/components/UpdateProcessor.jsx"() {
7579
+ pty2 = null;
7580
+ try {
7581
+ const ptyModule = await Promise.resolve().then(() => __toESM(require_lib(), 1));
7582
+ pty2 = ptyModule.default || ptyModule;
7583
+ } catch (err) {
7584
+ }
7585
+ SPINNER_FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
6100
7586
  UpdateProcessor = ({ latest, current, settings, onClose, onUpdateSettings, onSuccess }) => {
6101
7587
  const [status, setStatus] = useState8("initializing");
6102
7588
  const [log, setLog] = useState8("");
6103
7589
  const [error, setError] = useState8(null);
7590
+ const [tick, setTick] = useState8(0);
7591
+ useEffect6(() => {
7592
+ const interval = setInterval(() => {
7593
+ setTick((t) => (t + 1) % 1e3);
7594
+ }, 33);
7595
+ return () => clearInterval(interval);
7596
+ }, []);
6104
7597
  useEffect6(() => {
6105
7598
  let child;
6106
7599
  const runUpdate = async () => {
@@ -6117,31 +7610,101 @@ var init_UpdateProcessor = __esm({
6117
7610
  else command = `npm install -g fluxflow-cli@${latest}`;
6118
7611
  setStatus("downloading");
6119
7612
  setLog(`Running: ${command}...`);
6120
- child = exec2(command, (err, stdout, stderr) => {
6121
- if (err) {
6122
- setError(stderr || err.message);
6123
- setStatus("error");
6124
- return;
7613
+ const isWin = process.platform === "win32";
7614
+ const executeCommand = (usePowerShell) => {
7615
+ return new Promise((resolve) => {
7616
+ const shell = isWin ? usePowerShell ? "powershell.exe" : "cmd.exe" : process.env.SHELL || "bash";
7617
+ const shellArgs = isWin ? usePowerShell ? ["-NoProfile", "-Command", command] : ["/c", command] : ["-c", command];
7618
+ const handleOutput = (data) => {
7619
+ const str = data.toString();
7620
+ const cleanStr = str.replace(/\x1B\[[0-?]*[ -/]*[@-~]|\x1B\][^\x07\x1B]*[\x07\x1B]|\b|\x07/g, "").replace(/\r/g, "").trim();
7621
+ if (cleanStr) {
7622
+ setLog((prev) => (prev + "\n" + cleanStr).split("\n").slice(-5).join("\n"));
7623
+ }
7624
+ };
7625
+ if (pty2) {
7626
+ try {
7627
+ const ptyProcess = pty2.spawn(shell, shellArgs, {
7628
+ name: "xterm-256color",
7629
+ cols: 80,
7630
+ rows: 30,
7631
+ cwd: process.cwd(),
7632
+ env: process.env
7633
+ });
7634
+ child = ptyProcess;
7635
+ ptyProcess.onData(handleOutput);
7636
+ ptyProcess.onExit(({ exitCode }) => {
7637
+ child = null;
7638
+ if (exitCode !== 0) {
7639
+ resolve({ error: `Process exited with code ${exitCode}` });
7640
+ } else {
7641
+ resolve({ success: true });
7642
+ }
7643
+ });
7644
+ return;
7645
+ } catch (err) {
7646
+ if (isWin && usePowerShell && err.code === "ENOENT") {
7647
+ resolve({ retryCmd: true });
7648
+ return;
7649
+ }
7650
+ }
7651
+ }
7652
+ const cp = isWin ? spawn2(shell, shellArgs, { cwd: process.cwd(), env: process.env }) : spawn2(command, { shell: true, cwd: process.cwd(), env: process.env });
7653
+ child = cp;
7654
+ cp.stdout.on("data", handleOutput);
7655
+ cp.stderr.on("data", handleOutput);
7656
+ cp.on("close", (code) => {
7657
+ child = null;
7658
+ if (code !== 0) {
7659
+ resolve({ error: `Process exited with code ${code}` });
7660
+ } else {
7661
+ resolve({ success: true });
7662
+ }
7663
+ });
7664
+ cp.on("error", (err) => {
7665
+ if (isWin && usePowerShell && err.code === "ENOENT") {
7666
+ resolve({ retryCmd: true });
7667
+ } else {
7668
+ child = null;
7669
+ resolve({ error: err.message });
7670
+ }
7671
+ });
7672
+ });
7673
+ };
7674
+ let result = {};
7675
+ if (isWin) {
7676
+ result = await executeCommand(true);
7677
+ if (result.retryCmd) {
7678
+ result = await executeCommand(false);
6125
7679
  }
7680
+ } else {
7681
+ result = await executeCommand(false);
7682
+ }
7683
+ if (result.error) {
7684
+ setError(result.error);
7685
+ setStatus("error");
7686
+ } else if (result.success) {
6126
7687
  setStatus("success");
6127
7688
  if (onSuccess) onSuccess();
6128
- });
6129
- child.stdout.on("data", (data) => {
6130
- setLog((prev) => (prev + "\n" + data).split("\n").slice(-5).join("\n"));
6131
- });
7689
+ }
6132
7690
  };
6133
7691
  runUpdate();
6134
7692
  return () => {
6135
7693
  if (child) {
6136
7694
  try {
6137
- child.kill();
7695
+ if (typeof child.destroy === "function") {
7696
+ child.destroy();
7697
+ } else if (typeof child.kill === "function") {
7698
+ child.kill();
7699
+ }
6138
7700
  } catch (e) {
6139
7701
  }
6140
7702
  }
6141
7703
  };
6142
7704
  }, []);
6143
7705
  if (status === "initializing" || status === "downloading") {
6144
- return /* @__PURE__ */ React11.createElement(Box11, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 2, paddingY: 1 }, /* @__PURE__ */ React11.createElement(Box11, null, /* @__PURE__ */ React11.createElement(Text11, { color: "cyan" }, /* @__PURE__ */ React11.createElement(Spinner, { type: "dots" })), /* @__PURE__ */ React11.createElement(Text11, { marginLeft: 1, bold: true }, " Updating Flux Flow to v", latest, "...")), /* @__PURE__ */ React11.createElement(Box11, { marginTop: 1, paddingX: 1, borderStyle: "single", borderColor: "#333" }, /* @__PURE__ */ React11.createElement(Text11, { color: "gray", dimColor: true, italic: true }, log || "Preparing environment...")), /* @__PURE__ */ React11.createElement(Text11, { marginTop: 1, dimColor: true }, "(Please do not close the terminal)"));
7706
+ const frame = SPINNER_FRAMES[Math.floor(tick / 3) % SPINNER_FRAMES.length];
7707
+ return /* @__PURE__ */ React11.createElement(Box11, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 2, paddingY: 1 }, /* @__PURE__ */ React11.createElement(Box11, null, /* @__PURE__ */ React11.createElement(Text11, { color: "magenta" }, frame), /* @__PURE__ */ React11.createElement(Text11, { marginLeft: 1, bold: true }, " Updating Flux Flow to v", latest, "...")), /* @__PURE__ */ React11.createElement(Box11, { marginTop: 1, paddingX: 1, borderStyle: "single", borderColor: "#333" }, /* @__PURE__ */ React11.createElement(Text11, { color: "gray", dimColor: true, italic: true }, log || "Preparing environment...")), /* @__PURE__ */ React11.createElement(Text11, { marginTop: 1, dimColor: true }, "(Please do not close the terminal)"));
6145
7708
  }
6146
7709
  if (status === "success") {
6147
7710
  return /* @__PURE__ */ React11.createElement(Box11, { flexDirection: "column", borderStyle: "round", borderColor: "green", paddingX: 2, paddingY: 1 }, /* @__PURE__ */ React11.createElement(Text11, { color: "green", bold: true }, "\u2705 UPDATE SUCCESSFUL!"), /* @__PURE__ */ React11.createElement(Text11, { marginTop: 1 }, "Flux Flow has been updated to ", /* @__PURE__ */ React11.createElement(Text11, { color: "cyan" }, "v", latest), "."), /* @__PURE__ */ React11.createElement(Text11, { marginTop: 1, color: "yellow", bold: true }, "CRITICAL: Please restart your terminal session to apply changes."), /* @__PURE__ */ React11.createElement(Box11, { marginTop: 1 }, /* @__PURE__ */ React11.createElement(Text11, { dimColor: true }, "(Press ESC to return to chat)")));
@@ -6211,14 +7774,17 @@ function RevertModal({ prompts, onSelect, onClose }) {
6211
7774
  function formatPromptPreview(prompt) {
6212
7775
  if (!prompt) return "";
6213
7776
  const firstLine = prompt.split("\n")[0] || "";
6214
- const words = firstLine.split(/\s+/).filter(Boolean);
6215
- if (words.length > 15) {
6216
- return words.slice(0, 15).join(" ") + "...";
7777
+ const formatted = firstLine.replace(/@\[(.*?)\]/g, (match, p1) => {
7778
+ const parts = p1.replace(/\\/g, "/").split("/");
7779
+ return `[${parts[parts.length - 1]}]`;
7780
+ });
7781
+ if (formatted.length > 69) {
7782
+ return formatted.slice(0, 67) + "...";
6217
7783
  }
6218
7784
  if (prompt.includes("\n")) {
6219
- return firstLine + "...";
7785
+ return formatted + "...";
6220
7786
  }
6221
- return firstLine;
7787
+ return formatted;
6222
7788
  }
6223
7789
  function formatDate2(timestamp) {
6224
7790
  if (!timestamp) return "N/A";
@@ -6238,13 +7804,13 @@ var init_RevertModal = __esm({
6238
7804
 
6239
7805
  // src/utils/setup.js
6240
7806
  import puppeteer4 from "puppeteer";
6241
- import { exec as exec3 } from "child_process";
7807
+ import { exec as exec2 } from "child_process";
6242
7808
  import { promisify } from "util";
6243
7809
  import fs17 from "fs";
6244
7810
  var execAsync, checkPuppeteerReady, installPuppeteerBrowser;
6245
7811
  var init_setup = __esm({
6246
7812
  "src/utils/setup.js"() {
6247
- execAsync = promisify(exec3);
7813
+ execAsync = promisify(exec2);
6248
7814
  checkPuppeteerReady = () => {
6249
7815
  try {
6250
7816
  const exePath = puppeteer4.executablePath();
@@ -6281,10 +7847,9 @@ __export(app_exports, {
6281
7847
  import os4 from "os";
6282
7848
  import React13, { useState as useState10, useEffect as useEffect7, useRef as useRef3, useMemo as useMemo2 } from "react";
6283
7849
  import { Box as Box13, Text as Text13, useInput as useInput7, useStdout } from "ink";
6284
- import Spinner2 from "ink-spinner";
6285
7850
  import fs18 from "fs-extra";
6286
7851
  import path16 from "path";
6287
- import { exec as exec4 } from "child_process";
7852
+ import { exec as exec3 } from "child_process";
6288
7853
  import { fileURLToPath } from "url";
6289
7854
  import TextInput4 from "ink-text-input";
6290
7855
  import gradient from "gradient-string";
@@ -6436,6 +8001,7 @@ function App({ args = [] }) {
6436
8001
  const [activeCommand, setActiveCommand] = useState10(null);
6437
8002
  const [execOutput, setExecOutput] = useState10("");
6438
8003
  const [isTerminalFocused, setIsTerminalFocused] = useState10(false);
8004
+ const [tick, setTick] = useState10(0);
6439
8005
  useEffect7(() => {
6440
8006
  if (apiTier !== "Free" && activeModel === "gemma-4-31b-it") {
6441
8007
  setActiveModel("gemini-3-flash-preview");
@@ -6576,13 +8142,17 @@ function App({ args = [] }) {
6576
8142
  if (key.return) {
6577
8143
  const isWin = process.platform === "win32";
6578
8144
  writeToActiveCommand(isWin ? "\r\n" : "\n");
6579
- setExecOutput((prev) => prev + "\n");
8145
+ if (!isActiveCommandPty) setExecOutput((prev) => prev + "\n");
6580
8146
  } else if (key.backspace || key.delete) {
6581
- writeToActiveCommand("\b \b");
6582
- setExecOutput((prev) => prev.slice(0, -1));
8147
+ if (isActiveCommandPty) {
8148
+ writeToActiveCommand("\x7F");
8149
+ } else {
8150
+ writeToActiveCommand("\b \b");
8151
+ setExecOutput((prev) => prev.slice(0, -1));
8152
+ }
6583
8153
  } else if (inputText) {
6584
8154
  writeToActiveCommand(inputText);
6585
- setExecOutput((prev) => prev + inputText);
8155
+ if (!isActiveCommandPty) setExecOutput((prev) => prev + inputText);
6586
8156
  }
6587
8157
  return;
6588
8158
  }
@@ -6631,17 +8201,21 @@ function App({ args = [] }) {
6631
8201
  } else if (nextCount === 2) {
6632
8202
  if (escDoubleTimerRef.current) clearTimeout(escDoubleTimerRef.current);
6633
8203
  setEscPressCount(0);
6634
- RevertManager.getChatHistory(chatId).then((prompts) => {
6635
- if (prompts.length > 0) {
6636
- setRecentPrompts(prompts.reverse());
6637
- setActiveView("revert");
6638
- } else {
6639
- setMessages((prev2) => {
6640
- setCompletedIndex(prev2.length + 1);
6641
- return [...prev2, { id: "revert-empty-" + Date.now(), role: "system", text: "\u{1F6C8} No revert checkpoints found for this session.", isMeta: true }];
6642
- });
6643
- }
6644
- });
8204
+ if (input.length > 0) {
8205
+ setInput("");
8206
+ } else {
8207
+ RevertManager.getChatHistory(chatId).then((prompts) => {
8208
+ if (prompts.length > 0) {
8209
+ setRecentPrompts(prompts.reverse());
8210
+ setActiveView("revert");
8211
+ } else {
8212
+ setMessages((prev2) => {
8213
+ setCompletedIndex(prev2.length + 1);
8214
+ return [...prev2, { id: "revert-empty-" + Date.now(), role: "system", text: "\u{1F6C8} No revert checkpoints found for this session.", isMeta: true }];
8215
+ });
8216
+ }
8217
+ });
8218
+ }
6645
8219
  }
6646
8220
  return nextCount;
6647
8221
  });
@@ -6664,6 +8238,10 @@ function App({ args = [] }) {
6664
8238
  if (key.tab && activeView === "chat") {
6665
8239
  }
6666
8240
  if (key.ctrl && inputText === "c" && activeView !== "exit") {
8241
+ if (input.length > 0) {
8242
+ setInput("");
8243
+ return;
8244
+ }
6667
8245
  if (key.shift) {
6668
8246
  setActiveView("exit");
6669
8247
  setConfirmExit(false);
@@ -7097,7 +8675,7 @@ ${hintText}`, color: "magenta" }];
7097
8675
  isMeta: true
7098
8676
  }];
7099
8677
  });
7100
- exec4("start https://enter.pollinations.ai/#pollen");
8678
+ exec3("start https://enter.pollinations.ai/#pollen");
7101
8679
  } else {
7102
8680
  try {
7103
8681
  const stats = await getImageQuotaStats();
@@ -7423,7 +9001,7 @@ ${list || "No saved chats found."}`, isMeta: true }];
7423
9001
  case "/changelog": {
7424
9002
  const platform = process.platform;
7425
9003
  const command = platform === "win32" ? "start" : platform === "darwin" ? "open" : "xdg-open";
7426
- exec4(`${command} ${CHANGELOG_URL}`);
9004
+ exec3(`${command} ${CHANGELOG_URL}`);
7427
9005
  setMessages((prev) => {
7428
9006
  setCompletedIndex(prev.length + 1);
7429
9007
  return [...prev, { id: Date.now(), role: "system", text: `\u{1F310} [BROWSER] Opening changelog: ${CHANGELOG_URL}`, isMeta: true }];
@@ -7527,6 +9105,8 @@ ${timestamp}` };
7527
9105
  janitorModel,
7528
9106
  sessionStats,
7529
9107
  chatId,
9108
+ cols: terminalSize.columns - 6,
9109
+ rows: 30,
7530
9110
  onExecStart: (cmd) => {
7531
9111
  setActiveCommand(cmd);
7532
9112
  setExecOutput("");
@@ -7539,6 +9119,7 @@ ${timestamp}` };
7539
9119
  if (!activeCommandRef.current) return prev;
7540
9120
  const finalStatus = `[TERMINAL_RECORD]
7541
9121
  COMMAND: ${activeCommandRef.current}
9122
+ PTY: ${isActiveCommandPty}
7542
9123
  OUTPUT: ${execOutputRef.current}`;
7543
9124
  return [...prev, { id: "term-" + Date.now(), role: "system", text: finalStatus, isTerminalRecord: true }];
7544
9125
  });
@@ -8428,7 +10009,7 @@ Selection: ${val}`,
8428
10009
  }
8429
10010
  )));
8430
10011
  default:
8431
- return /* @__PURE__ */ React13.createElement(Box13, { flexDirection: "column", marginTop: 1, flexShrink: 0, width: "100%" }, /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, marginBottom: 0, justifyContent: "space-between", width: "100%" }, /* @__PURE__ */ React13.createElement(Box13, null, statusText ? /* @__PURE__ */ React13.createElement(Box13, null, isSpinnerActive && /* @__PURE__ */ React13.createElement(Text13, { color: "magenta" }, /* @__PURE__ */ React13.createElement(Spinner2, { type: "dots" })), /* @__PURE__ */ React13.createElement(Text13, { color: "magenta", bold: true, italic: true }, isSpinnerActive ? " " : "", statusText.toUpperCase())) : /* @__PURE__ */ React13.createElement(Text13, { color: "cyan", dimColor: true, italic: true }, "READY FOR COMMAND...")), /* @__PURE__ */ React13.createElement(Box13, null, /* @__PURE__ */ React13.createElement(Text13, { color: "gray", bold: true }, "[ "), /* @__PURE__ */ React13.createElement(Text13, { color: "white" }, tempModelOverride || activeModel), /* @__PURE__ */ React13.createElement(Text13, { color: "gray", bold: true }, " ]"))), /* @__PURE__ */ React13.createElement(
10012
+ return /* @__PURE__ */ React13.createElement(Box13, { flexDirection: "column", marginTop: 1, flexShrink: 0, width: "100%" }, /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, marginBottom: 0, justifyContent: "space-between", width: "100%" }, /* @__PURE__ */ React13.createElement(Box13, null, statusText ? /* @__PURE__ */ React13.createElement(Box13, null, isSpinnerActive && /* @__PURE__ */ React13.createElement(StatusSpinner, null), /* @__PURE__ */ React13.createElement(Text13, { color: "magenta", bold: true, italic: true }, isSpinnerActive ? " " : "", statusText.toUpperCase())) : /* @__PURE__ */ React13.createElement(Text13, { color: "cyan", dimColor: true, italic: true }, "READY FOR COMMAND...")), /* @__PURE__ */ React13.createElement(Box13, null, /* @__PURE__ */ React13.createElement(Text13, { color: "gray", bold: true }, "[ "), /* @__PURE__ */ React13.createElement(Text13, { color: "white" }, tempModelOverride || activeModel), /* @__PURE__ */ React13.createElement(Text13, { color: "gray", bold: true }, " ]"))), /* @__PURE__ */ React13.createElement(
8432
10013
  Box13,
8433
10014
  {
8434
10015
  borderStyle: "round",
@@ -8454,12 +10035,13 @@ Selection: ${val}`,
8454
10035
  newline: (key) => key.return && key.shift || key.return && key.ctrl || key.return && key.leftAlt || key.return && key.rightAlt
8455
10036
  }
8456
10037
  }
8457
- )))) : /* @__PURE__ */ React13.createElement(Box13, { flexDirection: "row", width: "100%", paddingY: 0 }, /* @__PURE__ */ React13.createElement(Box13, { flexShrink: 0, width: 4 }, /* @__PURE__ */ React13.createElement(Text13, { color: isProcessing ? "magenta" : "cyan", bold: true }, isProcessing ? "\u2726 " : "\u{1F4A0} ")), /* @__PURE__ */ React13.createElement(Box13, { flexGrow: 1 }, /* @__PURE__ */ React13.createElement(Box13, { flexGrow: 1, position: "relative" }, input === "" && /* @__PURE__ */ React13.createElement(Box13, { position: "absolute", paddingLeft: 0 }, activeCommand && !isTerminalFocused ? /* @__PURE__ */ React13.createElement(Text13, { color: "yellow" }, " Press TAB to interact with terminal...") : activeCommand && isTerminalFocused ? /* @__PURE__ */ React13.createElement(Text13, { color: "yellow", bold: true }, " [ TERMINAL FOCUSED ] Type to interact, press TAB to exit...") : escPressCount === 1 ? /* @__PURE__ */ React13.createElement(Text13, { color: "cyan", bold: true }, " Press ESC again to revert codebase to checkpoint...") : /* @__PURE__ */ React13.createElement(Text13, { color: "gray" }, escPressed ? " Press ESC again to cancel the request." : !isProcessing ? ` Send message or /cmd... (${terminalEnv.shortcut} for newline)` : " Enter a prompt to steer the agent.")), /* @__PURE__ */ React13.createElement(
10038
+ )))) : /* @__PURE__ */ React13.createElement(Box13, { flexDirection: "row", width: "100%", paddingY: 0 }, /* @__PURE__ */ React13.createElement(Box13, { flexShrink: 0, width: 4 }, /* @__PURE__ */ React13.createElement(Text13, { color: isProcessing ? "magenta" : "cyan", bold: true }, isProcessing ? "\u2726 " : "\u{1F4A0} ")), /* @__PURE__ */ React13.createElement(Box13, { flexGrow: 1 }, /* @__PURE__ */ React13.createElement(Box13, { flexGrow: 1, position: "relative" }, input === "" && /* @__PURE__ */ React13.createElement(Box13, { position: "absolute", paddingLeft: 0 }, activeCommand && !isTerminalFocused ? /* @__PURE__ */ React13.createElement(Text13, { color: "yellow" }, " Press TAB to interact with terminal...") : activeCommand && isTerminalFocused ? /* @__PURE__ */ React13.createElement(Text13, { color: "yellow", bold: true }, " [ TERMINAL FOCUSED ] Type to interact, press TAB to exit...") : escPressCount === 1 ? /* @__PURE__ */ React13.createElement(Text13, { color: "cyan", bold: true }, " Press ESC again to ", input.length > 0 ? "clear input" : "revert codebase to checkpoint", "...") : /* @__PURE__ */ React13.createElement(Text13, { color: "gray" }, escPressed ? " Press ESC again to cancel the request." : !isProcessing ? ` Send message or /cmd... (${terminalEnv.shortcut} for newline)` : " Enter a prompt to steer the agent.")), /* @__PURE__ */ React13.createElement(
8458
10039
  MultilineInput,
8459
10040
  {
8460
10041
  key: `input-${inputKey}`,
8461
10042
  focus: !isTerminalFocused,
8462
10043
  value: input,
10044
+ columns: terminalSize.columns,
8463
10045
  onChange: (val) => {
8464
10046
  const cleanVal = val.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\\\s*\n/g, "\n");
8465
10047
  setInput(cleanVal);
@@ -8483,7 +10065,7 @@ Selection: ${val}`,
8483
10065
  showFullThinking,
8484
10066
  columns: Math.max(20, (stdout?.columns || 80) - 1)
8485
10067
  }
8486
- ), activeCommand && /* @__PURE__ */ React13.createElement(Box13, { marginTop: 1 }, /* @__PURE__ */ React13.createElement(TerminalBox, { command: activeCommand, output: execOutput, isFocused: isTerminalFocused }))), isInitializing ? /* @__PURE__ */ React13.createElement(Box13, { borderStyle: "double", borderColor: "magenta", padding: 1, flexShrink: 0 }, /* @__PURE__ */ React13.createElement(Text13, { color: "magenta" }, "\u{1F30A} Starting Flux Flow...")) : !apiKey ? /* @__PURE__ */ React13.createElement(Box13, { borderStyle: "round", borderColor: "gray", padding: 0, flexDirection: "column", flexShrink: 0, width: "100%" }, /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, marginBottom: 1 }, /* @__PURE__ */ React13.createElement(Text13, { color: "yellow", bold: true }, "\u{1F511}", emojiSpace(2), "API KEY REQUIRED")), /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, flexDirection: "column" }, /* @__PURE__ */ React13.createElement(Text13, null, "Please enter your Gemini API Key to initialize the agent."), /* @__PURE__ */ React13.createElement(Box13, { marginTop: 1 }, /* @__PURE__ */ React13.createElement(Text13, { color: "cyan", bold: true }, "\u{1F4A0} "), /* @__PURE__ */ React13.createElement(
10068
+ ), activeCommand && /* @__PURE__ */ React13.createElement(Box13, { marginTop: 1 }, /* @__PURE__ */ React13.createElement(TerminalBox, { command: activeCommand, output: execOutput, isFocused: isTerminalFocused, isPty: isActiveCommandPty }))), isInitializing ? /* @__PURE__ */ React13.createElement(Box13, { borderStyle: "double", borderColor: "magenta", padding: 1, flexShrink: 0 }, /* @__PURE__ */ React13.createElement(Text13, { color: "magenta" }, "\u{1F30A} Starting Flux Flow...")) : !apiKey ? /* @__PURE__ */ React13.createElement(Box13, { borderStyle: "round", borderColor: "gray", padding: 0, flexDirection: "column", flexShrink: 0, width: "100%" }, /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, marginBottom: 1 }, /* @__PURE__ */ React13.createElement(Text13, { color: "yellow", bold: true }, "\u{1F511}", emojiSpace(2), "API KEY REQUIRED")), /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, flexDirection: "column" }, /* @__PURE__ */ React13.createElement(Text13, null, "Please enter your Gemini API Key to initialize the agent."), /* @__PURE__ */ React13.createElement(Box13, { marginTop: 1 }, /* @__PURE__ */ React13.createElement(Text13, { color: "cyan", bold: true }, "\u{1F4A0} "), /* @__PURE__ */ React13.createElement(
8487
10069
  TextInput4,
8488
10070
  {
8489
10071
  value: tempKey,
@@ -8558,9 +10140,9 @@ Selection: ${val}`,
8558
10140
  );
8559
10141
  })()));
8560
10142
  }
8561
- var SESSION_START_TIME, CHANGELOG_URL, linesAdded, linesRemoved, packageJsonPath, packageJson, versionFluxflow, updatedOn, ResolutionModal, FLUX_LOGO, parseAgentText, getProjectFiles;
10143
+ var SESSION_START_TIME, CHANGELOG_URL, linesAdded, linesRemoved, packageJsonPath, packageJson, versionFluxflow, updatedOn, SPINNER_FRAMES2, StatusSpinner, ResolutionModal, FLUX_LOGO, parseAgentText, getProjectFiles;
8562
10144
  var init_app = __esm({
8563
- "src/app.jsx"() {
10145
+ async "src/app.jsx"() {
8564
10146
  init_MultilineInput();
8565
10147
  init_ChatLayout();
8566
10148
  init_StatusBar();
@@ -8569,12 +10151,12 @@ var init_app = __esm({
8569
10151
  init_ProfileForm();
8570
10152
  init_AskUserModal();
8571
10153
  init_secrets();
8572
- init_ai();
10154
+ await init_ai();
8573
10155
  init_settings();
8574
10156
  init_history();
8575
10157
  init_ResumeModal();
8576
10158
  init_MemoryModal();
8577
- init_UpdateProcessor();
10159
+ await init_UpdateProcessor();
8578
10160
  init_revert();
8579
10161
  init_RevertModal();
8580
10162
  init_usage();
@@ -8582,7 +10164,7 @@ var init_app = __esm({
8582
10164
  init_arg_parser();
8583
10165
  init_paths();
8584
10166
  init_terminal();
8585
- init_exec_command();
10167
+ await init_exec_command();
8586
10168
  init_setup();
8587
10169
  init_text();
8588
10170
  SESSION_START_TIME = Date.now();
@@ -8593,6 +10175,17 @@ var init_app = __esm({
8593
10175
  packageJson = JSON.parse(fs18.readFileSync(packageJsonPath, "utf8"));
8594
10176
  versionFluxflow = packageJson.version;
8595
10177
  updatedOn = packageJson.date || "2026-05-20";
10178
+ SPINNER_FRAMES2 = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
10179
+ StatusSpinner = () => {
10180
+ const [tick, setTick] = useState10(0);
10181
+ useEffect7(() => {
10182
+ const interval = setInterval(() => {
10183
+ setTick((t) => (t + 1) % 1e3);
10184
+ }, 33);
10185
+ return () => clearInterval(interval);
10186
+ }, []);
10187
+ return /* @__PURE__ */ React13.createElement(Text13, { color: "magenta" }, SPINNER_FRAMES2[Math.floor(tick / 3) % SPINNER_FRAMES2.length]);
10188
+ };
8596
10189
  ResolutionModal = ({ data, onResolve, onEdit }) => /* @__PURE__ */ React13.createElement(Box13, { flexDirection: "column", borderStyle: "round", borderColor: "gray", padding: 0, width: "100%" }, /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1 }, /* @__PURE__ */ React13.createElement(Text13, { color: "magenta", bold: true, underline: true }, "\u{1F7E3} STEERING HINT RESOLUTION")), /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, marginTop: 1 }, /* @__PURE__ */ React13.createElement(Text13, null, "The agent already finished the task before your hint was consumed.")), /* @__PURE__ */ React13.createElement(Box13, { marginTop: 1, backgroundColor: "#222", paddingX: 2, width: "100%" }, /* @__PURE__ */ React13.createElement(Text13, { italic: true, color: "gray" }, '"', data, '"')), /* @__PURE__ */ React13.createElement(Box13, { paddingX: 1, marginTop: 1 }, /* @__PURE__ */ React13.createElement(Text13, { color: "cyan" }, "How would you like to proceed?")), /* @__PURE__ */ React13.createElement(Box13, { marginTop: 0 }, /* @__PURE__ */ React13.createElement(
8597
10190
  CommandMenu,
8598
10191
  {
@@ -8720,12 +10313,12 @@ var init_app = __esm({
8720
10313
  });
8721
10314
 
8722
10315
  // src/cli.jsx
8723
- import { spawn as spawn2 } from "child_process";
10316
+ import { spawn as spawn3 } from "child_process";
8724
10317
  import { fileURLToPath as fileURLToPath2 } from "url";
8725
10318
  var HEAP_LIMIT = 4096;
8726
10319
  var isBundled = fileURLToPath2(import.meta.url).endsWith(".js");
8727
10320
  if (isBundled && !process.execArgv.some((arg) => arg.includes("max-old-space-size"))) {
8728
- const cp = spawn2(process.execPath, [
10321
+ const cp = spawn3(process.execPath, [
8729
10322
  `--max-old-space-size=${HEAP_LIMIT}`,
8730
10323
  fileURLToPath2(import.meta.url),
8731
10324
  ...process.argv.slice(2)
@@ -8734,7 +10327,7 @@ if (isBundled && !process.execArgv.some((arg) => arg.includes("max-old-space-siz
8734
10327
  } else {
8735
10328
  const { default: React14 } = await import("react");
8736
10329
  const { render } = await import("ink");
8737
- const { default: App2 } = await Promise.resolve().then(() => (init_app(), app_exports));
10330
+ const { default: App2 } = await init_app().then(() => app_exports);
8738
10331
  process.env.NODE_NO_WARNINGS = "1";
8739
10332
  const silentPatterns = [
8740
10333
  "cuimp",