@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/lib/install.js ADDED
@@ -0,0 +1,188 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+ const { loadManifest, findBundle } = require('./manifest');
7
+ const { loadLedger, saveLedger } = require('./ledger');
8
+ const { sha256File, walk, copyFileEnsuringDir } = require('./fsutil');
9
+ const { wireItems } = require('./wiring');
10
+ const { wireMcpItems } = require('./mcpWiring');
11
+ const { installComponentsForBundle } = require('./components');
12
+
13
+ class InstallError extends Error {}
14
+
15
+ function defaultTargetBase() {
16
+ return path.join(os.homedir(), '.claude');
17
+ }
18
+
19
+ /**
20
+ * Install one bundle's items into targetBase, recording every installed
21
+ * file's hash in the ledger. Idempotent: a file already present with a
22
+ * matching hash for the matching ledger entry is left untouched.
23
+ *
24
+ * `itemPaths` (optional): restrict the install to items whose `path` is in
25
+ * this array — the advanced menu's per-item selection. Omit to install every
26
+ * item in the bundle (the default, and the only behavior before this slice).
27
+ *
28
+ * `pythonChecker` (optional, test seam): overrides wiring.js's PATH probe
29
+ * for python3/python when deciding whether a Python-backed hook can be
30
+ * wired.
31
+ *
32
+ * `mcpConfigPath` (optional, test seam): overrides mcpWiring.js's default
33
+ * MCP config path (a sibling `.claude.json` next to targetBase) — mainly for
34
+ * tests that want an MCP config file independent of targetBase's location.
35
+ *
36
+ * `componentRunner` (optional, test seam): overrides components.js's
37
+ * spawnSync-based detection/install runner for any component this bundle
38
+ * declares in `deps` (e.g. litellm) — see components.js's defaultRunner doc.
39
+ */
40
+ function installBundle({
41
+ packageRoot,
42
+ bundleKey,
43
+ targetBase,
44
+ cliVersion,
45
+ now,
46
+ itemPaths,
47
+ pythonChecker,
48
+ mcpConfigPath,
49
+ componentRunner,
50
+ }) {
51
+ const { manifest, manifestPath } = loadManifest(packageRoot);
52
+ const repoRoot = path.dirname(manifestPath);
53
+
54
+ const bundle = findBundle(manifest, bundleKey);
55
+ if (!bundle) {
56
+ const available = manifest.bundles.map((b) => b.key);
57
+ throw new InstallError(
58
+ `Unknown bundle "${bundleKey}". Available bundles: ${available.length ? available.join(', ') : '(none defined yet)'}`
59
+ );
60
+ }
61
+
62
+ const itemFilter = itemPaths ? new Set(itemPaths) : null;
63
+ const items = itemFilter ? bundle.items.filter((item) => itemFilter.has(item.path)) : bundle.items;
64
+ if (itemFilter && items.length === 0) {
65
+ throw new InstallError(
66
+ `None of the requested item paths matched bundle "${bundle.key}". Available items: ${bundle.items.map((i) => i.path).join(', ')}`
67
+ );
68
+ }
69
+
70
+ const resolvedTargetBase = targetBase || defaultTargetBase();
71
+ const ledger = loadLedger(resolvedTargetBase, cliVersion);
72
+ const timestamp = now || new Date().toISOString();
73
+
74
+ let filesWritten = 0;
75
+ let filesUnchanged = 0;
76
+
77
+ for (const item of items) {
78
+ // mcp-kind items carry declarative wiring data only (see manifest.schema.json
79
+ // item.wiring doc) — their `path` typically points at a shared file like
80
+ // mcps/mcps.json that also holds OTHER servers' (often self-only) config, so
81
+ // copying it wholesale would leak unrelated/personal entries into a public
82
+ // install. Registering the MCP server is wiring execution, deferred to a
83
+ // later slice — this slice writes zero files for an mcp item.
84
+ if (item.kind === 'mcp') {
85
+ continue;
86
+ }
87
+
88
+ const srcRoot = path.join(repoRoot, ...item.path.split('/'));
89
+ if (!fs.existsSync(srcRoot)) {
90
+ throw new InstallError(
91
+ `Item path "${item.path}" declared by bundle "${bundle.key}" does not exist in the repo at ${srcRoot}`
92
+ );
93
+ }
94
+
95
+ const excluded = new Set(item.exclude || []);
96
+ // walk() yields a bare basename (not a path relative to srcRoot) when
97
+ // srcRoot is itself a file rather than a directory — single-file items
98
+ // (e.g. "agents/orchestrator.md", "proxy/reddit_intent_hook.py") need
99
+ // srcFile/relTarget computed directly from item.path, not joined onto it.
100
+ const srcIsFile = fs.statSync(srcRoot).isFile();
101
+ // targetPath (optional) overrides item.path when computing the install
102
+ // destination only — item.path itself stays what orphan-lint claiming
103
+ // and update.js source resolution use. See manifest.schema.json's item
104
+ // definition for the flatten/relocate semantics.
105
+ const targetPrefix = item.targetPath || item.path;
106
+
107
+ for (const relFile of walk(srcRoot)) {
108
+ if (excluded.has(relFile)) {
109
+ continue;
110
+ }
111
+
112
+ const srcFile = srcIsFile ? srcRoot : path.join(srcRoot, ...relFile.split('/'));
113
+ const sourcePath = srcIsFile ? item.path : `${item.path}/${relFile}`;
114
+ const relTarget = srcIsFile ? targetPrefix : `${targetPrefix}/${relFile}`;
115
+ const destFile = path.join(resolvedTargetBase, ...relTarget.split('/'));
116
+ const sourceHash = sha256File(srcFile);
117
+
118
+ const existingEntry = ledger.entries[relTarget];
119
+ const destHash = fs.existsSync(destFile) ? sha256File(destFile) : null;
120
+
121
+ if (existingEntry && existingEntry.sha256 === sourceHash && destHash === sourceHash) {
122
+ filesUnchanged += 1;
123
+ continue;
124
+ }
125
+
126
+ copyFileEnsuringDir(srcFile, destFile);
127
+ ledger.entries[relTarget] = {
128
+ sha256: sourceHash,
129
+ bundle: bundle.key,
130
+ installedAt: timestamp,
131
+ sourcePath,
132
+ };
133
+ filesWritten += 1;
134
+ }
135
+ }
136
+
137
+ const wiring = wireItems(items, {
138
+ targetBase: resolvedTargetBase,
139
+ bundleKey: bundle.key,
140
+ ledger,
141
+ timestamp,
142
+ pythonChecker,
143
+ });
144
+
145
+ const mcpWiring = wireMcpItems(items, {
146
+ targetBase: resolvedTargetBase,
147
+ bundleKey: bundle.key,
148
+ ledger,
149
+ timestamp,
150
+ configPath: mcpConfigPath,
151
+ });
152
+
153
+ const components = installComponentsForBundle(bundle, {
154
+ manifest,
155
+ repoRoot,
156
+ targetBase: resolvedTargetBase,
157
+ ledger,
158
+ timestamp,
159
+ runner: componentRunner,
160
+ });
161
+
162
+ ledger.cliVersion = cliVersion;
163
+ saveLedger(resolvedTargetBase, ledger);
164
+
165
+ return {
166
+ bundle: bundle.key,
167
+ targetBase: resolvedTargetBase,
168
+ filesWritten,
169
+ filesUnchanged,
170
+ unchanged:
171
+ filesWritten === 0 &&
172
+ wiring.wired.length === 0 &&
173
+ mcpWiring.wired.length === 0 &&
174
+ components.every((c) => (c.filesWritten || []).length === 0),
175
+ hooksWired: wiring.wired,
176
+ hooksAlreadyWired: wiring.alreadyWired,
177
+ hooksSkippedNoPython: wiring.skippedNoPython,
178
+ settingsBackupFile: wiring.backupFile,
179
+ mcpWired: mcpWiring.wired,
180
+ mcpAlreadyWired: mcpWiring.alreadyWired,
181
+ mcpSkippedNoSecret: mcpWiring.skippedNoSecret,
182
+ mcpConfigPath: mcpWiring.configPath,
183
+ mcpBackupFile: mcpWiring.backupFile,
184
+ components,
185
+ };
186
+ }
187
+
188
+ module.exports = { installBundle, defaultTargetBase, InstallError };
package/lib/ledger.js ADDED
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { major } = require('./semver');
6
+ const { writeFileAtomic } = require('./fsutil');
7
+
8
+ // The highest install-ledger schemaVersion major this CLI build understands.
9
+ const CLI_LEDGER_SCHEMA_MAJOR = 1;
10
+ // The full current schema version migrateLedger() stamps a same-major ledger
11
+ // up to. Bump this alongside adding a new entry to MIGRATIONS.
12
+ // 1.1.0 (npx distribution slice #28): entries[].sourcePath added — the exact
13
+ // repo-relative source path a file was copied from, independent of any
14
+ // item.targetPath override. Additive/backward-compatible: an entry written
15
+ // by an older CLI simply lacks sourcePath, and every reader (managed_files_
16
+ // guard.py, update.js) falls back to the ledger key (relTarget) when absent.
17
+ const CLI_LEDGER_SCHEMA_VERSION = '1.1.0';
18
+ const LEDGER_FILE_NAME = 'agents-ledger.json';
19
+ // ledger.entries[].bundle tag used for files owned by a shared component
20
+ // (e.g. the litellm config/start-script templates) rather than any one
21
+ // bundle — see packages/cli/lib/components.js. Filtered out of
22
+ // bundleKeysInLedger() so `agents-cli update`/`secrets` (which resolve keys
23
+ // via findBundle()) never see a synthetic non-bundle key.
24
+ const COMPONENT_ENTRY_PREFIX = '__component:';
25
+
26
+ // Per-major-version migration functions, keyed by the ledger's OLD major
27
+ // version number. Each receives the raw parsed ledger object and returns a
28
+ // (possibly mutated-in-place) ledger object shaped for the current major.
29
+ // #37's same-major auto-migrate hook point — empty today (identity for
30
+ // major 1) since no ledger shape change has shipped yet.
31
+ const MIGRATIONS = {
32
+ 1: (ledger) => ledger,
33
+ };
34
+
35
+ class LedgerError extends Error {}
36
+
37
+ function ledgerPath(targetBase) {
38
+ return path.join(targetBase, LEDGER_FILE_NAME);
39
+ }
40
+
41
+ /**
42
+ * Run the migration registered for `raw`'s major version (identity if none
43
+ * registered) and stamp the result's schemaVersion to `currentVersion`.
44
+ * `migrations`/`currentVersion` are injectable (test seam) so a synthetic
45
+ * migration can be exercised without editing the production MIGRATIONS
46
+ * table/version constant.
47
+ */
48
+ function migrateLedger(raw, { migrations = MIGRATIONS, currentVersion = CLI_LEDGER_SCHEMA_VERSION } = {}) {
49
+ const ledgerMajor = major(raw.schemaVersion);
50
+ const migrate = migrations[ledgerMajor] || ((ledger) => ledger);
51
+ const migrated = migrate(raw);
52
+ migrated.schemaVersion = currentVersion;
53
+ return migrated;
54
+ }
55
+
56
+ /**
57
+ * Load the per-machine install ledger, or a fresh empty one if none exists
58
+ * yet. Refuses (LedgerError) a ledger written by a newer-major CLI, per the
59
+ * #37 resolution: fail-closed, never guess-parse. A same-major ledger is
60
+ * run through migrateLedger() so an older-minor ledger picks up any shape
61
+ * changes a later minor introduced.
62
+ */
63
+ function loadLedger(targetBase, cliVersion) {
64
+ const file = ledgerPath(targetBase);
65
+ if (!fs.existsSync(file)) {
66
+ return { schemaVersion: CLI_LEDGER_SCHEMA_VERSION, cliVersion, entries: {} };
67
+ }
68
+
69
+ let raw;
70
+ try {
71
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
72
+ } catch (err) {
73
+ throw new LedgerError(`Ledger at ${file} is not valid JSON: ${err.message}`);
74
+ }
75
+ if (!raw.schemaVersion || !raw.entries) {
76
+ throw new LedgerError(`Ledger at ${file} is missing required fields (schemaVersion/entries)`);
77
+ }
78
+
79
+ const ledgerMajor = major(raw.schemaVersion);
80
+ if (ledgerMajor > CLI_LEDGER_SCHEMA_MAJOR) {
81
+ throw new LedgerError(
82
+ `Existing ledger at ${file} has schemaVersion ${raw.schemaVersion}, a newer major than this CLI ` +
83
+ `understands (supports ${CLI_LEDGER_SCHEMA_MAJOR}.x). Update the CLI: npx @yasaswy.nagavolu/agents@latest install`
84
+ );
85
+ }
86
+
87
+ return migrateLedger(raw);
88
+ }
89
+
90
+ function saveLedger(targetBase, ledger) {
91
+ writeFileAtomic(ledgerPath(targetBase), `${JSON.stringify(ledger, null, 2)}\n`);
92
+ }
93
+
94
+ /** Every bundle key with at least one file/wiring/mcp entry in `ledger`. */
95
+ function bundleKeysInLedger(ledger) {
96
+ const fromEntries = Object.values(ledger.entries || {})
97
+ .map((e) => e.bundle)
98
+ .filter((b) => !String(b).startsWith(COMPONENT_ENTRY_PREFIX));
99
+ const fromWiring = Object.keys(ledger.wiring || {});
100
+ const fromMcp = Object.keys(ledger.mcp || {});
101
+ return [...new Set([...fromEntries, ...fromWiring, ...fromMcp])];
102
+ }
103
+
104
+ module.exports = {
105
+ loadLedger,
106
+ saveLedger,
107
+ ledgerPath,
108
+ migrateLedger,
109
+ bundleKeysInLedger,
110
+ LedgerError,
111
+ CLI_LEDGER_SCHEMA_MAJOR,
112
+ CLI_LEDGER_SCHEMA_VERSION,
113
+ MIGRATIONS,
114
+ LEDGER_FILE_NAME,
115
+ COMPONENT_ENTRY_PREFIX,
116
+ };
@@ -0,0 +1,100 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { major } = require('./semver');
6
+
7
+ // The highest manifest schemaVersion major this CLI build understands.
8
+ const CLI_MANIFEST_SCHEMA_MAJOR = 1;
9
+
10
+ class ManifestError extends Error {}
11
+
12
+ /**
13
+ * Where manifest.json lives relative to the CLI package. Repo-root today
14
+ * (packages/cli/../../manifest.json). Packing the manifest into the
15
+ * published npm tarball is a decision deferred to npx distribution slice
16
+ * #22 — this function is the single seam that slice will change.
17
+ */
18
+ function resolveManifestPath(packageRoot) {
19
+ return path.join(packageRoot, '..', '..', 'manifest.json');
20
+ }
21
+
22
+ function assertStructure(raw, manifestPath) {
23
+ for (const key of ['schemaVersion', 'components', 'bundles', 'internal']) {
24
+ if (!(key in raw)) {
25
+ throw new ManifestError(`manifest.json at ${manifestPath} is missing required field "${key}"`);
26
+ }
27
+ }
28
+ if (!Array.isArray(raw.bundles)) {
29
+ throw new ManifestError(`manifest.json at ${manifestPath}: "bundles" must be an array`);
30
+ }
31
+ for (const bundle of raw.bundles) {
32
+ for (const key of ['key', 'title', 'summary', 'profile', 'items']) {
33
+ if (!(key in bundle)) {
34
+ throw new ManifestError(
35
+ `manifest.json at ${manifestPath}: bundle is missing required field "${key}" (${JSON.stringify(bundle).slice(0, 120)})`
36
+ );
37
+ }
38
+ }
39
+ if (!Array.isArray(bundle.items)) {
40
+ throw new ManifestError(`manifest.json at ${manifestPath}: bundle "${bundle.key}" must have an items array`);
41
+ }
42
+ if (bundle.items.length === 0 && !bundle.passthrough) {
43
+ throw new ManifestError(
44
+ `manifest.json at ${manifestPath}: bundle "${bundle.key}" must have a non-empty items array (or declare passthrough)`
45
+ );
46
+ }
47
+ if (bundle.passthrough && !bundle.passthrough.command) {
48
+ throw new ManifestError(
49
+ `manifest.json at ${manifestPath}: bundle "${bundle.key}" declares passthrough without a command`
50
+ );
51
+ }
52
+ for (const item of bundle.items) {
53
+ if (!item.path || !item.kind) {
54
+ throw new ManifestError(`manifest.json at ${manifestPath}: bundle "${bundle.key}" has an item missing path/kind`);
55
+ }
56
+ }
57
+ }
58
+ }
59
+
60
+ function loadManifest(packageRoot) {
61
+ const manifestPath = resolveManifestPath(packageRoot);
62
+ if (!fs.existsSync(manifestPath)) {
63
+ throw new ManifestError(
64
+ `manifest.json not found at ${manifestPath}. This CLI build resolves the manifest relative to the ` +
65
+ `repo (repo-root manifest.json); packing it into the published tarball is decided in a later slice ` +
66
+ `(npx distribution slice #22). If you installed via npm/npx, this build predates that packaging.`
67
+ );
68
+ }
69
+
70
+ let raw;
71
+ try {
72
+ raw = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
73
+ } catch (err) {
74
+ throw new ManifestError(`manifest.json at ${manifestPath} is not valid JSON: ${err.message}`);
75
+ }
76
+
77
+ assertStructure(raw, manifestPath);
78
+
79
+ const manifestMajor = major(raw.schemaVersion);
80
+ if (manifestMajor > CLI_MANIFEST_SCHEMA_MAJOR) {
81
+ throw new ManifestError(
82
+ `manifest.json schemaVersion ${raw.schemaVersion} is a newer major version than this CLI understands ` +
83
+ `(supports ${CLI_MANIFEST_SCHEMA_MAJOR}.x). Update the CLI: npx @yasaswy.nagavolu/agents@latest install`
84
+ );
85
+ }
86
+
87
+ return { manifest: raw, manifestPath };
88
+ }
89
+
90
+ function findBundle(manifest, key) {
91
+ return manifest.bundles.find((bundle) => bundle.key === key);
92
+ }
93
+
94
+ module.exports = {
95
+ loadManifest,
96
+ resolveManifestPath,
97
+ findBundle,
98
+ ManifestError,
99
+ CLI_MANIFEST_SCHEMA_MAJOR,
100
+ };