layermap 0.1.26 → 0.1.27
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 +3 -2
- package/analyzers/project-map-java/java-map.jar +0 -0
- package/dist/cli.mjs +5 -2
- package/package.json +1 -1
- package/pi/layermap.mjs +212 -243
package/README.md
CHANGED
|
@@ -166,8 +166,9 @@ the agent can use the existing code instead of a copy. When the change takes awa
|
|
|
166
166
|
declaration, as when new code replaces old, it names that declaration, so the agent can delete what
|
|
167
167
|
the change left behind. It never writes or runs tests. In Claude Code and
|
|
168
168
|
CodeBuddy Code the plugin asks the agent once, before it finishes, to run this check for each repository it edited code in
|
|
169
|
-
and has not checked since, whether through its edit tools or shell commands
|
|
170
|
-
work tree do not count); the Pi extension does the same after the agent's own
|
|
169
|
+
and has not checked since, whether through its edit tools or shell commands, which count for the code files they name
|
|
170
|
+
(changes another session makes in the same work tree do not count); the Pi extension does the same after the agent's own
|
|
171
|
+
edits. Set `LAYERMAP_STOP_CHECK=0` to turn that
|
|
171
172
|
off. Codex and DeepSeek Harness are told to run it.
|
|
172
173
|
|
|
173
174
|
**Without plugins:** run `npx layermap setup claude` or `npx layermap setup codex`. Setup does three
|
|
Binary file
|
package/dist/cli.mjs
CHANGED
|
@@ -24154,6 +24154,10 @@ import { createInterface } from "node:readline";
|
|
|
24154
24154
|
import { setTimeout as delay } from "node:timers/promises";
|
|
24155
24155
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
24156
24156
|
|
|
24157
|
+
// src/agent/notes.ts
|
|
24158
|
+
var AGENT_MAP_NOTE = "The layermap MCP server is available here. When a task needs to know what calls a function, what a change could affect beyond the code you are editing, or where code is used, use its project_explore_map tool (direction INCOMING, depth up to 8) instead of grep, then confirm in source; a change confined to code you have read does not need it. When the edits are done, call its project_check_changes tool once before reporting the work done.";
|
|
24159
|
+
var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
|
|
24160
|
+
|
|
24157
24161
|
// src/agent/projects.ts
|
|
24158
24162
|
import { existsSync as existsSync6 } from "node:fs";
|
|
24159
24163
|
import { readdir as readdir2, realpath as realpath3, stat as stat2 } from "node:fs/promises";
|
|
@@ -24396,7 +24400,6 @@ async function runMapTool(map2, { name, args }, signal) {
|
|
|
24396
24400
|
}
|
|
24397
24401
|
}
|
|
24398
24402
|
var AGENT_MAP_INSTRUCTIONS = `Use the LayerMap tools instead of grep whenever a task needs to know what calls something, what a change could affect beyond the code at hand, where something is used, or how the code is organized; a change confined to code you have read does not need them: project_explore_map on a declaration with direction INCOMING and depth up to 8 traces its callers up to the entry points (HTTP routes, handlers, jobs, commands) in one call, which grep can only approximate one name at a time. LayerMap is a static, layered map of this repository for TypeScript/JavaScript, Go, Python and Java: directories and modules, each file's declarations, and each declaration's callers and callees up to 8 hops. path "." shows what exists. Continue from any NOT EXPANDED declarations a view names, then confirm entry points in source. When the edits are done, call project_check_changes once before reporting the work done, not after every edit: it lists the entry points and existing tests the changes reach, and the existing tests the diff rewrote. The map is static: dynamic dispatch, framework wiring and unresolved targets need source reading, and a missing relationship does not prove absence. The first call on a project builds its map, which can take minutes on a large repository; later calls update only what changed. Each result names the Git repository it maps, and its paths are relative to that repository's root. The paths you give are relative to the repository the session started in, or to the starting folder when that is not a repository (such as a folder holding several); for a file in another repository, such as after changing directory, give its absolute path. Give project_check_changes a path in the repository to check when the session works in more than one.`;
|
|
24399
|
-
var AGENT_MAP_NOTE = "The layermap MCP server is available here. When a task needs to know what calls a function, what a change could affect beyond the code you are editing, or where code is used, use its project_explore_map tool (direction INCOMING, depth up to 8) instead of grep, then confirm in source; a change confined to code you have read does not need it. When the edits are done, call its project_check_changes tool once before reporting the work done.";
|
|
24400
24403
|
|
|
24401
24404
|
// src/agent/mcp.ts
|
|
24402
24405
|
var ROOTS_WAIT_MS = 5e3;
|
|
@@ -24460,7 +24463,7 @@ function serveMcp(options) {
|
|
|
24460
24463
|
content: [
|
|
24461
24464
|
{
|
|
24462
24465
|
type: "text",
|
|
24463
|
-
text: project ?
|
|
24466
|
+
text: project ? `${projectHeading(project)}
|
|
24464
24467
|
|
|
24465
24468
|
${text}` : text
|
|
24466
24469
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "layermap",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.27",
|
|
4
4
|
"mcpName": "io.github.coffeecoproject/layermap",
|
|
5
5
|
"description": "A layered map of a codebase for coding agents: directories, modules and call chains across TypeScript, JavaScript, Go, Python and Java.",
|
|
6
6
|
"license": "Apache-2.0",
|
package/pi/layermap.mjs
CHANGED
|
@@ -1,45 +1,181 @@
|
|
|
1
1
|
// Generated by scripts/plugins.ts from scripts/pi-extension.mjs.
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
// The map runs in LayerMap's own MCP server, started with Pi's Node in the session's directory; its
|
|
6
|
-
// tools become Pi tools of the same names. Like the Claude Code plugin's stop hook, the extension
|
|
7
|
-
// asks the agent once, before it settles, to check what its code edits affect.
|
|
8
|
-
import { execFile, spawn } from "node:child_process";
|
|
9
|
-
import { createHash } from "node:crypto";
|
|
10
|
-
import { readFile, stat } from "node:fs/promises";
|
|
11
|
-
import os from "node:os";
|
|
12
|
-
import path from "node:path";
|
|
2
|
+
// scripts/pi-extension.mjs
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import path2 from "node:path";
|
|
13
5
|
import { createInterface } from "node:readline";
|
|
14
6
|
import { fileURLToPath } from "node:url";
|
|
15
7
|
import { Type } from "typebox";
|
|
16
8
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
9
|
+
// src/agent/notes.ts
|
|
10
|
+
var AGENT_MAP_NOTE = "The layermap MCP server is available here. When a task needs to know what calls a function, what a change could affect beyond the code you are editing, or where code is used, use its project_explore_map tool (direction INCOMING, depth up to 8) instead of grep, then confirm in source; a change confined to code you have read does not need it. When the edits are done, call its project_check_changes tool once before reporting the work done.";
|
|
11
|
+
var AGENT_STOP_CHECK = "Code changed in this session. Before finishing, call the LayerMap tool project_check_changes: it lists the routes, jobs and commands the changes reach and the existing tests related to them. Check the affected entry points in source, and run the related tests if the change needs verifying. If it lists EXISTING TESTS CHANGED or code SHARED BY several areas, decide which of them the request is about; for the others, restore their tests and narrow the change. If it lists NEW MODULE DEPENDENCIES, check that each runs the way the project's layers do. If you already checked these changes, say so briefly and finish.";
|
|
12
|
+
var AGENT_STOP_CHECK_REPOSITORIES = "The changes are in more than one repository, or not in the one the session started in: call project_check_changes once for each, with its path set to the repository: ";
|
|
13
|
+
var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
|
|
14
|
+
|
|
15
|
+
// src/agent/session-changes.ts
|
|
16
|
+
import { execFile } from "node:child_process";
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import { readFile, stat } from "node:fs/promises";
|
|
19
|
+
import os from "node:os";
|
|
20
|
+
import path from "node:path";
|
|
21
|
+
var CODE_EXTENSIONS = ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "go", "py", "java"];
|
|
22
|
+
var CODE_FILE = new RegExp(`\\.(?:${CODE_EXTENSIONS.join("|")})$`, "u");
|
|
23
|
+
var CODE_GLOBS = CODE_EXTENSIONS.map((extension) => `*.${extension}`);
|
|
24
|
+
var git = (cwd, args) => new Promise(
|
|
25
|
+
(resolve) => execFile(
|
|
26
|
+
"git",
|
|
27
|
+
["-C", cwd, ...args],
|
|
28
|
+
{ maxBuffer: 64 * 1024 * 1024, windowsHide: true },
|
|
29
|
+
(error, stdout) => resolve(error ? "" : stdout)
|
|
30
|
+
)
|
|
32
31
|
);
|
|
32
|
+
async function repositoryGit(repository, args) {
|
|
33
|
+
const drivers = new Set(
|
|
34
|
+
(await git(repository, ["config", "--name-only", "--get-regexp", "^filter\\."])).split("\n").flatMap((key) => /^filter\.(.+)\.[^.]+$/su.exec(key)?.[1] ?? [])
|
|
35
|
+
);
|
|
36
|
+
const blank = [...drivers].flatMap(
|
|
37
|
+
(driver) => ["clean=", "process=", "required=false"].flatMap((setting) => [
|
|
38
|
+
"-c",
|
|
39
|
+
`filter.${driver}.${setting}`
|
|
40
|
+
])
|
|
41
|
+
);
|
|
42
|
+
return git(repository, [
|
|
43
|
+
"-c",
|
|
44
|
+
"core.fsmonitor=false",
|
|
45
|
+
"-c",
|
|
46
|
+
"core.quotePath=false",
|
|
47
|
+
...blank,
|
|
48
|
+
...args
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
var isDirectory = async (given) => Boolean((await stat(given).catch(() => void 0))?.isDirectory());
|
|
52
|
+
async function existingDirectory(given) {
|
|
53
|
+
let directory = given;
|
|
54
|
+
while (!await isDirectory(directory)) {
|
|
55
|
+
if (path.dirname(directory) === directory) return void 0;
|
|
56
|
+
directory = path.dirname(directory);
|
|
57
|
+
}
|
|
58
|
+
return directory;
|
|
59
|
+
}
|
|
60
|
+
async function repositoryAt(given) {
|
|
61
|
+
const directory = await existingDirectory(given);
|
|
62
|
+
return directory ? (await git(directory, ["rev-parse", "--show-toplevel"])).trim() : "";
|
|
63
|
+
}
|
|
64
|
+
async function codeEdits(files) {
|
|
65
|
+
const located = /* @__PURE__ */ new Map();
|
|
66
|
+
const locate = async (directory) => {
|
|
67
|
+
const [repository, prefix = ""] = (await git(directory, ["rev-parse", "--show-toplevel", "--show-prefix"])).split("\n");
|
|
68
|
+
return repository ? { repository, prefix } : void 0;
|
|
69
|
+
};
|
|
70
|
+
const edits = [];
|
|
71
|
+
for (const file of new Set(files)) {
|
|
72
|
+
if (!CODE_FILE.test(file)) continue;
|
|
73
|
+
const directory = await existingDirectory(path.dirname(file));
|
|
74
|
+
if (!directory) continue;
|
|
75
|
+
if (!located.has(directory)) located.set(directory, locate(directory));
|
|
76
|
+
const where = await located.get(directory);
|
|
77
|
+
if (!where) continue;
|
|
78
|
+
const rest = path.relative(directory, file).split(path.sep).join("/");
|
|
79
|
+
edits.push({ kind: "edit", repository: where.repository, file: `${where.prefix}${rest}` });
|
|
80
|
+
}
|
|
81
|
+
return edits;
|
|
82
|
+
}
|
|
83
|
+
async function commandFiles(cwd, command) {
|
|
84
|
+
const words = [
|
|
85
|
+
...new Set(
|
|
86
|
+
command.split(/[^A-Za-z0-9._/\\~:@+,%-]+/u).map((word) => word.replace(/[,:]+$/u, "")).filter(Boolean)
|
|
87
|
+
)
|
|
88
|
+
];
|
|
89
|
+
const resolve = (base, word) => word.startsWith("~/") ? path.join(os.homedir(), word.slice(2)) : path.resolve(base, word);
|
|
90
|
+
const bases = [cwd];
|
|
91
|
+
for (const word of words.filter((word2) => !CODE_FILE.test(word2)).slice(0, 300)) {
|
|
92
|
+
if (bases.length > 20) break;
|
|
93
|
+
const named = resolve(cwd, word);
|
|
94
|
+
if (!bases.includes(named) && await isDirectory(named)) bases.push(named);
|
|
95
|
+
}
|
|
96
|
+
const files = /* @__PURE__ */ new Set();
|
|
97
|
+
for (const word of words.filter((word2) => CODE_FILE.test(word2)))
|
|
98
|
+
for (const base of bases) {
|
|
99
|
+
const file = resolve(base, word);
|
|
100
|
+
if (files.size < 200 && await isDirectory(path.dirname(file))) files.add(file);
|
|
101
|
+
}
|
|
102
|
+
return [...files];
|
|
103
|
+
}
|
|
104
|
+
var hash = (content) => createHash("sha256").update(content).digest("hex");
|
|
105
|
+
async function fileStates(files) {
|
|
106
|
+
const states = {};
|
|
107
|
+
for (const file of files) {
|
|
108
|
+
const content = await readFile(file).catch(() => void 0);
|
|
109
|
+
states[file] = content ? hash(content) : "";
|
|
110
|
+
}
|
|
111
|
+
return states;
|
|
112
|
+
}
|
|
113
|
+
var changedFiles = (before, after) => Object.keys(before).filter((file) => before[file] !== after[file]);
|
|
114
|
+
async function changedCode(repository) {
|
|
115
|
+
if (!await git(repository, ["rev-parse", "--verify", "--quiet", "HEAD"])) return /* @__PURE__ */ new Set();
|
|
116
|
+
const listed = await Promise.all([
|
|
117
|
+
repositoryGit(repository, ["diff", "HEAD", "--name-only", "--no-renames", "--", ...CODE_GLOBS]),
|
|
118
|
+
repositoryGit(repository, ["ls-files", "--others", "--exclude-standard", "--", ...CODE_GLOBS])
|
|
119
|
+
]);
|
|
120
|
+
return new Set(listed.join("\n").split("\n").filter(Boolean));
|
|
121
|
+
}
|
|
122
|
+
async function checkRequest(changes, start, asked) {
|
|
123
|
+
const pending = /* @__PURE__ */ new Map();
|
|
124
|
+
for (const change of changes) {
|
|
125
|
+
if (change.kind === "check") pending.delete(change.repository);
|
|
126
|
+
else
|
|
127
|
+
pending.set(
|
|
128
|
+
change.repository,
|
|
129
|
+
(pending.get(change.repository) ?? /* @__PURE__ */ new Set()).add(change.file)
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
const due = [];
|
|
133
|
+
for (const [repository, files] of [...pending].sort(([a], [b]) => a < b ? -1 : 1)) {
|
|
134
|
+
const changed = await changedCode(repository);
|
|
135
|
+
const still = [...files].filter((file) => changed.has(file)).sort();
|
|
136
|
+
if (still.length)
|
|
137
|
+
due.push({
|
|
138
|
+
repository,
|
|
139
|
+
states: await fileStates(still.map((file) => path.join(repository, file)))
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
const fingerprint = due.length ? hash(JSON.stringify(due)) : "";
|
|
143
|
+
if (!fingerprint || fingerprint === asked) return void 0;
|
|
144
|
+
const elsewhere = due.some(({ repository }) => repository !== start);
|
|
145
|
+
return {
|
|
146
|
+
text: elsewhere ? `${AGENT_STOP_CHECK} ${AGENT_STOP_CHECK_REPOSITORIES}${due.map(({ repository }) => repository).join(", ")}.` : AGENT_STOP_CHECK,
|
|
147
|
+
fingerprint
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
var [HEADING_START, HEADING_END] = projectHeading("\0").split("\0");
|
|
151
|
+
function checkedRepository(result, depth = 0) {
|
|
152
|
+
if (typeof result === "string") {
|
|
153
|
+
const line = result.split("\n", 1)[0] ?? "";
|
|
154
|
+
return line.startsWith(HEADING_START) && line.endsWith(HEADING_END) ? line.slice(HEADING_START.length, line.length - HEADING_END.length) : void 0;
|
|
155
|
+
}
|
|
156
|
+
if (!result || typeof result !== "object" || depth > 3) return void 0;
|
|
157
|
+
for (const value of Object.values(result)) {
|
|
158
|
+
const repository = checkedRepository(value, depth + 1);
|
|
159
|
+
if (repository) return repository;
|
|
160
|
+
}
|
|
161
|
+
return void 0;
|
|
162
|
+
}
|
|
33
163
|
|
|
34
|
-
//
|
|
35
|
-
|
|
164
|
+
// scripts/pi-extension.mjs
|
|
165
|
+
var CHECK_TOOL = "project_check_changes";
|
|
166
|
+
var CLI = path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "dist", "cli.mjs");
|
|
167
|
+
var READS = /* @__PURE__ */ new Set(["read", "grep", "find", "ls"]);
|
|
168
|
+
var WRITES = /* @__PURE__ */ new Set(["edit", "write"]);
|
|
169
|
+
var PATCH = "apply_patch";
|
|
170
|
+
var PATCH_FILES = /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/gm;
|
|
171
|
+
var MapServer = class {
|
|
36
172
|
constructor(cwd) {
|
|
37
|
-
this.pending = new Map();
|
|
173
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
38
174
|
this.next = 1;
|
|
39
175
|
this.child = spawn(process.execPath, [CLI, "mcp"], {
|
|
40
176
|
cwd,
|
|
41
177
|
stdio: ["pipe", "pipe", "ignore"],
|
|
42
|
-
windowsHide: true
|
|
178
|
+
windowsHide: true
|
|
43
179
|
});
|
|
44
180
|
this.exited = new Promise((resolve) => this.child.once("exit", resolve));
|
|
45
181
|
this.child.once("error", (error) => this.fail(error));
|
|
@@ -64,7 +200,8 @@ class MapServer {
|
|
|
64
200
|
this.dead = true;
|
|
65
201
|
}
|
|
66
202
|
send(message) {
|
|
67
|
-
this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}
|
|
203
|
+
this.child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}
|
|
204
|
+
`);
|
|
68
205
|
}
|
|
69
206
|
request(method, params, signal) {
|
|
70
207
|
if (this.dead) return Promise.reject(new Error("The LayerMap server is not running."));
|
|
@@ -78,7 +215,7 @@ class MapServer {
|
|
|
78
215
|
this.send({ method: "notifications/cancelled", params: { requestId: id } });
|
|
79
216
|
reject(new Error("Cancelled."));
|
|
80
217
|
},
|
|
81
|
-
{ once: true }
|
|
218
|
+
{ once: true }
|
|
82
219
|
);
|
|
83
220
|
this.send({ id, method, params });
|
|
84
221
|
});
|
|
@@ -87,155 +224,38 @@ class MapServer {
|
|
|
87
224
|
await this.request("initialize", {
|
|
88
225
|
protocolVersion: "2025-06-18",
|
|
89
226
|
capabilities: {},
|
|
90
|
-
clientInfo: { name: "layermap-pi", version }
|
|
227
|
+
clientInfo: { name: "layermap-pi", version }
|
|
91
228
|
});
|
|
92
|
-
// The server starts building the map as soon as it is told the client is ready.
|
|
93
229
|
this.send({ method: "notifications/initialized" });
|
|
94
230
|
return (await this.request("tools/list", {})).tools;
|
|
95
231
|
}
|
|
96
232
|
async stop() {
|
|
97
233
|
this.child.stdin.end();
|
|
98
|
-
const timer = setTimeout(() => this.child.kill(),
|
|
234
|
+
const timer = setTimeout(() => this.child.kill(), 3e3);
|
|
99
235
|
await this.exited;
|
|
100
236
|
clearTimeout(timer);
|
|
101
237
|
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
const git = (cwd, args) =>
|
|
105
|
-
new Promise((resolve) =>
|
|
106
|
-
execFile("git", ["-C", cwd, ...args], { maxBuffer: 64 * 1024 * 1024 }, (error, stdout) =>
|
|
107
|
-
resolve(error ? "" : stdout),
|
|
108
|
-
),
|
|
109
|
-
);
|
|
110
|
-
|
|
111
|
-
// Git in a repository with no program its own config names: no fsmonitor, and no filter its
|
|
112
|
-
// attributes would put a changed file's content through.
|
|
113
|
-
async function repositoryGit(repository, args) {
|
|
114
|
-
const drivers = new Set(
|
|
115
|
-
(await git(repository, ["config", "--name-only", "--get-regexp", "^filter\\."]))
|
|
116
|
-
.split("\n")
|
|
117
|
-
.flatMap((key) => /^filter\.(.+)\.[^.]+$/su.exec(key)?.[1] ?? []),
|
|
118
|
-
);
|
|
119
|
-
const blank = [...drivers].flatMap((driver) =>
|
|
120
|
-
["clean=", "process=", "required=false"].flatMap((setting) => [
|
|
121
|
-
"-c",
|
|
122
|
-
`filter.${driver}.${setting}`,
|
|
123
|
-
]),
|
|
124
|
-
);
|
|
125
|
-
return git(repository, [
|
|
126
|
-
"-c",
|
|
127
|
-
"core.fsmonitor=false",
|
|
128
|
-
"-c",
|
|
129
|
-
"core.quotePath=false",
|
|
130
|
-
...blank,
|
|
131
|
-
...args,
|
|
132
|
-
]);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// The Git repository around a path, or the nearest directory of it that exists; empty outside one.
|
|
136
|
-
async function repositoryAt(given) {
|
|
137
|
-
let directory = given;
|
|
138
|
-
while (!(await stat(directory).catch(() => undefined))?.isDirectory()) {
|
|
139
|
-
if (path.dirname(directory) === directory) return "";
|
|
140
|
-
directory = path.dirname(directory);
|
|
141
|
-
}
|
|
142
|
-
return (await git(directory, ["rev-parse", "--show-toplevel"])).trim();
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// The files a tool call names to change, relative to the session's directory.
|
|
238
|
+
};
|
|
146
239
|
function namedFiles({ toolName, input }) {
|
|
147
240
|
if (WRITES.has(toolName)) return typeof input?.path === "string" ? [input.path] : [];
|
|
148
241
|
if (toolName === PATCH && typeof input?.patch === "string")
|
|
149
242
|
return [...input.patch.matchAll(PATCH_FILES)].map((match) => match[1].trim());
|
|
150
243
|
return [];
|
|
151
244
|
}
|
|
152
|
-
|
|
153
|
-
// The repository LayerMap's server routes a tool call's path to: a relative path that stays in the
|
|
154
|
-
// repository the session started in is that one's, and any other is resolved from where it started.
|
|
155
|
-
function routedRepository(start, given) {
|
|
156
|
-
const normal = path.normalize(given || ".");
|
|
157
|
-
const escapes = normal === ".." || normal.startsWith(`..${path.sep}`);
|
|
158
|
-
if (start.git && !path.isAbsolute(normal) && !escapes) return Promise.resolve(start.directory);
|
|
159
|
-
return repositoryAt(path.resolve(start.directory, normal));
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// A repository's uncommitted code files, each with a hash of its content ("" once deleted); empty
|
|
163
|
-
// without a commit.
|
|
164
|
-
async function changedCode(repository) {
|
|
165
|
-
const changed = new Map();
|
|
166
|
-
if (!(await git(repository, ["rev-parse", "--verify", "--quiet", "HEAD"]))) return changed;
|
|
167
|
-
const listed = await Promise.all([
|
|
168
|
-
repositoryGit(repository, ["diff", "HEAD", "--name-only", "--no-renames", "--", ...CODE_GLOBS]),
|
|
169
|
-
repositoryGit(repository, ["ls-files", "--others", "--exclude-standard", "--", ...CODE_GLOBS]),
|
|
170
|
-
]);
|
|
171
|
-
const files = [...new Set(listed.join("\n").split("\n").filter(Boolean))].sort();
|
|
172
|
-
for (const file of files) {
|
|
173
|
-
const content = await readFile(path.join(repository, file)).catch(() => undefined);
|
|
174
|
-
changed.set(file, content ? createHash("sha256").update(content).digest("hex") : "");
|
|
175
|
-
}
|
|
176
|
-
return changed;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
// The changes as one hash, empty when there are none.
|
|
180
|
-
const fingerprint = (changed) =>
|
|
181
|
-
changed.size
|
|
182
|
-
? createHash("sha256")
|
|
183
|
-
.update(JSON.stringify([...changed]))
|
|
184
|
-
.digest("hex")
|
|
185
|
-
: "";
|
|
186
|
-
|
|
187
|
-
// How long a command runs (ms) before only the files it names count as its changes.
|
|
188
|
-
const LONG_COMMAND = 10_000;
|
|
189
|
-
|
|
190
|
-
// The folders a shell command names that exist, relative to the directory it runs in.
|
|
191
|
-
async function namedFolders(cwd, command) {
|
|
192
|
-
const folders = new Set();
|
|
193
|
-
for (const word of command.split(/[^A-Za-z0-9._/~:@+,%-]+/).slice(0, 300)) {
|
|
194
|
-
if (!word) continue;
|
|
195
|
-
const named = word.startsWith("~/")
|
|
196
|
-
? path.join(os.homedir(), word.slice(2))
|
|
197
|
-
: path.resolve(cwd, word);
|
|
198
|
-
for (const folder of [named, path.dirname(named)])
|
|
199
|
-
if ((await stat(folder).catch(() => undefined))?.isDirectory()) {
|
|
200
|
-
folders.add(folder);
|
|
201
|
-
break;
|
|
202
|
-
}
|
|
203
|
-
if (folders.size >= 20) break;
|
|
204
|
-
}
|
|
205
|
-
return folders;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
export default function layermap(pi) {
|
|
245
|
+
function layermap(pi) {
|
|
209
246
|
let server;
|
|
210
247
|
let starting;
|
|
211
248
|
let cwd;
|
|
212
|
-
const registered = new Set();
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
// edit, write or patch names, and those in which any other tool that can change files (bash, …)
|
|
218
|
-
// changed code files while it ran, among the repository the session started in, those of the
|
|
219
|
-
// folders its command names and those already edited.
|
|
220
|
-
// It compares a repository's uncommitted code changes with those it had before the session's
|
|
221
|
-
// first such tool there and those the agent last checked in it, and all of them with those it
|
|
222
|
-
// was last asked about; changes another session makes while this one reads do not count. A
|
|
223
|
-
// command that ran longer than ten seconds (tests, builds, scripts) leaves time for another
|
|
224
|
-
// session to change the same work tree, so only the files it names count; one that writes code
|
|
225
|
-
// without naming the file, such as a generator or formatter, takes a few seconds.
|
|
226
|
-
const edited = new Set();
|
|
227
|
-
const before = new Map();
|
|
228
|
-
const checked = new Map();
|
|
229
|
-
// The code changes of each repository a running tool may change, when it started and its
|
|
230
|
-
// command, by the tool call's id.
|
|
231
|
-
const running = new Map();
|
|
232
|
-
let askedAbout = "";
|
|
233
|
-
|
|
249
|
+
const registered = /* @__PURE__ */ new Set();
|
|
250
|
+
let start = "";
|
|
251
|
+
const changes = [];
|
|
252
|
+
const running = /* @__PURE__ */ new Map();
|
|
253
|
+
let asked = "";
|
|
234
254
|
const ensureServer = async () => {
|
|
235
255
|
if (server && !server.dead) return server;
|
|
236
256
|
starting ??= (async () => {
|
|
237
257
|
const next = new MapServer(cwd);
|
|
238
|
-
const tools = await next.start("0.1.
|
|
258
|
+
const tools = await next.start("0.1.27");
|
|
239
259
|
for (const tool of tools) {
|
|
240
260
|
if (registered.has(tool.name)) continue;
|
|
241
261
|
registered.add(tool.name);
|
|
@@ -244,129 +264,78 @@ export default function layermap(pi) {
|
|
|
244
264
|
label: tool.title ?? tool.name,
|
|
245
265
|
description: tool.description,
|
|
246
266
|
promptSnippet: tool.title,
|
|
247
|
-
promptGuidelines: tool.name === "project_explore_map" ? [
|
|
267
|
+
promptGuidelines: tool.name === "project_explore_map" ? [AGENT_MAP_NOTE] : [],
|
|
248
268
|
parameters: Type.Unsafe(tool.inputSchema),
|
|
249
269
|
async execute(_id, params, signal) {
|
|
250
|
-
const
|
|
251
|
-
const result = await
|
|
270
|
+
const running2 = await ensureServer();
|
|
271
|
+
const result = await running2.request(
|
|
252
272
|
"tools/call",
|
|
253
273
|
{ name: tool.name, arguments: params ?? {} },
|
|
254
|
-
signal
|
|
274
|
+
signal
|
|
255
275
|
);
|
|
256
276
|
const text = (result.content ?? []).map((part) => part.text ?? "").join("\n");
|
|
257
277
|
if (result.isError) throw new Error(text);
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
if (repository) checked.set(repository, fingerprint(await changedCode(repository)));
|
|
261
|
-
}
|
|
278
|
+
const repository = tool.name === CHECK_TOOL && checkedRepository(text);
|
|
279
|
+
if (repository) changes.push({ kind: "check", repository });
|
|
262
280
|
return { content: [{ type: "text", text }], details: {} };
|
|
263
|
-
}
|
|
281
|
+
}
|
|
264
282
|
});
|
|
265
283
|
}
|
|
266
284
|
server = next;
|
|
267
285
|
return next;
|
|
268
286
|
})().finally(() => {
|
|
269
|
-
starting =
|
|
287
|
+
starting = void 0;
|
|
270
288
|
});
|
|
271
289
|
return starting;
|
|
272
290
|
};
|
|
273
|
-
|
|
274
291
|
pi.on("session_start", async (_event, ctx) => {
|
|
275
292
|
cwd = ctx.cwd;
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
edited.clear();
|
|
279
|
-
before.clear();
|
|
280
|
-
checked.clear();
|
|
293
|
+
start = await repositoryAt(cwd);
|
|
294
|
+
changes.length = 0;
|
|
281
295
|
running.clear();
|
|
282
|
-
|
|
283
|
-
await ensureServer().catch(
|
|
284
|
-
ctx.ui?.notify?.(`LayerMap could not start: ${error.message}`, "warning")
|
|
296
|
+
asked = "";
|
|
297
|
+
await ensureServer().catch(
|
|
298
|
+
(error) => ctx.ui?.notify?.(`LayerMap could not start: ${error.message}`, "warning")
|
|
285
299
|
);
|
|
286
300
|
});
|
|
287
|
-
|
|
288
301
|
pi.on("tool_call", async (event) => {
|
|
289
302
|
if (READS.has(event.toolName) || registered.has(event.toolName) || !cwd) return;
|
|
290
|
-
const files = namedFiles(event);
|
|
291
|
-
if (files.length) {
|
|
292
|
-
const repositories = await Promise.all(
|
|
293
|
-
files.map((file) => repositoryAt(path.resolve(cwd, file))),
|
|
294
|
-
);
|
|
295
|
-
for (const repository of new Set(repositories)) {
|
|
296
|
-
if (!repository || edited.has(repository)) continue;
|
|
297
|
-
edited.add(repository);
|
|
298
|
-
before.set(repository, fingerprint(await changedCode(repository)));
|
|
299
|
-
}
|
|
300
|
-
return;
|
|
301
|
-
}
|
|
302
303
|
const command = event.input?.command;
|
|
303
|
-
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
...(await Promise.all([...folders].map(repositoryAt))),
|
|
307
|
-
...edited,
|
|
308
|
-
]);
|
|
309
|
-
const changes = new Map();
|
|
310
|
-
for (const repository of repositories)
|
|
311
|
-
if (repository) changes.set(repository, await changedCode(repository));
|
|
312
|
-
running.set(event.toolCallId, {
|
|
313
|
-
changes,
|
|
314
|
-
started: Date.now(),
|
|
315
|
-
command: typeof command === "string" ? command : "",
|
|
316
|
-
});
|
|
304
|
+
if (namedFiles(event).length || typeof command !== "string") return;
|
|
305
|
+
const files = await commandFiles(cwd, command);
|
|
306
|
+
if (files.length) running.set(event.toolCallId, await fileStates(files));
|
|
317
307
|
});
|
|
318
|
-
|
|
319
308
|
pi.on("tool_result", async (event) => {
|
|
320
|
-
|
|
321
|
-
|
|
309
|
+
if (!cwd) return;
|
|
310
|
+
const before = running.get(event.toolCallId);
|
|
322
311
|
running.delete(event.toolCallId);
|
|
323
|
-
const
|
|
324
|
-
|
|
325
|
-
if (edited.has(repository)) continue;
|
|
326
|
-
const now = await changedCode(repository);
|
|
327
|
-
if (
|
|
328
|
-
[...now].some(
|
|
329
|
-
([file, content]) =>
|
|
330
|
-
earlier.get(file) !== content && (!long || call.command.includes(path.basename(file))),
|
|
331
|
-
)
|
|
332
|
-
) {
|
|
333
|
-
edited.add(repository);
|
|
334
|
-
before.set(repository, fingerprint(earlier));
|
|
335
|
-
}
|
|
336
|
-
}
|
|
312
|
+
const files = before ? changedFiles(before, await fileStates(Object.keys(before))) : event.isError ? [] : namedFiles(event).map((file) => path2.resolve(cwd, file));
|
|
313
|
+
changes.push(...await codeEdits(files));
|
|
337
314
|
});
|
|
338
|
-
|
|
339
315
|
pi.on("agent_before_settle", async (event) => {
|
|
340
316
|
if (process.env.LAYERMAP_STOP_CHECK === "0") return;
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
if (changes && changes !== before.get(repository) && changes !== checked.get(repository))
|
|
345
|
-
due.push({ repository, changes });
|
|
346
|
-
}
|
|
347
|
-
const asked = JSON.stringify(due);
|
|
348
|
-
if (!due.length || asked === askedAbout) return;
|
|
349
|
-
askedAbout = asked;
|
|
350
|
-
const elsewhere = due.some(({ repository }) => !start.git || repository !== start.directory);
|
|
317
|
+
const request = await checkRequest(changes, start, asked);
|
|
318
|
+
if (!request) return;
|
|
319
|
+
asked = request.fingerprint;
|
|
351
320
|
return {
|
|
352
321
|
entries: [
|
|
353
322
|
...event.entries,
|
|
354
323
|
{
|
|
355
324
|
type: "custom_message",
|
|
356
325
|
customType: "layermap-check",
|
|
357
|
-
content:
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
display: false,
|
|
361
|
-
},
|
|
326
|
+
content: request.text,
|
|
327
|
+
display: false
|
|
328
|
+
}
|
|
362
329
|
],
|
|
363
|
-
continue: true
|
|
330
|
+
continue: true
|
|
364
331
|
};
|
|
365
332
|
});
|
|
366
|
-
|
|
367
333
|
pi.on("session_shutdown", async () => {
|
|
368
|
-
const
|
|
369
|
-
server =
|
|
370
|
-
await
|
|
334
|
+
const running2 = server;
|
|
335
|
+
server = void 0;
|
|
336
|
+
await running2?.stop();
|
|
371
337
|
});
|
|
372
338
|
}
|
|
339
|
+
export {
|
|
340
|
+
layermap as default
|
|
341
|
+
};
|