@anhlp/alp-daemon 0.0.0-beta.1 → 0.0.0-beta.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.
- package/dist/alpd.js +1867 -741
- package/dist/build-manifest.json +4 -1
- package/dist/files.d.ts +109 -0
- package/dist/files.js +331 -0
- package/dist/gitignore.d.ts +57 -0
- package/dist/gitignore.js +235 -0
- package/dist/main.js +1 -1
- package/dist/server.js +145 -13
- package/package.json +13 -5
- package/src/files.ts +420 -0
- package/src/gitignore.ts +260 -0
- package/src/server.ts +184 -15
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// packages/daemon/src/gitignore.ts
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { accessSync, constants, lstatSync, realpathSync, statSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
var GIT_CHECK = Object.freeze({
|
|
6
|
+
/** Git gets this long per request, waiting for a turn included, then is killed. */
|
|
7
|
+
timeoutMs: 2e3,
|
|
8
|
+
/** Git processes alpd runs at once, and requests that may wait for one. */
|
|
9
|
+
maxConcurrent: 4,
|
|
10
|
+
maxQueued: 64,
|
|
11
|
+
maxErrorBytes: 64 * 1024
|
|
12
|
+
});
|
|
13
|
+
var IgnoreUnknown = class extends Error {
|
|
14
|
+
constructor(why) {
|
|
15
|
+
super(`git check-ignore failed: ${why}`);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
function gitEnvironment() {
|
|
19
|
+
const env = {};
|
|
20
|
+
for (const [key, value] of Object.entries(process.env)) if (!/^GIT_/i.test(key)) env[key] = value;
|
|
21
|
+
return { ...env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" };
|
|
22
|
+
}
|
|
23
|
+
var executable = (file) => {
|
|
24
|
+
try {
|
|
25
|
+
if (!statSync(file).isFile()) return false;
|
|
26
|
+
if (process.platform !== "win32") accessSync(file, constants.X_OK);
|
|
27
|
+
return true;
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
var identity = (file) => {
|
|
33
|
+
const { dev, ino } = statSync(file, { bigint: true });
|
|
34
|
+
return { dev, ino };
|
|
35
|
+
};
|
|
36
|
+
var foldCase = process.platform === "darwin" || process.platform === "win32";
|
|
37
|
+
var comparable = (file) => foldCase ? file.toLowerCase() : file;
|
|
38
|
+
function insideRoot(file, root) {
|
|
39
|
+
let directory;
|
|
40
|
+
try {
|
|
41
|
+
directory = realpathSync.native(file);
|
|
42
|
+
} catch {
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
const rootName = comparable(root.path.endsWith(path.sep) && root.path.length > 1 ? root.path.slice(0, -1) : root.path);
|
|
46
|
+
for (; ; ) {
|
|
47
|
+
const name = comparable(directory);
|
|
48
|
+
if (name === rootName || name.startsWith(rootName.endsWith(path.sep) ? rootName : `${rootName}${path.sep}`)) return true;
|
|
49
|
+
let id;
|
|
50
|
+
try {
|
|
51
|
+
id = identity(directory);
|
|
52
|
+
} catch {
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
if (root.id.ino !== 0n && id.dev === root.id.dev && id.ino === root.id.ino) return true;
|
|
56
|
+
const parent = path.dirname(directory);
|
|
57
|
+
if (parent === directory) return false;
|
|
58
|
+
directory = parent;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function rootOf(root) {
|
|
62
|
+
try {
|
|
63
|
+
const real = realpathSync.native(root);
|
|
64
|
+
return { path: real, id: identity(real) };
|
|
65
|
+
} catch {
|
|
66
|
+
return void 0;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function resolveGit(name = "git", searchPath = process.env.PATH ?? process.env.Path ?? "", root) {
|
|
70
|
+
const box = root === void 0 ? void 0 : rootOf(root);
|
|
71
|
+
if (root !== void 0 && !box) throw new IgnoreUnknown("the workspace cannot be examined");
|
|
72
|
+
const accept = (file) => {
|
|
73
|
+
if (!executable(file)) return void 0;
|
|
74
|
+
if (!box) return file;
|
|
75
|
+
let real;
|
|
76
|
+
try {
|
|
77
|
+
real = realpathSync.native(file);
|
|
78
|
+
} catch {
|
|
79
|
+
return void 0;
|
|
80
|
+
}
|
|
81
|
+
return insideRoot(path.dirname(real), box) || !executable(real) ? void 0 : real;
|
|
82
|
+
};
|
|
83
|
+
if (path.isAbsolute(name)) return accept(name);
|
|
84
|
+
if (name.includes("/") || name.includes("\\")) return void 0;
|
|
85
|
+
const names = process.platform === "win32" ? [`${name}.exe`, `${name}.com`] : [name];
|
|
86
|
+
for (const directory of searchPath.split(path.delimiter)) {
|
|
87
|
+
if (!directory || !path.isAbsolute(directory)) continue;
|
|
88
|
+
if (box && insideRoot(directory, box)) continue;
|
|
89
|
+
for (const candidate of names) {
|
|
90
|
+
const file = accept(path.join(directory, candidate));
|
|
91
|
+
if (file) return file;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return void 0;
|
|
95
|
+
}
|
|
96
|
+
function hasGitEntry(root) {
|
|
97
|
+
for (let directory = root; ; directory = path.dirname(directory)) {
|
|
98
|
+
try {
|
|
99
|
+
lstatSync(path.join(directory, ".git"));
|
|
100
|
+
return true;
|
|
101
|
+
} catch {
|
|
102
|
+
}
|
|
103
|
+
if (path.dirname(directory) === directory) return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
var running = 0;
|
|
107
|
+
var waiting = [];
|
|
108
|
+
function acquire(deadline) {
|
|
109
|
+
const release = () => {
|
|
110
|
+
running--;
|
|
111
|
+
waiting.shift()?.();
|
|
112
|
+
};
|
|
113
|
+
if (running < GIT_CHECK.maxConcurrent) {
|
|
114
|
+
running++;
|
|
115
|
+
return Promise.resolve(release);
|
|
116
|
+
}
|
|
117
|
+
if (waiting.length >= GIT_CHECK.maxQueued) return Promise.reject(new IgnoreUnknown("too many waiting"));
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
const turn = () => {
|
|
120
|
+
clearTimeout(timer);
|
|
121
|
+
running++;
|
|
122
|
+
resolve(release);
|
|
123
|
+
};
|
|
124
|
+
const timer = setTimeout(() => {
|
|
125
|
+
const index = waiting.indexOf(turn);
|
|
126
|
+
if (index >= 0) waiting.splice(index, 1);
|
|
127
|
+
reject(new IgnoreUnknown("timed out waiting for a turn"));
|
|
128
|
+
}, Math.max(0, deadline - Date.now()));
|
|
129
|
+
waiting.push(turn);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
var gitChecksRunning = () => running;
|
|
133
|
+
async function gitIgnored(root, paths, { binary = "git", timeoutMs = GIT_CHECK.timeoutMs } = {}) {
|
|
134
|
+
if (!paths.length) return /* @__PURE__ */ new Set();
|
|
135
|
+
const git = resolveGit(binary, void 0, root);
|
|
136
|
+
if (!git) return null;
|
|
137
|
+
const deadline = Date.now() + timeoutMs;
|
|
138
|
+
const release = await acquire(deadline);
|
|
139
|
+
try {
|
|
140
|
+
return await check(git, root, paths, deadline, timeoutMs);
|
|
141
|
+
} finally {
|
|
142
|
+
release();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function check(git, root, paths, deadline, timeoutMs) {
|
|
146
|
+
const input = `${paths.map((entry) => `./${entry}`).join("\0")}\0`;
|
|
147
|
+
const maxOutputBytes = Buffer.byteLength(input) + 1024;
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
let settled = false;
|
|
150
|
+
let timer;
|
|
151
|
+
let child;
|
|
152
|
+
const group = process.platform !== "win32";
|
|
153
|
+
const kill = () => {
|
|
154
|
+
try {
|
|
155
|
+
if (group && child.pid) process.kill(-child.pid, "SIGKILL");
|
|
156
|
+
else child.kill("SIGKILL");
|
|
157
|
+
} catch {
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
const finish = (outcome) => {
|
|
161
|
+
if (settled) return;
|
|
162
|
+
settled = true;
|
|
163
|
+
if (timer) clearTimeout(timer);
|
|
164
|
+
outcome();
|
|
165
|
+
};
|
|
166
|
+
try {
|
|
167
|
+
child = spawn(git, ["-c", "core.fsmonitor=false", "check-ignore", "--no-index", "--stdin", "-z"], {
|
|
168
|
+
cwd: root,
|
|
169
|
+
env: gitEnvironment(),
|
|
170
|
+
shell: false,
|
|
171
|
+
windowsHide: true,
|
|
172
|
+
detached: group,
|
|
173
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
174
|
+
});
|
|
175
|
+
} catch (error) {
|
|
176
|
+
reject(new IgnoreUnknown(String(error.message)));
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
timer = setTimeout(() => finish(() => {
|
|
180
|
+
kill();
|
|
181
|
+
reject(new IgnoreUnknown("timed out"));
|
|
182
|
+
}), Math.max(1, Math.min(timeoutMs, deadline - Date.now())));
|
|
183
|
+
const out = [];
|
|
184
|
+
let outBytes = 0;
|
|
185
|
+
let err = "";
|
|
186
|
+
child.stdout.on("data", (chunk) => {
|
|
187
|
+
outBytes += chunk.length;
|
|
188
|
+
if (outBytes > maxOutputBytes) finish(() => {
|
|
189
|
+
kill();
|
|
190
|
+
reject(new IgnoreUnknown("more output than input"));
|
|
191
|
+
});
|
|
192
|
+
else out.push(chunk);
|
|
193
|
+
});
|
|
194
|
+
child.stderr.on("data", (chunk) => {
|
|
195
|
+
if (err.length < GIT_CHECK.maxErrorBytes) err += chunk.toString("utf8");
|
|
196
|
+
});
|
|
197
|
+
child.on("error", (error) => finish(() => {
|
|
198
|
+
if (error.code === "ENOENT") resolve(null);
|
|
199
|
+
else reject(new IgnoreUnknown(error.message));
|
|
200
|
+
}));
|
|
201
|
+
child.on("close", (code) => finish(() => {
|
|
202
|
+
if (code === 128 && /not a git repository/i.test(err)) {
|
|
203
|
+
if (hasGitEntry(root)) reject(new IgnoreUnknown("a .git Git cannot use"));
|
|
204
|
+
else resolve(null);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (code !== 0 && code !== 1) {
|
|
208
|
+
reject(new IgnoreUnknown(`exit ${code}`));
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const asked = new Set(paths);
|
|
212
|
+
const ignored = /* @__PURE__ */ new Set();
|
|
213
|
+
for (const entry of Buffer.concat(out).toString("utf8").split("\0")) {
|
|
214
|
+
if (!entry) continue;
|
|
215
|
+
const relative = entry.startsWith("./") ? entry.slice(2) : void 0;
|
|
216
|
+
if (relative === void 0 || !asked.has(relative)) {
|
|
217
|
+
reject(new IgnoreUnknown("an answer for a path not asked"));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
ignored.add(relative);
|
|
221
|
+
}
|
|
222
|
+
resolve(ignored);
|
|
223
|
+
}));
|
|
224
|
+
child.stdin.on("error", () => {
|
|
225
|
+
});
|
|
226
|
+
child.stdin.end(input);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
export {
|
|
230
|
+
GIT_CHECK,
|
|
231
|
+
IgnoreUnknown,
|
|
232
|
+
gitChecksRunning,
|
|
233
|
+
gitIgnored,
|
|
234
|
+
resolveGit
|
|
235
|
+
};
|
package/dist/main.js
CHANGED
|
@@ -18,7 +18,7 @@ import { validateUserSettings } from "@anhlp/alp-core/validation";
|
|
|
18
18
|
import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } from "@anhlp/alp-core/backup";
|
|
19
19
|
import { migrateState } from "@anhlp/alp-core/migrations";
|
|
20
20
|
import { createLogger } from "@anhlp/alp-core/log";
|
|
21
|
-
var VERSION = true ? "0.0.0-beta.
|
|
21
|
+
var VERSION = true ? "0.0.0-beta.2" : "0.0.0-dev";
|
|
22
22
|
var LOG_BYTES = 10 * 1024 * 1024;
|
|
23
23
|
var LOG_FILES = 3;
|
|
24
24
|
var log = createLogger({ component: "alpd" });
|
package/dist/server.js
CHANGED
|
@@ -2,15 +2,17 @@
|
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
3
|
import { appendFile, chmod, mkdir, readFile, unlink, lstat, rename } from "node:fs/promises";
|
|
4
4
|
import net from "node:net";
|
|
5
|
+
import os from "node:os";
|
|
5
6
|
import { assertPrivateDirectory, assertPrivateSocket } from "@anhlp/alp-client/index";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
import { createLogger } from "@anhlp/alp-core/log";
|
|
8
|
-
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, encodeFrame } from "@anhlp/alp-protocol";
|
|
9
|
+
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from "@anhlp/alp-protocol";
|
|
9
10
|
import { validateParams } from "@anhlp/alp-protocol/contract";
|
|
10
11
|
import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
|
|
11
12
|
import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
|
|
12
13
|
import { RpcError } from "./rpc-error.js";
|
|
13
14
|
import { createOperations } from "./operations.js";
|
|
15
|
+
import { FileAccessError, FilesError, listWorkspaceDirectory, readWorkspaceFile, searchWorkspaceFiles } from "./files.js";
|
|
14
16
|
var log = createLogger({ component: "alpd.ipc" });
|
|
15
17
|
var recoveryLog = createLogger({ component: "alpd.recovery" });
|
|
16
18
|
function validId(id) {
|
|
@@ -36,6 +38,29 @@ var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
|
36
38
|
var RECEIPT_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
37
39
|
var RETENTION_SWEEP_MS = 6 * 60 * 60 * 1e3;
|
|
38
40
|
var LIVE = ["initializing", "idle", "running"];
|
|
41
|
+
var PROMPT_TITLE_CHARS = 60;
|
|
42
|
+
function titleFromPrompt(text) {
|
|
43
|
+
const line = text.split(/\r?\n/).map((entry) => entry.replace(/\s+/g, " ").trim()).find(Boolean);
|
|
44
|
+
return line ? [...line].slice(0, PROMPT_TITLE_CHARS).join("").trim() || void 0 : void 0;
|
|
45
|
+
}
|
|
46
|
+
var listCursor = {
|
|
47
|
+
key: (session) => [session.parentId ? 1 : 0, session.updatedAt ?? "", session.id],
|
|
48
|
+
compare([childA, updatedA, idA], [childB, updatedB, idB]) {
|
|
49
|
+
return childA - childB || (updatedA === updatedB ? 0 : updatedA < updatedB ? 1 : -1) || (idA === idB ? 0 : idA < idB ? -1 : 1);
|
|
50
|
+
},
|
|
51
|
+
encode: (key) => Buffer.from(JSON.stringify(key), "utf8").toString("base64url"),
|
|
52
|
+
decode(cursor) {
|
|
53
|
+
let key;
|
|
54
|
+
try {
|
|
55
|
+
key = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
56
|
+
} catch {
|
|
57
|
+
}
|
|
58
|
+
if (!Array.isArray(key) || key.length !== 3 || key[0] !== 0 && key[0] !== 1 || typeof key[1] !== "string" || typeof key[2] !== "string") {
|
|
59
|
+
throw new RpcError(RPC_ERROR.invalidParams, "cursor is not one session.list answered", { reason: "invalid_params" });
|
|
60
|
+
}
|
|
61
|
+
return key;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
39
64
|
function createDaemonServer({ runtime, socketPath, version, onShutdown, store, runLogDir, previousExit, retentionSweepMs = RETENTION_SWEEP_MS, home, templates }) {
|
|
40
65
|
const connections = /* @__PURE__ */ new Set();
|
|
41
66
|
const rootOf = /* @__PURE__ */ new Map();
|
|
@@ -51,6 +76,21 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
51
76
|
const startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
52
77
|
const restored = store ? restore() : Promise.resolve();
|
|
53
78
|
const deliver = (connection, envelope) => connection.send({ jsonrpc: "2.0", method: "event", params: envelope });
|
|
79
|
+
const watchers = /* @__PURE__ */ new Map();
|
|
80
|
+
function projectOf(root) {
|
|
81
|
+
return runtime.snapshot(root)?.projectRoot ?? records.get(root)?.session?.projectRoot;
|
|
82
|
+
}
|
|
83
|
+
function tellWatchers(root, envelope, turn = false) {
|
|
84
|
+
if (!watchers.size) return;
|
|
85
|
+
const { cursor: _cursor, ...announced } = envelope;
|
|
86
|
+
const project = projectOf(root);
|
|
87
|
+
for (const [connection, { projectRoot, turns }] of watchers) {
|
|
88
|
+
if (turn && !turns) continue;
|
|
89
|
+
if (attached.get(root)?.has(connection)) continue;
|
|
90
|
+
if (projectRoot !== void 0 && project !== projectRoot) continue;
|
|
91
|
+
deliver(connection, announced);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
54
94
|
function save(record, changes = {}) {
|
|
55
95
|
Object.assign(record, changes, { updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
|
|
56
96
|
records.set(record.id, record);
|
|
@@ -74,18 +114,35 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
74
114
|
let record = records.get(sessionId);
|
|
75
115
|
if (event.type === "session.opened") {
|
|
76
116
|
record ??= { version: 1, id: sessionId, rootId: root, status: "initializing", createdAt: now, updatedAt: now };
|
|
77
|
-
|
|
78
|
-
|
|
117
|
+
const usage = event.session.usage ?? record.session?.usage;
|
|
118
|
+
save(record, { rootId: root, session: { ...event.session, ...usage ? { usage } : {} }, status: "idle", lastError: void 0, activeTurnId: void 0 });
|
|
119
|
+
return false;
|
|
79
120
|
}
|
|
80
|
-
if (!record) return;
|
|
121
|
+
if (!record) return false;
|
|
81
122
|
if (event.type === "session.updated") save(record, { session: { ...record.session, ...event.session, ...event.session.parked ? {} : { parked: void 0 } } });
|
|
82
123
|
else if (event.type === "turn.started") save(record, { status: "running", activeTurnId: event.turnId, archived: void 0 });
|
|
83
124
|
else if (event.type === "turn.ended") save(record, { status: "idle", activeTurnId: void 0, ...event.state === "failed" ? { lastError: { message: event.error?.message ?? "Turn failed" } } : {} });
|
|
125
|
+
else if (event.type === "usage" && record.session) record.session = { ...record.session, usage: event.usage };
|
|
84
126
|
else if (event.type === "session.failed") save(record, { status: "error", lastError: event.error });
|
|
85
127
|
else if (event.type === "session.closed") save(record, { status: record.status === "error" ? "error" : "closed", activeTurnId: void 0 });
|
|
86
128
|
else if (event.type === "item" && sessionId === root && !record.title && event.item.kind === "user_message" && !event.item.clientMessageId?.startsWith("alp-")) {
|
|
87
|
-
|
|
129
|
+
const title = titleFromPrompt(event.item.text);
|
|
130
|
+
if (title) {
|
|
131
|
+
save(record, { title });
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
88
134
|
}
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
function announceTitle(root, title) {
|
|
138
|
+
const session = runtime.snapshot(root);
|
|
139
|
+
if (!session || rootOf.get(root) !== root) return;
|
|
140
|
+
const envelope = keep(root, { sessionId: root, epoch: `title-${startedAt}`, seq: 0, ts: (/* @__PURE__ */ new Date()).toISOString(), event: { type: "session.updated", session: { ...session, title } } });
|
|
141
|
+
const log2 = logs.get(root) ?? [];
|
|
142
|
+
log2.push(envelope);
|
|
143
|
+
if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
|
|
144
|
+
logs.set(root, log2);
|
|
145
|
+
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
89
146
|
}
|
|
90
147
|
runtime.onEvent((original) => {
|
|
91
148
|
if (closing) return;
|
|
@@ -96,15 +153,19 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
96
153
|
rootOf.set(sessionId, parent ? rootOf.get(parent) ?? parent : sessionId);
|
|
97
154
|
}
|
|
98
155
|
const root = rootOf.get(sessionId) ?? sessionId;
|
|
156
|
+
let named = false;
|
|
99
157
|
if (rootOf.has(sessionId)) {
|
|
100
158
|
envelope = keep(root, envelope);
|
|
101
159
|
const log2 = logs.get(root) ?? [];
|
|
102
160
|
log2.push(envelope);
|
|
103
161
|
if (log2.length > TREE_LOG_LIMIT) log2.splice(0, log2.length - TREE_LOG_LIMIT);
|
|
104
162
|
logs.set(root, log2);
|
|
105
|
-
track(sessionId, root, event);
|
|
163
|
+
named = track(sessionId, root, event);
|
|
106
164
|
}
|
|
107
165
|
for (const connection of attached.get(root) ?? []) deliver(connection, envelope);
|
|
166
|
+
if (event.type === "question" || event.type === "question.resolved") tellWatchers(root, envelope);
|
|
167
|
+
else if (event.type === "turn.ended" && sessionId === root) tellWatchers(root, envelope, true);
|
|
168
|
+
if (named) announceTitle(root, records.get(root).title);
|
|
108
169
|
if (event.type === "session.closed" && sessionId === root) {
|
|
109
170
|
setImmediate(() => forget(root));
|
|
110
171
|
} else {
|
|
@@ -483,8 +544,43 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
483
544
|
return { rootId: root, entries };
|
|
484
545
|
},
|
|
485
546
|
"question.list"(_connection, { projectRoot } = {}) {
|
|
486
|
-
|
|
487
|
-
|
|
547
|
+
return { questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot) };
|
|
548
|
+
},
|
|
549
|
+
/**
|
|
550
|
+
* The questions waiting now; from then on this connection is told of `question` and
|
|
551
|
+
* `question.resolved` in every tree, or those of `projectRoot`, attached or not. Calling it
|
|
552
|
+
* again replaces the filter; it lasts as long as the connection (ALPD §15). With `turns`, also
|
|
553
|
+
* of `turn.ended` of every root (docs/protocol/alp-json-rpc-v1.md §12.2).
|
|
554
|
+
*/
|
|
555
|
+
"question.watch"(connection, { projectRoot, turns } = {}) {
|
|
556
|
+
watchers.set(connection, { projectRoot, turns: turns === true });
|
|
557
|
+
return { questions: runtime.questions().filter((question) => projectRoot === void 0 || projectOf(question.rootId) === projectRoot) };
|
|
558
|
+
},
|
|
559
|
+
/**
|
|
560
|
+
* The files of a directory whose path matches a query, read-only and confined to it: no link
|
|
561
|
+
* is followed, only names are read (docs/protocol/alp-json-rpc-v1.md §12.3, ALPD §15).
|
|
562
|
+
*/
|
|
563
|
+
async "workspace.files.search"(_connection, { projectRoot, query, limit } = {}) {
|
|
564
|
+
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot) || path.resolve(projectRoot) !== projectRoot) {
|
|
565
|
+
throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute, normalized path", { reason: "invalid_path" });
|
|
566
|
+
}
|
|
567
|
+
try {
|
|
568
|
+
return await searchWorkspaceFiles(projectRoot, { query, limit });
|
|
569
|
+
} catch (error) {
|
|
570
|
+
if (error instanceof FilesError) throw new RpcError(ERROR.notFound, error.message, { reason: "not_directory" });
|
|
571
|
+
throw error;
|
|
572
|
+
}
|
|
573
|
+
},
|
|
574
|
+
/**
|
|
575
|
+
* The entries of a directory under projectRoot, and the content of a text file there:
|
|
576
|
+
* read-only, confined to it, no link followed, blocked paths always refused, .gitignore'd ones
|
|
577
|
+
* unless includeIgnored (docs/protocol/alp-json-rpc-v1.md §12.4, ALPD §15).
|
|
578
|
+
*/
|
|
579
|
+
async "workspace.files.list"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
580
|
+
return filesCall(projectRoot, () => listWorkspaceDirectory(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
581
|
+
},
|
|
582
|
+
async "workspace.files.read"(_connection, { projectRoot, path: relative, includeIgnored } = {}) {
|
|
583
|
+
return filesCall(projectRoot, () => readWorkspaceFile(projectRoot, { path: relative, includeIgnored: includeIgnored === true }));
|
|
488
584
|
},
|
|
489
585
|
/** The project board: live claims, decisions and findings (ALPD §18). */
|
|
490
586
|
async "board.list"(_connection, { projectRoot } = {}) {
|
|
@@ -621,6 +717,15 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
621
717
|
async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content }) {
|
|
622
718
|
if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
|
|
623
719
|
if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
|
|
720
|
+
const images = content.filter((part) => part?.type === "image");
|
|
721
|
+
if (images.length > PROMPT_IMAGES.maxCount) throw new RpcError(-32602, `A prompt takes at most ${PROMPT_IMAGES.maxCount} images`);
|
|
722
|
+
let total = 0;
|
|
723
|
+
for (const image of images) {
|
|
724
|
+
const bytes = base64Bytes(image.data);
|
|
725
|
+
total += bytes;
|
|
726
|
+
if (bytes > PROMPT_IMAGES.maxBytes) throw new RpcError(-32602, `An image in a prompt is at most ${PROMPT_IMAGES.maxBytes} bytes`);
|
|
727
|
+
if (total > PROMPT_IMAGES.maxTotalBytes) throw new RpcError(-32602, `The images of a prompt are at most ${PROMPT_IMAGES.maxTotalBytes} bytes together`);
|
|
728
|
+
}
|
|
624
729
|
const send = async () => {
|
|
625
730
|
live(sessionId);
|
|
626
731
|
await runtime.prompt(sessionId, { clientMessageId, delivery, content });
|
|
@@ -654,6 +759,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
654
759
|
record.title = before;
|
|
655
760
|
throw persistenceFailed(`the name of ${record.id}`, error);
|
|
656
761
|
}
|
|
762
|
+
announceTitle(record.id, record.title);
|
|
657
763
|
return { session: summary(record.id) };
|
|
658
764
|
},
|
|
659
765
|
/** Sets a root aside: it closes, with its tree, and leaves the lists until unarchived (ALPD §61). */
|
|
@@ -673,10 +779,22 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
673
779
|
"session.get"(_connection, { sessionId }) {
|
|
674
780
|
return { session: known(sessionId) };
|
|
675
781
|
},
|
|
676
|
-
|
|
782
|
+
/**
|
|
783
|
+
* Roots first, then newest first, by id last. With `limit` a page, and `nextCursor` while more
|
|
784
|
+
* follow; `cursor` continues after the session it names; `query` keeps the sessions whose title
|
|
785
|
+
* or id holds every word of it; `projectRoots` those of any of these projects, as a gateway lists
|
|
786
|
+
* a grant's workspaces (docs/protocol/alp-json-rpc-v1.md §12.1).
|
|
787
|
+
*/
|
|
788
|
+
"session.list"(_connection, { projectRoot, projectRoots, rootsOnly = false, includeClosed = false, includeArchived = false, limit, cursor, query } = {}) {
|
|
789
|
+
const projects = Array.isArray(projectRoots) ? new Set(projectRoots) : void 0;
|
|
790
|
+
const after = cursor === void 0 ? void 0 : listCursor.decode(cursor);
|
|
791
|
+
const words = typeof query === "string" ? query.toLowerCase().split(/\s+/).filter(Boolean) : [];
|
|
677
792
|
const ids = /* @__PURE__ */ new Set([...runtime.list().map((session) => session.id), ...records.keys()]);
|
|
678
|
-
const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => projectRoot === void 0 || session.projectRoot === projectRoot).
|
|
679
|
-
|
|
793
|
+
const sessions = [...ids].map(summary).filter((session) => !!session).filter((session) => includeClosed || session.status === "idle" || session.status === "running").filter((session) => includeArchived || !session.archived).filter((session) => !rootsOnly || !session.parentId).filter((session) => projectRoot === void 0 || session.projectRoot === projectRoot).filter((session) => !projects || projects.has(session.projectRoot)).filter((session) => !words.length || words.every((word) => `${session.title ?? ""}
|
|
794
|
+
${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(listCursor.key(a), listCursor.key(b))).filter((session) => !after || listCursor.compare(listCursor.key(session), after) > 0);
|
|
795
|
+
if (limit === void 0 || sessions.length <= limit) return { sessions };
|
|
796
|
+
const page = sessions.slice(0, limit);
|
|
797
|
+
return { sessions: page, nextCursor: listCursor.encode(listCursor.key(page.at(-1))) };
|
|
680
798
|
}
|
|
681
799
|
};
|
|
682
800
|
for (const [method, handler] of Object.entries(operations.handlers)) handlers[method] = (_connection, params) => handler(params);
|
|
@@ -713,7 +831,20 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
713
831
|
}
|
|
714
832
|
return { live: true, ready: checks.every((check) => check.ok), checks };
|
|
715
833
|
}
|
|
716
|
-
|
|
834
|
+
async function filesCall(projectRoot, read) {
|
|
835
|
+
if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot) || path.resolve(projectRoot) !== projectRoot) {
|
|
836
|
+
throw new RpcError(RPC_ERROR.invalidParams, "projectRoot must be an absolute, normalized path", { reason: "invalid_path" });
|
|
837
|
+
}
|
|
838
|
+
try {
|
|
839
|
+
return await read();
|
|
840
|
+
} catch (error) {
|
|
841
|
+
if (error instanceof FileAccessError) throw new RpcError(error.code, error.message, { reason: error.reason });
|
|
842
|
+
if (error instanceof FilesError) throw new RpcError(ERROR.notFound, error.message, { reason: "not_directory" });
|
|
843
|
+
log.error("workspace file read failed", { code: "ALPD_FILES_FAILED", error });
|
|
844
|
+
throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
const capabilities = [CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts] : [], ...operations.capabilities];
|
|
717
848
|
function fits(response) {
|
|
718
849
|
if (frameBytes(response) <= MAX_FRAME) return response;
|
|
719
850
|
log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
|
|
@@ -756,7 +887,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
756
887
|
const issues2 = validateParams(method, params);
|
|
757
888
|
if (issues2.length) throw invalidParams(issues2);
|
|
758
889
|
connection.helloed = true;
|
|
759
|
-
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, capabilities } });
|
|
890
|
+
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities } });
|
|
760
891
|
return;
|
|
761
892
|
}
|
|
762
893
|
if (!connection.helloed) throw new RpcError(ERROR.protocol, "daemon.hello is required first", { reason: "hello_required" });
|
|
@@ -795,6 +926,7 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
795
926
|
waiting.reject(new Error("ALP daemon caller connection closed"));
|
|
796
927
|
}
|
|
797
928
|
connections.delete(connection);
|
|
929
|
+
watchers.delete(connection);
|
|
798
930
|
for (const root of [...connection.roots]) {
|
|
799
931
|
detach(connection, root);
|
|
800
932
|
void reap(root);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-daemon",
|
|
3
|
-
"version": "0.0.0-beta.
|
|
3
|
+
"version": "0.0.0-beta.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP daemon module",
|
|
6
6
|
"files": [
|
|
@@ -25,6 +25,14 @@
|
|
|
25
25
|
"types": "./dist/index.d.ts",
|
|
26
26
|
"default": "./dist/index.js"
|
|
27
27
|
},
|
|
28
|
+
"./files": {
|
|
29
|
+
"alp-source": {
|
|
30
|
+
"types": "./src/files.ts",
|
|
31
|
+
"default": "./src/files.ts"
|
|
32
|
+
},
|
|
33
|
+
"types": "./dist/files.d.ts",
|
|
34
|
+
"default": "./dist/files.js"
|
|
35
|
+
},
|
|
28
36
|
"./lock": {
|
|
29
37
|
"alp-source": {
|
|
30
38
|
"types": "./src/lock.ts",
|
|
@@ -62,10 +70,10 @@
|
|
|
62
70
|
"node": ">=22.12"
|
|
63
71
|
},
|
|
64
72
|
"dependencies": {
|
|
65
|
-
"@anhlp/alp-core": "0.0.0-beta.
|
|
66
|
-
"@anhlp/alp-runtime": "0.0.0-beta.
|
|
67
|
-
"@anhlp/alp-client": "0.0.0-beta.
|
|
68
|
-
"@anhlp/alp-protocol": "0.0.0-beta.
|
|
73
|
+
"@anhlp/alp-core": "0.0.0-beta.2",
|
|
74
|
+
"@anhlp/alp-runtime": "0.0.0-beta.2",
|
|
75
|
+
"@anhlp/alp-client": "0.0.0-beta.2",
|
|
76
|
+
"@anhlp/alp-protocol": "0.0.0-beta.2",
|
|
69
77
|
"@anthropic-ai/sdk": "^0.131.0",
|
|
70
78
|
"ws": "^8.22.0",
|
|
71
79
|
"zod": "4.4.3",
|