@yasaswy.nagavolu/agents 0.8.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.
- package/README.md +349 -0
- package/bin/cli.js +721 -0
- package/lib/agentsEnv.js +82 -0
- package/lib/components.js +256 -0
- package/lib/diff.js +157 -0
- package/lib/fsutil.js +99 -0
- package/lib/install.js +188 -0
- package/lib/ledger.js +116 -0
- package/lib/manifest.js +100 -0
- package/lib/mcpWiring.js +328 -0
- package/lib/menu.js +138 -0
- package/lib/secretsPrompt.js +319 -0
- package/lib/secretsStore.js +115 -0
- package/lib/selfProfile.js +173 -0
- package/lib/semver.js +11 -0
- package/lib/tty-menu.js +132 -0
- package/lib/uninstall.js +94 -0
- package/lib/update.js +363 -0
- package/lib/wiring.js +379 -0
- package/package.json +39 -0
- package/templates/litellm-config.yaml +95 -0
- package/templates/start-litellm.ps1 +47 -0
- package/templates/start-litellm.sh +51 -0
package/lib/agentsEnv.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const os = require('node:os');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Shared secrets-resolution contract. Also implemented, verbatim-identical
|
|
9
|
+
* contract, in proxy/agents_env.py (Python, stdlib-only) for hooks — keep
|
|
10
|
+
* the two in sync on any change here.
|
|
11
|
+
*
|
|
12
|
+
* Resolution order:
|
|
13
|
+
* 1. A real environment variable of this name.
|
|
14
|
+
* 2. <base>/agents.env, where base = AGENTS_ENV_DIR env override, else
|
|
15
|
+
* ~/.claude.
|
|
16
|
+
*
|
|
17
|
+
* Secret values are never logged.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const ENV_FILE_NAME = 'agents.env';
|
|
21
|
+
|
|
22
|
+
function resolveEnvBase() {
|
|
23
|
+
return process.env.AGENTS_ENV_DIR || path.join(os.homedir(), '.claude');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function envFilePath(base) {
|
|
27
|
+
return path.join(base || resolveEnvBase(), ENV_FILE_NAME);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Parse `KEY=value` lines. Blank lines and `#`-prefixed comment lines are
|
|
32
|
+
* ignored. A value wrapped in a single matching layer of quotes (' or ")
|
|
33
|
+
* has the quotes stripped, matching common .env tooling conventions.
|
|
34
|
+
*/
|
|
35
|
+
function parseEnvFile(contents) {
|
|
36
|
+
const values = {};
|
|
37
|
+
for (const rawLine of contents.split(/\r?\n/)) {
|
|
38
|
+
const line = rawLine.trim();
|
|
39
|
+
if (!line || line.startsWith('#')) continue;
|
|
40
|
+
const eq = line.indexOf('=');
|
|
41
|
+
if (eq === -1) continue;
|
|
42
|
+
const key = line.slice(0, eq).trim();
|
|
43
|
+
let value = line.slice(eq + 1).trim();
|
|
44
|
+
if (value.length >= 2 && (
|
|
45
|
+
(value.startsWith('"') && value.endsWith('"')) ||
|
|
46
|
+
(value.startsWith("'") && value.endsWith("'"))
|
|
47
|
+
)) {
|
|
48
|
+
value = value.slice(1, -1);
|
|
49
|
+
}
|
|
50
|
+
if (key) values[key] = value;
|
|
51
|
+
}
|
|
52
|
+
return values;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readEnvFile(base) {
|
|
56
|
+
const file = envFilePath(base);
|
|
57
|
+
if (!fs.existsSync(file)) {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
return parseEnvFile(fs.readFileSync(file, 'utf8'));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Resolve one secret by name using the contract's resolution order.
|
|
65
|
+
* Returns `defaultValue` (undefined unless given) if neither a real env var
|
|
66
|
+
* nor agents.env has a non-empty value for `name`.
|
|
67
|
+
*/
|
|
68
|
+
function getSecret(name, defaultValue, { base } = {}) {
|
|
69
|
+
const envValue = process.env[name];
|
|
70
|
+
if (envValue) return envValue;
|
|
71
|
+
const fileValue = readEnvFile(base)[name];
|
|
72
|
+
return fileValue ? fileValue : defaultValue;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = {
|
|
76
|
+
ENV_FILE_NAME,
|
|
77
|
+
resolveEnvBase,
|
|
78
|
+
envFilePath,
|
|
79
|
+
parseEnvFile,
|
|
80
|
+
readEnvFile,
|
|
81
|
+
getSecret,
|
|
82
|
+
};
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const { spawnSync } = require('node:child_process');
|
|
6
|
+
const { sha256File, copyFileEnsuringDir, removeEmptyParents } = require('./fsutil');
|
|
7
|
+
const { COMPONENT_ENTRY_PREFIX, bundleKeysInLedger } = require('./ledger');
|
|
8
|
+
const { findBundle } = require('./manifest');
|
|
9
|
+
|
|
10
|
+
class ComponentError extends Error {}
|
|
11
|
+
|
|
12
|
+
/** The ledger.entries[].bundle tag used for one component's shipped files. */
|
|
13
|
+
function componentEntryTag(componentKey) {
|
|
14
|
+
return `${COMPONENT_ENTRY_PREFIX}${componentKey}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Real process-spawning runner used outside of tests. `--version` probes are
|
|
19
|
+
* read-only and always run for real. The two *mutating* installer
|
|
20
|
+
* invocations (`<tool> tool install <package>` / `<fallback> install
|
|
21
|
+
* <package>`) are refused when NODE_ENV === "test" — test/index.js sets that
|
|
22
|
+
* before requiring any *.test.js file, which also covers the
|
|
23
|
+
* execFileSync-spawned `bin/cli.js` child processes in install.test.js that
|
|
24
|
+
* have no way to inject a fake runner directly. Every in-process unit test
|
|
25
|
+
* (test/components.test.js and friends) should still pass its own injected
|
|
26
|
+
* runner regardless of NODE_ENV, so this guard only matters as a backstop.
|
|
27
|
+
*/
|
|
28
|
+
function defaultRunner(cmd, args) {
|
|
29
|
+
const isMutatingInstall =
|
|
30
|
+
(cmd === 'uv' && args[0] === 'tool' && args[1] === 'install') || args[0] === 'install';
|
|
31
|
+
if (isMutatingInstall && process.env.NODE_ENV === 'test') {
|
|
32
|
+
return { status: 1, error: null, blocked: true };
|
|
33
|
+
}
|
|
34
|
+
return spawnSync(cmd, args, { stdio: 'ignore' });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function ranOk(result) {
|
|
38
|
+
return !!result && !result.error && result.status === 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Is `bin --version` runnable on PATH? */
|
|
42
|
+
function binaryPresent(bin, runner) {
|
|
43
|
+
try {
|
|
44
|
+
return ranOk(runner(bin, ['--version']));
|
|
45
|
+
} catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Detect/install one component. Idempotent and side-effect-free when the
|
|
52
|
+
* binary is already present. Returns one of:
|
|
53
|
+
* - { status: 'present' } — componentKey already on PATH
|
|
54
|
+
* - { status: 'installed', tool } — installed via `tool` (or its fallback)
|
|
55
|
+
* - { status: 'failed', tool, message } — installer ran but exited non-zero
|
|
56
|
+
* - { status: 'pending', message } — neither installer tool was found;
|
|
57
|
+
* caller still installs the bundle's
|
|
58
|
+
* files, just not this dependency
|
|
59
|
+
*/
|
|
60
|
+
function ensureComponentInstalled(componentKey, component, { runner = defaultRunner } = {}) {
|
|
61
|
+
if (binaryPresent(componentKey, runner)) {
|
|
62
|
+
return { status: 'present', tool: null };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const { tool, package: pkg, fallback } = component.install;
|
|
66
|
+
|
|
67
|
+
if (binaryPresent(tool, runner)) {
|
|
68
|
+
const result = runner(tool, ['tool', 'install', pkg]);
|
|
69
|
+
if (ranOk(result)) return { status: 'installed', tool };
|
|
70
|
+
return {
|
|
71
|
+
status: 'failed',
|
|
72
|
+
tool,
|
|
73
|
+
message: `"${tool} tool install ${pkg}" failed (exit ${result ? result.status : 'unknown'}).`,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (fallback && binaryPresent(fallback, runner)) {
|
|
78
|
+
const result = runner(fallback, ['install', pkg]);
|
|
79
|
+
if (ranOk(result)) return { status: 'installed', tool: fallback };
|
|
80
|
+
return {
|
|
81
|
+
status: 'failed',
|
|
82
|
+
tool: fallback,
|
|
83
|
+
message: `"${fallback} install ${pkg}" failed (exit ${result ? result.status : 'unknown'}).`,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
status: 'pending',
|
|
89
|
+
tool: null,
|
|
90
|
+
message:
|
|
91
|
+
`Neither "${tool}" nor "${fallback || 'a fallback installer'}" was found on PATH — could not install ${pkg}. ` +
|
|
92
|
+
`Install uv (https://docs.astral.sh/uv/) and re-run, or install manually: ${tool} tool install "${pkg}". ` +
|
|
93
|
+
`This bundle's files were still installed; re-run "agents-cli install --bundle <key> --yes" once ${componentKey} is on PATH to finish setup.`,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Repo-relative source -> target-relative destination pairs a component ships. */
|
|
98
|
+
function componentFileTargets(componentKey, component) {
|
|
99
|
+
const targets = [];
|
|
100
|
+
if (component.configTemplate) {
|
|
101
|
+
targets.push({ src: component.configTemplate, rel: `${componentKey}/config.yaml` });
|
|
102
|
+
}
|
|
103
|
+
if (component.startScripts) {
|
|
104
|
+
if (component.startScripts.ps1) {
|
|
105
|
+
targets.push({ src: component.startScripts.ps1, rel: `${componentKey}/start-${componentKey}.ps1` });
|
|
106
|
+
}
|
|
107
|
+
if (component.startScripts.sh) {
|
|
108
|
+
targets.push({ src: component.startScripts.sh, rel: `${componentKey}/start-${componentKey}.sh` });
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return targets;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Copy a component's shipped files (config template + start scripts) into
|
|
116
|
+
* <targetBase>/<componentKey>/, hash-ledger tracked exactly like a bundle
|
|
117
|
+
* item — same idempotent copy-if-changed contract as install.js's item loop,
|
|
118
|
+
* just tagged with the shared componentEntryTag() instead of a bundle key so
|
|
119
|
+
* more than one dep-bundle installing it doesn't fight over ownership.
|
|
120
|
+
*/
|
|
121
|
+
function installComponentFiles(componentKey, component, { repoRoot, targetBase, ledger, timestamp }) {
|
|
122
|
+
const written = [];
|
|
123
|
+
const unchanged = [];
|
|
124
|
+
const tag = componentEntryTag(componentKey);
|
|
125
|
+
|
|
126
|
+
for (const { src, rel } of componentFileTargets(componentKey, component)) {
|
|
127
|
+
const srcFile = path.join(repoRoot, ...src.split('/'));
|
|
128
|
+
if (!fs.existsSync(srcFile)) {
|
|
129
|
+
throw new ComponentError(
|
|
130
|
+
`Component "${componentKey}" declares file "${src}" which does not exist in the repo at ${srcFile}`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const destFile = path.join(targetBase, ...rel.split('/'));
|
|
135
|
+
const sourceHash = sha256File(srcFile);
|
|
136
|
+
const existingEntry = ledger.entries[rel];
|
|
137
|
+
const destHash = fs.existsSync(destFile) ? sha256File(destFile) : null;
|
|
138
|
+
|
|
139
|
+
if (existingEntry && existingEntry.sha256 === sourceHash && destHash === sourceHash) {
|
|
140
|
+
unchanged.push(rel);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
copyFileEnsuringDir(srcFile, destFile);
|
|
145
|
+
ledger.entries[rel] = { sha256: sourceHash, bundle: tag, installedAt: timestamp };
|
|
146
|
+
written.push(rel);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return { written, unchanged };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Run the full component flow (detect/install the binary + copy its shipped
|
|
154
|
+
* files) for every dep a bundle declares. Called from install.js right
|
|
155
|
+
* after a bundle's own items/wiring are installed. Mutates `ledger` in
|
|
156
|
+
* place (entries + ledger.components); caller is responsible for saving it.
|
|
157
|
+
*/
|
|
158
|
+
function installComponentsForBundle(bundle, { manifest, repoRoot, targetBase, ledger, timestamp, runner }) {
|
|
159
|
+
const results = [];
|
|
160
|
+
for (const componentKey of bundle.deps || []) {
|
|
161
|
+
const component = manifest.components && manifest.components[componentKey];
|
|
162
|
+
if (!component) {
|
|
163
|
+
throw new ComponentError(
|
|
164
|
+
`Bundle "${bundle.key}" declares dep "${componentKey}" which is not defined in manifest.components`
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const detect = ensureComponentInstalled(componentKey, component, { runner });
|
|
169
|
+
const files = installComponentFiles(componentKey, component, { repoRoot, targetBase, ledger, timestamp });
|
|
170
|
+
|
|
171
|
+
ledger.components = ledger.components || {};
|
|
172
|
+
ledger.components[componentKey] = {
|
|
173
|
+
status: detect.status,
|
|
174
|
+
tool: detect.tool || null,
|
|
175
|
+
updatedAt: timestamp,
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
results.push({ key: componentKey, ...detect, filesWritten: files.written, filesUnchanged: files.unchanged });
|
|
179
|
+
}
|
|
180
|
+
return results;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Every currently-installed bundle (per the ledger) other than `excludingKey` whose manifest deps include componentKey. */
|
|
184
|
+
function remainingDependents(manifest, ledger, excludingKey, componentKey) {
|
|
185
|
+
return bundleKeysInLedger(ledger)
|
|
186
|
+
.filter((key) => key !== excludingKey)
|
|
187
|
+
.map((key) => findBundle(manifest, key))
|
|
188
|
+
.filter((b) => b && Array.isArray(b.deps) && b.deps.includes(componentKey));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Remove a component's shipped files (hash-matched only — a file edited
|
|
193
|
+
* since install is left in place, same protection uninstallBundle gives a
|
|
194
|
+
* bundle's own files) and drop its ledger.components entry. Does NOT touch
|
|
195
|
+
* the actual installed binary (uv tool / pipx package) — uninstalling a
|
|
196
|
+
* shared dependency the user may still use elsewhere is out of scope; the
|
|
197
|
+
* caller is expected to say so.
|
|
198
|
+
*/
|
|
199
|
+
function uninstallComponentFiles(componentKey, { targetBase, ledger }) {
|
|
200
|
+
const tag = componentEntryTag(componentKey);
|
|
201
|
+
const removed = [];
|
|
202
|
+
const keptUserEdited = [];
|
|
203
|
+
|
|
204
|
+
for (const [rel, entry] of Object.entries(ledger.entries)) {
|
|
205
|
+
if (entry.bundle !== tag) continue;
|
|
206
|
+
const destFile = path.join(targetBase, ...rel.split('/'));
|
|
207
|
+
if (fs.existsSync(destFile)) {
|
|
208
|
+
if (sha256File(destFile) === entry.sha256) {
|
|
209
|
+
fs.unlinkSync(destFile);
|
|
210
|
+
removeEmptyParents(path.dirname(destFile), targetBase);
|
|
211
|
+
removed.push(rel);
|
|
212
|
+
} else {
|
|
213
|
+
keptUserEdited.push(rel);
|
|
214
|
+
}
|
|
215
|
+
} else {
|
|
216
|
+
removed.push(rel);
|
|
217
|
+
}
|
|
218
|
+
delete ledger.entries[rel];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (ledger.components) delete ledger.components[componentKey];
|
|
222
|
+
return { removed, keptUserEdited };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Called from uninstall.js after a bundle's own files/wiring are removed.
|
|
227
|
+
* For each dep the bundle declared: if another still-installed bundle also
|
|
228
|
+
* depends on it, leave the component alone (`kept: true`); otherwise this
|
|
229
|
+
* was the last dependent, so its shipped files are removed (binary itself
|
|
230
|
+
* is left installed — see uninstallComponentFiles doc).
|
|
231
|
+
*/
|
|
232
|
+
function uninstallComponentsForBundle(bundle, { manifest, targetBase, ledger }) {
|
|
233
|
+
const results = [];
|
|
234
|
+
for (const componentKey of bundle.deps || []) {
|
|
235
|
+
if (remainingDependents(manifest, ledger, bundle.key, componentKey).length > 0) {
|
|
236
|
+
results.push({ key: componentKey, kept: true, removed: [], keptUserEdited: [] });
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
const fileResult = uninstallComponentFiles(componentKey, { targetBase, ledger });
|
|
240
|
+
results.push({ key: componentKey, kept: false, ...fileResult });
|
|
241
|
+
}
|
|
242
|
+
return results;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
module.exports = {
|
|
246
|
+
ComponentError,
|
|
247
|
+
componentEntryTag,
|
|
248
|
+
defaultRunner,
|
|
249
|
+
ensureComponentInstalled,
|
|
250
|
+
componentFileTargets,
|
|
251
|
+
installComponentFiles,
|
|
252
|
+
installComponentsForBundle,
|
|
253
|
+
remainingDependents,
|
|
254
|
+
uninstallComponentFiles,
|
|
255
|
+
uninstallComponentsForBundle,
|
|
256
|
+
};
|
package/lib/diff.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Minimal, dependency-free unified-line-diff for the update command's
|
|
4
|
+
// conflict prompt. No npm diff package: this CLI has zero runtime
|
|
5
|
+
// dependencies by design (see package.json), and the diff only needs to be
|
|
6
|
+
// readable in a terminal, not machine-parseable.
|
|
7
|
+
|
|
8
|
+
const DEFAULT_CONTEXT = 3;
|
|
9
|
+
const DEFAULT_MAX_LINES = 200;
|
|
10
|
+
// Guard against pathological O(n*m) time/memory on huge files — beyond this
|
|
11
|
+
// many (line-count-a * line-count-b) cells, skip straight to a summary
|
|
12
|
+
// instead of computing a full LCS table.
|
|
13
|
+
const MAX_DIFF_CELLS = 4_000_000;
|
|
14
|
+
|
|
15
|
+
function splitLines(text) {
|
|
16
|
+
if (text === '') return [];
|
|
17
|
+
return text.split(/\r\n|\r|\n/);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Longest-common-subsequence table, line-granularity, classic O(n*m) DP. */
|
|
21
|
+
function lcsTable(a, b) {
|
|
22
|
+
const n = a.length;
|
|
23
|
+
const m = b.length;
|
|
24
|
+
const table = new Array(n + 1);
|
|
25
|
+
for (let i = 0; i <= n; i += 1) {
|
|
26
|
+
table[i] = new Uint32Array(m + 1);
|
|
27
|
+
}
|
|
28
|
+
for (let i = n - 1; i >= 0; i -= 1) {
|
|
29
|
+
for (let j = m - 1; j >= 0; j -= 1) {
|
|
30
|
+
table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return table;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Walk the LCS table into a flat same/del/add op sequence with 1-based source line numbers. */
|
|
37
|
+
function buildOps(a, b, table) {
|
|
38
|
+
const ops = [];
|
|
39
|
+
let i = 0;
|
|
40
|
+
let j = 0;
|
|
41
|
+
while (i < a.length && j < b.length) {
|
|
42
|
+
if (a[i] === b[j]) {
|
|
43
|
+
ops.push({ type: 'same', line: a[i], aLine: i + 1, bLine: j + 1 });
|
|
44
|
+
i += 1;
|
|
45
|
+
j += 1;
|
|
46
|
+
} else if (table[i + 1][j] >= table[i][j + 1]) {
|
|
47
|
+
ops.push({ type: 'del', line: a[i], aLine: i + 1, bLine: null });
|
|
48
|
+
i += 1;
|
|
49
|
+
} else {
|
|
50
|
+
ops.push({ type: 'add', line: b[j], aLine: null, bLine: j + 1 });
|
|
51
|
+
j += 1;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
while (i < a.length) {
|
|
55
|
+
ops.push({ type: 'del', line: a[i], aLine: i + 1, bLine: null });
|
|
56
|
+
i += 1;
|
|
57
|
+
}
|
|
58
|
+
while (j < b.length) {
|
|
59
|
+
ops.push({ type: 'add', line: b[j], aLine: null, bLine: j + 1 });
|
|
60
|
+
j += 1;
|
|
61
|
+
}
|
|
62
|
+
return ops;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function findChangeRuns(ops) {
|
|
66
|
+
const runs = [];
|
|
67
|
+
let start = null;
|
|
68
|
+
for (let idx = 0; idx < ops.length; idx += 1) {
|
|
69
|
+
if (ops[idx].type !== 'same') {
|
|
70
|
+
if (start === null) start = idx;
|
|
71
|
+
} else if (start !== null) {
|
|
72
|
+
runs.push([start, idx - 1]);
|
|
73
|
+
start = null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (start !== null) runs.push([start, ops.length - 1]);
|
|
77
|
+
return runs;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Group ops into unified-diff-style hunks: each change run padded with up to
|
|
82
|
+
* `context` lines of surrounding unchanged context; hunks whose padded
|
|
83
|
+
* ranges touch/overlap are merged into one, matching real unified-diff
|
|
84
|
+
* behavior (no isolated 1-line context gaps between adjacent hunks).
|
|
85
|
+
*/
|
|
86
|
+
function groupHunks(ops, context) {
|
|
87
|
+
const runs = findChangeRuns(ops);
|
|
88
|
+
if (runs.length === 0) return [];
|
|
89
|
+
const ranges = [];
|
|
90
|
+
for (const [runStart, runEnd] of runs) {
|
|
91
|
+
const start = Math.max(0, runStart - context);
|
|
92
|
+
const end = Math.min(ops.length - 1, runEnd + context);
|
|
93
|
+
const last = ranges[ranges.length - 1];
|
|
94
|
+
if (last && start <= last[1] + 1) {
|
|
95
|
+
last[1] = Math.max(last[1], end);
|
|
96
|
+
} else {
|
|
97
|
+
ranges.push([start, end]);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return ranges.map(([s, e]) => ops.slice(s, e + 1));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function formatHunk(hunkOps) {
|
|
104
|
+
const aLines = hunkOps.filter((o) => o.aLine !== null).map((o) => o.aLine);
|
|
105
|
+
const bLines = hunkOps.filter((o) => o.bLine !== null).map((o) => o.bLine);
|
|
106
|
+
const aStart = aLines.length ? aLines[0] : 0;
|
|
107
|
+
const bStart = bLines.length ? bLines[0] : 0;
|
|
108
|
+
const header = `@@ -${aStart},${aLines.length} +${bStart},${bLines.length} @@`;
|
|
109
|
+
const body = hunkOps.map((o) => {
|
|
110
|
+
const prefix = o.type === 'same' ? ' ' : o.type === 'del' ? '-' : '+';
|
|
111
|
+
return `${prefix}${o.line}`;
|
|
112
|
+
});
|
|
113
|
+
return [header, ...body];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Plain-text unified diff of `oldText` vs `newText`. Returns a string; the
|
|
118
|
+
* caller decides how to display it (console.log, or bundled into --json
|
|
119
|
+
* output). Output is capped at `maxLines` total lines (including the
|
|
120
|
+
* `---`/`+++` header and hunk headers) with a truncation notice appended —
|
|
121
|
+
* this is a terminal conflict prompt, not an archival diff.
|
|
122
|
+
*/
|
|
123
|
+
function unifiedDiff(oldText, newText, { oldLabel = 'old', newLabel = 'new', context = DEFAULT_CONTEXT, maxLines = DEFAULT_MAX_LINES } = {}) {
|
|
124
|
+
const a = splitLines(oldText);
|
|
125
|
+
const b = splitLines(newText);
|
|
126
|
+
const header = [`--- ${oldLabel}`, `+++ ${newLabel}`];
|
|
127
|
+
|
|
128
|
+
if (a.length * b.length > MAX_DIFF_CELLS) {
|
|
129
|
+
return [
|
|
130
|
+
...header,
|
|
131
|
+
`(files too large to compute a line-level diff here — ${a.length} vs ${b.length} lines; ` +
|
|
132
|
+
'resolve by inspecting the files directly)',
|
|
133
|
+
].join('\n');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const table = lcsTable(a, b);
|
|
137
|
+
const ops = buildOps(a, b, table);
|
|
138
|
+
const hunks = groupHunks(ops, context);
|
|
139
|
+
|
|
140
|
+
const lines = [...header];
|
|
141
|
+
if (hunks.length === 0) {
|
|
142
|
+
lines.push('(no textual differences)');
|
|
143
|
+
} else {
|
|
144
|
+
for (const hunk of hunks) {
|
|
145
|
+
lines.push(...formatHunk(hunk));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (lines.length > maxLines) {
|
|
150
|
+
const truncated = lines.slice(0, maxLines);
|
|
151
|
+
truncated.push(`... diff truncated at ${maxLines} lines ...`);
|
|
152
|
+
return truncated.join('\n');
|
|
153
|
+
}
|
|
154
|
+
return lines.join('\n');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { unifiedDiff, DEFAULT_MAX_LINES };
|
package/lib/fsutil.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const crypto = require('node:crypto');
|
|
6
|
+
|
|
7
|
+
// Same exclusions as the repo's own .gitignore — never deploy build byproducts.
|
|
8
|
+
const EXCLUDED_NAMES = new Set(['__pycache__']);
|
|
9
|
+
const EXCLUDED_EXT = new Set(['.pyc']);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Any directory whose name starts with "." is skipped unconditionally
|
|
13
|
+
* (npx distribution slice #28's parity_check.py caught real cases: .pytest_
|
|
14
|
+
* cache/.mypy_cache tool caches, and — more seriously — skills/publish-
|
|
15
|
+
* article/.architecture-reviews/ and .html-mock-reviews/, this maintainer's
|
|
16
|
+
* own local review-session artifacts, both untracked). A directory-kind
|
|
17
|
+
* item's walk() reads the live filesystem, not git's tracked-file list, so
|
|
18
|
+
* anything sitting next to the source at install time gets copied unless
|
|
19
|
+
* filtered here. Verified safe repo-wide: no git-tracked file under any
|
|
20
|
+
* manifest scope dir (agents/skills/commands/hooks/proxy/global/statusline/
|
|
21
|
+
* scripts) lives inside a dot-prefixed directory component.
|
|
22
|
+
*/
|
|
23
|
+
function isExcludedDir(name) {
|
|
24
|
+
return name.startsWith('.') || EXCLUDED_NAMES.has(name);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function sha256File(filePath) {
|
|
28
|
+
return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Yield POSIX-style relative file paths under rootPath (a file or directory),
|
|
33
|
+
* skipping excluded names/extensions. Deterministic order (sorted per directory).
|
|
34
|
+
*/
|
|
35
|
+
function* walk(rootPath, relBase = '') {
|
|
36
|
+
const stat = fs.statSync(rootPath);
|
|
37
|
+
if (stat.isFile()) {
|
|
38
|
+
yield relBase || path.basename(rootPath);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const entries = fs
|
|
42
|
+
.readdirSync(rootPath, { withFileTypes: true })
|
|
43
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
44
|
+
for (const entry of entries) {
|
|
45
|
+
if (entry.isDirectory() && isExcludedDir(entry.name)) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (entry.isFile() && EXCLUDED_EXT.has(path.extname(entry.name))) {
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const abs = path.join(rootPath, entry.name);
|
|
52
|
+
const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
|
|
53
|
+
if (entry.isDirectory()) {
|
|
54
|
+
yield* walk(abs, rel);
|
|
55
|
+
} else if (entry.isFile()) {
|
|
56
|
+
yield rel;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function copyFileEnsuringDir(src, dest) {
|
|
62
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
63
|
+
fs.copyFileSync(src, dest);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function writeFileAtomic(filePath, contents) {
|
|
67
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
68
|
+
const tmp = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
|
|
69
|
+
fs.writeFileSync(tmp, contents);
|
|
70
|
+
fs.renameSync(tmp, filePath);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Remove `dir` and any now-empty parent directories, stopping at (and never
|
|
75
|
+
* removing) `stopAt` itself. Shared by uninstall (file removal) and update
|
|
76
|
+
* (upstream-removed file cleanup) so a fully-removed item doesn't leave
|
|
77
|
+
* empty directory litter behind.
|
|
78
|
+
*/
|
|
79
|
+
function removeEmptyParents(dir, stopAt) {
|
|
80
|
+
let current = dir;
|
|
81
|
+
const resolvedStop = path.resolve(stopAt);
|
|
82
|
+
while (path.resolve(current) !== resolvedStop && path.resolve(current).startsWith(resolvedStop)) {
|
|
83
|
+
let entries;
|
|
84
|
+
try {
|
|
85
|
+
entries = fs.readdirSync(current);
|
|
86
|
+
} catch {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (entries.length > 0) return;
|
|
90
|
+
try {
|
|
91
|
+
fs.rmdirSync(current);
|
|
92
|
+
} catch {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
current = path.dirname(current);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = { sha256File, walk, copyFileEnsuringDir, writeFileAtomic, removeEmptyParents };
|