@hncode/hncode 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,104 +1,143 @@
1
- // Shared helpers for the hncode toolbelt.
2
-
3
- import path from 'node:path';
4
- import os from 'node:os';
5
- import fs from 'node:fs';
6
- import { recordBeforeWrite } from '../file-history.js';
7
-
8
- export const MAX_OUTPUT_BYTES = 128 * 1024; // cap tool results to avoid token blowup
9
-
10
- export function truncateBuf(buf) {
11
- if (Buffer.isBuffer(buf)) {
12
- if (buf.length <= MAX_OUTPUT_BYTES) return buf.toString('utf8');
13
- return buf.subarray(0, MAX_OUTPUT_BYTES).toString('utf8') + `\n...[truncated ${buf.length - MAX_OUTPUT_BYTES} bytes]`;
14
- }
15
- const s = String(buf);
16
- if (s.length <= MAX_OUTPUT_BYTES) return s;
17
- // The cap is a BYTE budget, but `s.length` is UTF-16 code units. Slicing by
18
- // code units both under-counts non-ASCII (a 3-byte CJK char costs 1 unit)
19
- // and can split a surrogate pair, emitting a lone half. Truncate by BYTES
20
- // and back off to the nearest code-point boundary.
21
- const bytes = Buffer.byteLength(s, 'utf8');
22
- if (bytes <= MAX_OUTPUT_BYTES) return s;
23
- const cut = Buffer.from(s, 'utf8').subarray(0, MAX_OUTPUT_BYTES).toString('utf8');
24
- // A trailing lone surrogate (from a split pair) is dropped by decoding; the
25
- // replacement char U+FFFD at the tail is also stripped so the marker is clean.
26
- const safe = cut.endsWith('\uFFFD') ? cut.slice(0, -1) : cut;
27
- return safe + `\n...[truncated ${bytes - MAX_OUTPUT_BYTES} bytes]`;
28
- }
29
-
30
- // Expand ~ and map Git-Bash /c/x -> C:\x style paths, then resolve against cwd.
31
- export function normalizeInput(p) {
32
- let s = String(p);
33
- if (s.startsWith('~')) s = path.join(os.homedir(), s.slice(1));
34
- // Windows only: under Git Bash an agent writes `/d/hncode/src` for `D:\hncode\src`.
35
- // Gated on the platform because on Linux `/c/x` is a perfectly ordinary absolute
36
- // path, and rewriting it to `C:\x` turned it into a relative garbage filename.
37
- if (process.platform === 'win32') {
38
- const m = s.match(/^\/([a-zA-Z])\/(.*)$/);
39
- if (m) return path.join(`${m[1].toUpperCase()}:\\`, ...m[2].split('/'));
40
- }
41
- return s;
42
- }
43
-
44
- export function resolvePath(input, ctx) {
45
- const raw = normalizeInput(input);
46
- let p = path.resolve(ctx.cwd || ctx.workspace, raw);
47
- try { p = fs.realpathSync(p); } catch {} // resolve symlinks if present
48
- const ws = path.resolve(ctx.cwd || ctx.workspace);
49
- if (!ctx.allowExternal) {
50
- let rel = path.relative(ws, p);
51
- if (rel === '') return p;
52
- // ESCAPE check, not a prefix check: the first path segment must not be `..`.
53
- // A plain startsWith('..') also rejected files INSIDE the workspace whose
54
- // names merely begin with dots — `..notes.md` — while `...` / `..a` are
55
- // legitimate relative names that stay below the root.
56
- if (rel.split(path.sep)[0] === '..' || path.isAbsolute(rel)) {
57
- throw new Error(`Path outside workspace: ${input}. Run hncode from that directory or set HNCODE_ALLOW_EXTERNAL=1.`);
58
- }
59
- }
60
- return p;
61
- }
62
-
63
- export function ensureDir(p) {
64
- fs.mkdirSync(path.dirname(p), { recursive: true });
65
- }
66
-
67
- // Checkpoint `p` before a write tool modifies it, so /undo can put it back (see
68
- // file-history.js). The record is taken ONCE per turn, so what is captured is the
69
- // file as it stood before ANY of this turn's changes — the state the user would
70
- // expect "Undid 1 prompt" to restore.
71
- //
72
- // ctx.sessionId identifies the checkpoint store. A caller without one (a
73
- // subagent's own context, a test) simply gets no checkpoint rather than an error:
74
- // losing the safety net must never fail the actual write.
75
- export function checkpointBeforeWrite(p, ctx) {
76
- if (!ctx || !ctx.sessionId) return false;
77
- try { return recordBeforeWrite(ctx.sessionId, p); } catch { return false; }
78
- }
79
-
80
- // Read a file fully, returning its string. Throws if not a file.
81
- export function readFileBytes(p) {
82
- const st = fs.statSync(p);
83
- if (!st.isFile() && !st.isFIFO()) throw new Error(`Not a file: ${p}`);
84
- return fs.readFileSync(p);
85
- }
86
-
87
- // Visible width ignoring ANSI escapes (approx).
88
- export function visibleWidth(s) {
89
- return (s || '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').length;
90
- }
91
-
92
- export function isProbablyTextFile(buf) {
93
- // Treat as text if mostly printable ASCII/UTF-8 and few NULs.
94
- if (buf.length === 0) return true;
95
- let nulls = 0;
96
- for (let i = 0; i < Math.min(buf.length, 8192); i++) if (buf[i] === 0) nulls++;
97
- if (nulls > 0) return false;
98
- let bad = 0;
99
- for (let i = 0; i < Math.min(buf.length, 8192); i++) {
100
- const b = buf[i];
101
- if (b < 9 || (b > 13 && b < 32) || b > 254) bad++;
102
- }
103
- return bad / Math.min(buf.length, 8192) < 0.10;
104
- }
1
+ // Shared helpers for the hncode toolbelt.
2
+
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import fs from 'node:fs';
6
+ import { recordBeforeWrite } from '../file-history.js';
7
+
8
+ export const MAX_OUTPUT_BYTES = 128 * 1024; // cap tool results to avoid token blowup
9
+
10
+ export function truncateBuf(buf) {
11
+ if (Buffer.isBuffer(buf)) {
12
+ if (buf.length <= MAX_OUTPUT_BYTES) return buf.toString('utf8');
13
+ return buf.subarray(0, MAX_OUTPUT_BYTES).toString('utf8') + `\n...[truncated ${buf.length - MAX_OUTPUT_BYTES} bytes]`;
14
+ }
15
+ const s = String(buf);
16
+ if (s.length <= MAX_OUTPUT_BYTES) return s;
17
+ // The cap is a BYTE budget, but `s.length` is UTF-16 code units. Slicing by
18
+ // code units both under-counts non-ASCII (a 3-byte CJK char costs 1 unit)
19
+ // and can split a surrogate pair, emitting a lone half. Truncate by BYTES
20
+ // and back off to the nearest code-point boundary.
21
+ const bytes = Buffer.byteLength(s, 'utf8');
22
+ if (bytes <= MAX_OUTPUT_BYTES) return s;
23
+ const cut = Buffer.from(s, 'utf8').subarray(0, MAX_OUTPUT_BYTES).toString('utf8');
24
+ // A trailing lone surrogate (from a split pair) is dropped by decoding; the
25
+ // replacement char U+FFFD at the tail is also stripped so the marker is clean.
26
+ const safe = cut.endsWith('\uFFFD') ? cut.slice(0, -1) : cut;
27
+ return safe + `\n...[truncated ${bytes - MAX_OUTPUT_BYTES} bytes]`;
28
+ }
29
+
30
+ // Expand ~ and map Git-Bash /c/x -> C:\x style paths, then resolve against cwd.
31
+ export function normalizeInput(p) {
32
+ let s = String(p);
33
+ if (s.startsWith('~')) s = path.join(os.homedir(), s.slice(1));
34
+ // Windows only: under Git Bash an agent writes `/d/hncode/src` for `D:\hncode\src`.
35
+ // Gated on the platform because on Linux `/c/x` is a perfectly ordinary absolute
36
+ // path, and rewriting it to `C:\x` turned it into a relative garbage filename.
37
+ if (process.platform === 'win32') {
38
+ const m = s.match(/^\/([a-zA-Z])\/(.*)$/);
39
+ if (m) return path.join(`${m[1].toUpperCase()}:\\`, ...m[2].split('/'));
40
+ }
41
+ return s;
42
+ }
43
+
44
+ export function resolvePath(input, ctx) {
45
+ const raw = normalizeInput(input);
46
+ let p = path.resolve(ctx.cwd || ctx.workspace, raw);
47
+ try { p = fs.realpathSync(p); } catch {} // resolve symlinks if present
48
+ const ws = path.resolve(ctx.cwd || ctx.workspace);
49
+ if (!ctx.allowExternal) {
50
+ let rel = path.relative(ws, p);
51
+ if (rel === '') return p;
52
+ // ESCAPE check, not a prefix check: the first path segment must not be `..`.
53
+ // A plain startsWith('..') also rejected files INSIDE the workspace whose
54
+ // names merely begin with dots — `..notes.md` — while `...` / `..a` are
55
+ // legitimate relative names that stay below the root.
56
+ if (rel.split(path.sep)[0] === '..' || path.isAbsolute(rel)) {
57
+ throw new Error(`Path outside workspace: ${input}. Run hncode from that directory or set HNCODE_ALLOW_EXTERNAL=1.`);
58
+ }
59
+ }
60
+ return p;
61
+ }
62
+
63
+ export function ensureDir(p) {
64
+ fs.mkdirSync(path.dirname(p), { recursive: true });
65
+ }
66
+
67
+ // Checkpoint `p` before a write tool modifies it, so /undo can put it back (see
68
+ // file-history.js). The record is taken ONCE per turn, so what is captured is the
69
+ // file as it stood before ANY of this turn's changes — the state the user would
70
+ // expect "Undid 1 prompt" to restore.
71
+ //
72
+ // ctx.sessionId identifies the checkpoint store. A caller without one (a
73
+ // subagent's own context, a test) simply gets no checkpoint rather than an error:
74
+ // losing the safety net must never fail the actual write.
75
+ export function checkpointBeforeWrite(p, ctx) {
76
+ if (!ctx || !ctx.sessionId) return false;
77
+ try { return recordBeforeWrite(ctx.sessionId, p); } catch { return false; }
78
+ }
79
+
80
+ // Read a file fully, returning its string. Throws if not a file.
81
+ export function readFileBytes(p) {
82
+ const st = fs.statSync(p);
83
+ if (!st.isFile() && !st.isFIFO()) throw new Error(`Not a file: ${p}`);
84
+ return fs.readFileSync(p);
85
+ }
86
+
87
+ // Visible width ignoring ANSI escapes (approx).
88
+ export function visibleWidth(s) {
89
+ return (s || '').replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').length;
90
+ }
91
+
92
+ export function isProbablyTextFile(buf) {
93
+ // Treat as text if mostly printable ASCII/UTF-8 and few NULs.
94
+ if (buf.length === 0) return true;
95
+ let nulls = 0;
96
+ for (let i = 0; i < Math.min(buf.length, 8192); i++) if (buf[i] === 0) nulls++;
97
+ if (nulls > 0) return false;
98
+ let bad = 0;
99
+ for (let i = 0; i < Math.min(buf.length, 8192); i++) {
100
+ const b = buf[i];
101
+ if (b < 9 || (b > 13 && b < 32) || b > 254) bad++;
102
+ }
103
+ return bad / Math.min(buf.length, 8192) < 0.10;
104
+ }
105
+
106
+
107
+
108
+
109
+ export function similarFileHint(missingPath) {
110
+ const dir = path.dirname(missingPath);
111
+ const base = path.basename(missingPath);
112
+ const stem = base.replace(/\.[^.]*$/, '').toLowerCase();
113
+ let entries;
114
+ try { entries = fs.readdirSync(dir); } catch { return ''; }
115
+ const lower = base.toLowerCase();
116
+ // Levenshtein distance, capped — enough to catch a typo (confg -> config).
117
+ const lev = (a, b) => {
118
+ const m = a.length, n = b.length;
119
+ if (Math.abs(m - n) > 2) return 3;
120
+ let prev = Array.from({ length: n + 1 }, (_, j) => j);
121
+ for (let i = 1; i <= m; i++) {
122
+ const cur = [i];
123
+ for (let j = 1; j <= n; j++) {
124
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
125
+ }
126
+ prev = cur;
127
+ }
128
+ return prev[n];
129
+ };
130
+ let cand = entries.find((e) => e.toLowerCase() === lower);
131
+ if (!cand) {
132
+ let best = null, bestD = 3;
133
+ for (const e of entries) {
134
+ const d = lev(stem, e.replace(/\.[^.]*$/, '').toLowerCase());
135
+ if (d < bestD) { bestD = d; best = e; }
136
+ }
137
+ cand = best;
138
+ }
139
+ if (cand && cand !== base) return ` Did you mean "${path.join(dir, cand)}"?`;
140
+ return '';
141
+ }
142
+
143
+