@anhlp/alp-daemon 0.0.1-beta.6 → 0.0.1-beta.8
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/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/alpd.js +10508 -4233
- package/dist/build-manifest.json +8 -2
- package/dist/git.d.ts +6 -1
- package/dist/git.js +86 -32
- package/dist/main.js +51 -10
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +44 -0
- package/dist/native-terminal.js +2 -3
- package/dist/operations.d.ts +8 -1
- package/dist/operations.js +32 -5
- package/dist/scheduler.js +2 -0
- package/dist/server.js +61 -11
- package/dist/terminals.d.ts +12 -2
- package/dist/terminals.js +3 -3
- package/dist/windows-terminal.d.ts +6 -3
- package/dist/windows-terminal.js +30 -73
- package/package.json +6 -6
- package/src/git.ts +102 -22
- package/src/main.ts +56 -7
- package/src/model-catalog.ts +36 -0
- package/src/native-terminal.ts +2 -5
- package/src/operations.ts +18 -5
- package/src/scheduler.ts +6 -0
- package/src/server.ts +66 -12
- package/src/terminals.ts +18 -6
- package/src/windows-terminal.ts +33 -82
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// packages/daemon/src/model-catalog.ts
|
|
2
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { loadProvider, listProviders } from "@anhlp/alp-core/providers";
|
|
6
|
+
import { probeAcp } from "@anhlp/alp-client/acp-probe";
|
|
7
|
+
import { antigravityProbe, liveProbes, ModelCatalog } from "@anhlp/alp-runtime/index";
|
|
8
|
+
function createModelCatalog(home, warn = console.error) {
|
|
9
|
+
let warnings = /* @__PURE__ */ new Set();
|
|
10
|
+
const probes = liveProbes();
|
|
11
|
+
probes.antigravity = async (signal) => {
|
|
12
|
+
const provider = await loadProvider(home, "antigravity");
|
|
13
|
+
if (provider?.enabled === false) return [];
|
|
14
|
+
return antigravityProbe(provider?.command, { ...process.env, ...provider?.env }, provider?.args)(signal);
|
|
15
|
+
};
|
|
16
|
+
return new ModelCatalog({
|
|
17
|
+
home,
|
|
18
|
+
probes,
|
|
19
|
+
acpProviders: async () => {
|
|
20
|
+
const errors = [];
|
|
21
|
+
const current = /* @__PURE__ */ new Set();
|
|
22
|
+
const providers = await listProviders(home, { onError: (error, name) => {
|
|
23
|
+
const message = `skipping provider ${name}: ${error instanceof Error ? error.message : String(error)}`;
|
|
24
|
+
errors.push(message);
|
|
25
|
+
current.add(message);
|
|
26
|
+
if (!warnings.has(message)) warn(`alpd: ${message}`);
|
|
27
|
+
} });
|
|
28
|
+
warnings = current;
|
|
29
|
+
return { providers, ...errors.length ? { error: errors.join("\n") } : {} };
|
|
30
|
+
},
|
|
31
|
+
acpProbe: async (provider, signal) => {
|
|
32
|
+
signal.throwIfAborted();
|
|
33
|
+
const cwd = await mkdtemp(path.join(os.tmpdir(), "alp-model-probe-"));
|
|
34
|
+
try {
|
|
35
|
+
return (await probeAcp(provider, { cwd, signal, discover: true, timeoutMs: 15e3 })).models ?? [];
|
|
36
|
+
} finally {
|
|
37
|
+
await rm(cwd, { recursive: true, force: true });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
export {
|
|
43
|
+
createModelCatalog
|
|
44
|
+
};
|
package/dist/native-terminal.js
CHANGED
|
@@ -9,9 +9,8 @@ var sha = (value) => createHash("sha256").update(value).digest("hex");
|
|
|
9
9
|
function binary() {
|
|
10
10
|
const libc = process.platform === "linux" ? process.report?.getReport()?.header?.glibcVersionRuntime ? "glibc" : "musl" : void 0;
|
|
11
11
|
const slot = [process.platform, process.arch, libc].filter(Boolean).join("-");
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
const dir = assets || existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../native");
|
|
12
|
+
const adjacent = path.join(path.dirname(fileURLToPath(import.meta.url)), "terminal-native");
|
|
13
|
+
const dir = existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../native");
|
|
15
14
|
const file = path.join(dir, "prebuilt", slot, "terminal-owner");
|
|
16
15
|
const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), "manifest.json"), "utf8"));
|
|
17
16
|
if (!statSync(file).isFile() || manifest.protocol !== 1 || manifest.slot !== slot || manifest.source !== sha(readFileSync(path.join(dir, "terminal-owner.c"))) || manifest.sha256 !== sha(readFileSync(file))) throw new Error("Native helper manifest mismatch");
|
package/dist/operations.d.ts
CHANGED
|
@@ -14,6 +14,13 @@ export type OperationsOptions = {
|
|
|
14
14
|
knownProjects?: () => Iterable<string>;
|
|
15
15
|
/** A gate changed through task.gate.resolve: the runtime syncs the project's gate cards and mail. */
|
|
16
16
|
onGateChange?: (projectRoot: string) => Promise<void> | void;
|
|
17
|
+
/** A provider file was written or removed; `enabled` when this save turned it from off to on (t-d0b0). */
|
|
18
|
+
onProviderSaved?: (id: string, enabled: boolean) => void;
|
|
19
|
+
/** The models alpd's catalog learned or probed for an ACP provider (t-d0b0). */
|
|
20
|
+
learnedModels?: (id: string) => Array<{
|
|
21
|
+
id: string;
|
|
22
|
+
label?: string;
|
|
23
|
+
}>;
|
|
17
24
|
};
|
|
18
25
|
/** `caller.agent`: the connection said in daemon.hello that an ALP agent started it (t-ca1f). */
|
|
19
26
|
export type Caller = {
|
|
@@ -24,7 +31,7 @@ type Handler = (params: any, caller?: Caller) => Promise<unknown>;
|
|
|
24
31
|
export declare function fromCore(error: any, context?: {
|
|
25
32
|
notFound?: 'not_found' | 'invalid_entry';
|
|
26
33
|
}): unknown;
|
|
27
|
-
export declare function createOperations({ home, templates, knownProjects, onGateChange }?: OperationsOptions): {
|
|
34
|
+
export declare function createOperations({ home, templates, knownProjects, onGateChange, onProviderSaved, learnedModels }?: OperationsOptions): {
|
|
28
35
|
handlers: {
|
|
29
36
|
[x: string]: Handler;
|
|
30
37
|
};
|
package/dist/operations.js
CHANGED
|
@@ -104,7 +104,7 @@ function unredact(kind, content, previous) {
|
|
|
104
104
|
if (found !== void 0) throw failure(RPC_ERROR.invalidParams, "secret_marker", `${found || "content"} holds a secret marker where no secret is kept`);
|
|
105
105
|
return next;
|
|
106
106
|
}
|
|
107
|
-
function createOperations({ home, templates, knownProjects = () => [], onGateChange } = {}) {
|
|
107
|
+
function createOperations({ home, templates, knownProjects = () => [], onGateChange, onProviderSaved, learnedModels } = {}) {
|
|
108
108
|
const revisionKey = randomBytes(32);
|
|
109
109
|
const toWire = (revision) => revision == null ? null : `r${createHmac("sha256", revisionKey).update(revision).digest("base64url").slice(0, 22)}`;
|
|
110
110
|
let writes = Promise.resolve();
|
|
@@ -222,6 +222,12 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
|
|
|
222
222
|
const previous = current?.content ?? (await layer(kind, name, options))?.content;
|
|
223
223
|
const next = unredact(kind, content, previous);
|
|
224
224
|
const saved = await saveEntry(kind, name, next, { ...options, scope, policy, ...revision !== void 0 ? { revision: current?.revision ?? null } : {} });
|
|
225
|
+
if (kind === "providers") {
|
|
226
|
+
try {
|
|
227
|
+
onProviderSaved?.(name, previous?.provider?.enabled === false && next?.provider?.enabled !== false);
|
|
228
|
+
} catch {
|
|
229
|
+
}
|
|
230
|
+
}
|
|
225
231
|
if (kind !== "teams" || sync !== "known-projects") return { revision: toWire(saved.revision) };
|
|
226
232
|
const roots = new Set(options.root ? [options.root] : []);
|
|
227
233
|
if (scope === "library") {
|
|
@@ -243,7 +249,14 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
|
|
|
243
249
|
const current = await layer(kind, name, options, scope);
|
|
244
250
|
if (!current) throw failure(ERROR.notFound, "not_found", `No ${kind} entry '${name}' in the ${scope}`);
|
|
245
251
|
if (revision !== void 0 && revision !== toWire(current.revision)) throw failure(ERROR.conflict, "revision_conflict", `${kind} '${name}' changed in the ${scope} since you opened it`);
|
|
246
|
-
|
|
252
|
+
const deleted = await deleteEntry(kind, name, { ...options, scope, policy, ...revision !== void 0 ? { revision: current.revision } : {} });
|
|
253
|
+
if (kind === "providers") {
|
|
254
|
+
try {
|
|
255
|
+
onProviderSaved?.(name, false);
|
|
256
|
+
} catch {
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
return deleted;
|
|
247
260
|
})),
|
|
248
261
|
"library.duplicate": guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
|
|
249
262
|
const options = await where(projectRoot, scope);
|
|
@@ -252,11 +265,25 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
|
|
|
252
265
|
} catch (error) {
|
|
253
266
|
throw fromCore(error, { notFound: "not_found" });
|
|
254
267
|
}
|
|
255
|
-
|
|
268
|
+
const result = { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope, policy })).revision) };
|
|
269
|
+
if (kind === "providers") {
|
|
270
|
+
try {
|
|
271
|
+
onProviderSaved?.(to, false);
|
|
272
|
+
} catch {
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return result;
|
|
256
276
|
}), { notFound: "invalid_entry" }),
|
|
257
277
|
"library.rename": guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
|
|
258
278
|
const options = await where(projectRoot, scope);
|
|
259
|
-
|
|
279
|
+
const renamed = await renameEntry(kind, from, to, { ...options, scope, policy });
|
|
280
|
+
if (kind === "providers") {
|
|
281
|
+
try {
|
|
282
|
+
onProviderSaved?.(to, false);
|
|
283
|
+
} catch {
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return { revision: toWire(renamed.revision) };
|
|
260
287
|
})),
|
|
261
288
|
"library.skills.set": guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: "invalid_entry" }),
|
|
262
289
|
"library.models": guard(async () => {
|
|
@@ -264,7 +291,7 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
|
|
|
264
291
|
for (const provider of await listProviders(home)) {
|
|
265
292
|
if (provider.enabled === false || provider.kind === "antigravity") continue;
|
|
266
293
|
models.push({ id: `acp:${provider.id}`, label: `${provider.label} \xB7 Provider default`, efforts: [] });
|
|
267
|
-
for (const model of [...provider.models ?? [], ...provider.additionalModels ?? []]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} \xB7 ${model.label ?? model.id}`, efforts: [] });
|
|
294
|
+
for (const model of [...provider.models ?? learnedModels?.(provider.id) ?? [], ...provider.additionalModels ?? []]) models.push({ id: `acp:${provider.id}/${model.id}`, label: `${provider.label} \xB7 ${model.label ?? model.id}`, efforts: [] });
|
|
268
295
|
}
|
|
269
296
|
return { models: [...new Map(models.map((model) => [model.id, model])).values()] };
|
|
270
297
|
}),
|
package/dist/scheduler.js
CHANGED
|
@@ -134,6 +134,8 @@ function createScheduler({ store, runtime, deliver, ready, session, settled, sto
|
|
|
134
134
|
opening.delete(current.id);
|
|
135
135
|
if (snapshot.parentId) return fail(current, "The session this job continues is not a root session", "not_a_root");
|
|
136
136
|
if (projectKey(snapshot.projectRoot) !== projectKey(current.projectRoot)) return fail(current, "The session this job continues belongs to another project", "other_project");
|
|
137
|
+
const refused = runtime.refusesPrompt?.(current.sessionId, [{ type: "text", text: current.prompt }]);
|
|
138
|
+
if (refused) return fail(current, refused, "native_command_unsupported");
|
|
137
139
|
const waitBusy = async () => {
|
|
138
140
|
const since = busy.get(current.id) ?? now();
|
|
139
141
|
busy.set(current.id, since);
|
package/dist/server.js
CHANGED
|
@@ -10,7 +10,7 @@ import os from "node:os";
|
|
|
10
10
|
import { assertPrivateDirectory, assertPrivateSocket } from "@anhlp/alp-client/index";
|
|
11
11
|
import path from "node:path";
|
|
12
12
|
import { createLogger } from "@anhlp/alp-core/log";
|
|
13
|
-
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from "@anhlp/alp-protocol";
|
|
13
|
+
import { AGENT_NAME, AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from "@anhlp/alp-protocol";
|
|
14
14
|
import { validateParams } from "@anhlp/alp-protocol/contract";
|
|
15
15
|
import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
|
|
16
16
|
import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
|
|
@@ -109,12 +109,18 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
109
109
|
const connections = /* @__PURE__ */ new Set();
|
|
110
110
|
const catalogResult = () => {
|
|
111
111
|
const state = modelCatalog?.state();
|
|
112
|
+
const acpRows = modelCatalog?.acpRows() ?? [];
|
|
113
|
+
const acpModels = acpRows.map((row) => ({ id: `acp:${row.id}`, label: row.label, description: row.description, thinkingOptions: [], runtime: "acp", provider: row.provider, source: row.source, enabled: row.enabled, status: row.status }));
|
|
114
|
+
const acpProviders = Object.fromEntries([...new Set(acpRows.map((row) => row.provider))].map((id) => {
|
|
115
|
+
const acp = state?.acp?.[id];
|
|
116
|
+
return [`acp:${id}`, { status: acp?.status ?? "unprobed", ...acp?.fetchedAt ? { fetchedAt: acp.fetchedAt } : {}, ...acp?.error ? { error: acp.error } : {} }];
|
|
117
|
+
}));
|
|
112
118
|
return {
|
|
113
|
-
models,
|
|
119
|
+
models: [...models, ...acpModels],
|
|
114
120
|
modes,
|
|
115
121
|
thinkingOptions,
|
|
116
122
|
defaultModel: `codex:${DEFAULT_MODEL}`,
|
|
117
|
-
...state ? { fetchedAt: state.fetchedAt, providers: Object.fromEntries(Object.entries(state.providers).map(([runtime2, provider]) => [runtime2, { status: provider.status, fetchedAt: provider.fetchedAt, ...provider.error ? { error: provider.error } : {} }])) } : {}
|
|
123
|
+
...state ? { fetchedAt: state.fetchedAt, providers: { ...Object.fromEntries(Object.entries(state.providers).map(([runtime2, provider]) => [runtime2, { status: provider.status, fetchedAt: provider.fetchedAt, ...provider.error ? { error: provider.error } : {} }])), ...acpProviders, ...modelCatalog?.acpLoadError() ? { acp: { status: "failed", error: modelCatalog.acpLoadError() } } : {} } } : {}
|
|
118
124
|
};
|
|
119
125
|
};
|
|
120
126
|
const unsubscribeCatalog = modelCatalog?.onUpdated((snapshot) => {
|
|
@@ -848,11 +854,24 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
848
854
|
if (!gitReader) throw new RpcError(ERROR.unavailable, "Registry needs ALP_HOME");
|
|
849
855
|
return run(gitReader);
|
|
850
856
|
};
|
|
851
|
-
const operations = createOperations({
|
|
857
|
+
const operations = createOperations({
|
|
858
|
+
home,
|
|
859
|
+
templates,
|
|
860
|
+
knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])),
|
|
861
|
+
onGateChange: (root) => runtime.syncGates?.(root),
|
|
862
|
+
// A provider file saved: reread the ACP rows; one the user just enabled is probed for its models (t-d0b0).
|
|
863
|
+
learnedModels: (id) => modelCatalog?.acpModels(id) ?? [],
|
|
864
|
+
onProviderSaved: (id, enabled) => {
|
|
865
|
+
if (!modelCatalog) return;
|
|
866
|
+
void (enabled ? modelCatalog.refreshAcp([id]) : modelCatalog.loadAcp()).catch(() => {
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
});
|
|
852
870
|
const extensionOwners = /* @__PURE__ */ new Map();
|
|
853
871
|
const findPages = createFindPages();
|
|
854
872
|
const handlers = {
|
|
855
873
|
"extension.register": async (connection, params) => {
|
|
874
|
+
agentRefused(connection, "extension.register");
|
|
856
875
|
const method = params?.method;
|
|
857
876
|
if (typeof method !== "string" || !/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(method) || method === "__proto__" || method === "constructor" || method === "toString") throw new RpcError(ERROR.protocol, "extension.register requires a safe method name");
|
|
858
877
|
if (method.length > 128 || reservedNamespaces.has(method.split(".")[0]) && !originalMethods.has(method)) throw new RpcError(ERROR.protocol, "extension.register requires an extension namespace and a name of at most 128 characters");
|
|
@@ -1081,7 +1100,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
1081
1100
|
"catalog.get": () => catalogResult(),
|
|
1082
1101
|
"catalog.refresh": async () => {
|
|
1083
1102
|
if (!modelCatalog) throw new RpcError(ERROR.unavailable, "The live model catalog is not available");
|
|
1084
|
-
await modelCatalog.refresh()
|
|
1103
|
+
await Promise.all([modelCatalog.refresh(), modelCatalog.refreshAcp().catch(() => {
|
|
1104
|
+
})]);
|
|
1085
1105
|
return catalogResult();
|
|
1086
1106
|
},
|
|
1087
1107
|
// attachment.* (§12.6): each call acts for its principal context; without the store (no home or
|
|
@@ -1268,6 +1288,8 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
1268
1288
|
async "session.prompt"(_connection, { sessionId, clientMessageId, delivery = "auto", content, ...context }) {
|
|
1269
1289
|
if (typeof clientMessageId !== "string" || !Array.isArray(content)) throw new RpcError(-32602, "clientMessageId and content are required");
|
|
1270
1290
|
if (delivery !== "auto" && delivery !== "steer") throw new RpcError(-32602, "delivery must be auto or steer");
|
|
1291
|
+
const refused = runtime.refusesPrompt?.(sessionId, content);
|
|
1292
|
+
if (refused) throw new RpcError(-32602, refused, { reason: "native_command_unsupported" });
|
|
1271
1293
|
const images = content.filter((part) => part?.type === "image");
|
|
1272
1294
|
if (images.length > PROMPT_IMAGES.maxCount) throw new RpcError(-32602, `A prompt takes at most ${PROMPT_IMAGES.maxCount} images`);
|
|
1273
1295
|
let total = 0;
|
|
@@ -1304,26 +1326,45 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
|
|
|
1304
1326
|
});
|
|
1305
1327
|
},
|
|
1306
1328
|
/** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
|
|
1307
|
-
async "session.fork"(
|
|
1329
|
+
async "session.fork"(connection, params) {
|
|
1330
|
+
agentRefused(connection, "session.fork");
|
|
1308
1331
|
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not fork conversations (capability session.fork is not listed)");
|
|
1309
1332
|
return conversation.fork({ ...params, principal: principalOf(params) });
|
|
1310
1333
|
},
|
|
1311
1334
|
/** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
|
|
1312
|
-
async "session.rewind"(
|
|
1335
|
+
async "session.rewind"(connection, params) {
|
|
1336
|
+
agentRefused(connection, "session.rewind");
|
|
1313
1337
|
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not rewind conversations (capability session.rewind is not listed)");
|
|
1314
1338
|
return conversation.rewind(params);
|
|
1315
1339
|
},
|
|
1316
1340
|
/** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
|
|
1317
|
-
async "session.reload"(
|
|
1341
|
+
async "session.reload"(connection, params) {
|
|
1342
|
+
agentRefused(connection, "session.reload");
|
|
1318
1343
|
if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not reload sessions (capability session.reload is not listed)");
|
|
1319
1344
|
return conversation.reload(params);
|
|
1320
1345
|
},
|
|
1321
1346
|
/** Compacts a live root's context now or at its next turn boundary (t-0e56). */
|
|
1322
|
-
async "session.compact"(
|
|
1347
|
+
async "session.compact"(connection, { sessionId }) {
|
|
1348
|
+
agentRefused(connection, "session.compact");
|
|
1323
1349
|
if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
|
|
1324
1350
|
if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd does not compact sessions");
|
|
1325
1351
|
try {
|
|
1326
1352
|
return runtime.compact(sessionId);
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
const reason = error?.data?.reason;
|
|
1355
|
+
throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error), typeof reason === "string" ? { reason } : void 0);
|
|
1356
|
+
}
|
|
1357
|
+
},
|
|
1358
|
+
/** The slash commands and skills a live session's composer offers after "/" (t-f628). */
|
|
1359
|
+
async "session.commands"(_connection, { sessionId }) {
|
|
1360
|
+
if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
|
|
1361
|
+
if (!runtime.commands) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd lists no commands (capability session.commands is not listed)");
|
|
1362
|
+
if (!runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
|
|
1363
|
+
try {
|
|
1364
|
+
const listed = await runtime.commands(sessionId);
|
|
1365
|
+
const seen2 = /* @__PURE__ */ new Set();
|
|
1366
|
+
const commands = listed.filter((command) => /^[^\s\u0000-\u001f\u007f]{1,256}$/.test(command.name) && !seen2.has(command.name) && seen2.add(command.name)).slice(0, 1e3).map((command) => ({ name: command.name, description: command.description.slice(0, 4096), ...command.argumentHint ? { argumentHint: command.argumentHint.slice(0, 256) } : {}, kind: command.kind }));
|
|
1367
|
+
return { commands };
|
|
1327
1368
|
} catch (error) {
|
|
1328
1369
|
throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
|
|
1329
1370
|
}
|
|
@@ -1543,7 +1584,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1543
1584
|
async function invokeExtended(owner, caller, method, params) {
|
|
1544
1585
|
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, "too many pending extension calls");
|
|
1545
1586
|
const id = ++owner.nextId;
|
|
1546
|
-
const invocation = { jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params } };
|
|
1587
|
+
const invocation = { jsonrpc: "2.0", id, method: "extension.invoke", params: { method, params, caller: { agent: caller.agent === true, ...caller.agentName !== void 0 ? { agentName: caller.agentName } : {} } } };
|
|
1547
1588
|
if (Buffer.byteLength(encodeFrame(invocation), "utf8") > MAX_FRAME) throw new RpcError(-32600, "ALP daemon frame exceeds size limit");
|
|
1548
1589
|
return new Promise((resolve, reject) => {
|
|
1549
1590
|
const timer = setTimeout(() => {
|
|
@@ -1583,7 +1624,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1583
1624
|
throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
|
|
1584
1625
|
}
|
|
1585
1626
|
}
|
|
1586
|
-
const capabilities = [...runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : [], CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : [], ...schedules ? [CAPABILITY.schedule] : [], ...registry ? ["workspace.registry", CAPABILITY.workspaceGit] : [], CAPABILITY.workspaceGitFacts, ...worktrees ? ["workspace.worktree"] : [], ...attachments ? [CAPABILITY.attachments] : [], ...conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : [], ...conversation?.reloads ? [CAPABILITY.sessionReload] : [], ...conversation?.configures ? [CAPABILITY.sessionConfigureLive] : [], ...conversation ? [CAPABILITY.sessionResumeCommand] : [], ...modelCatalog ? [CAPABILITY.catalogLive] : [], ...operations.capabilities];
|
|
1627
|
+
const capabilities = [...runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : [], ...runtime.commands ? [CAPABILITY.sessionCommands] : [], CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : [], ...schedules ? [CAPABILITY.schedule] : [], ...registry ? ["workspace.registry", CAPABILITY.workspaceGit] : [], CAPABILITY.workspaceGitFacts, ...worktrees ? ["workspace.worktree"] : [], ...attachments ? [CAPABILITY.attachments] : [], ...conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : [], ...conversation?.reloads ? [CAPABILITY.sessionReload] : [], ...conversation?.configures ? [CAPABILITY.sessionConfigureLive] : [], ...conversation ? [CAPABILITY.sessionResumeCommand] : [], ...modelCatalog ? [CAPABILITY.catalogLive] : [], ...operations.capabilities];
|
|
1587
1628
|
function fits(response) {
|
|
1588
1629
|
if (frameBytes(response) <= MAX_FRAME) return response;
|
|
1589
1630
|
log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
|
|
@@ -1625,9 +1666,18 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
|
|
|
1625
1666
|
if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`, { reason: "protocol_version", supported: [PROTOCOL_VERSION] });
|
|
1626
1667
|
const issues2 = validateParams(method, params);
|
|
1627
1668
|
if (issues2.length) throw invalidParams(issues2);
|
|
1669
|
+
const named = params?.principal?.agent;
|
|
1670
|
+
if (named !== void 0 && (typeof named !== "string" || !AGENT_NAME.test(named))) throw new RpcError(RPC_ERROR.invalidParams, "principal.agent must be an agent name", { reason: "invalid_params" });
|
|
1628
1671
|
connection.helloed = true;
|
|
1629
1672
|
connection.agent = connection.agent === true || Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY);
|
|
1630
1673
|
if (typeof params?.client?.name === "string") connection.client = params.client.name;
|
|
1674
|
+
if (named !== void 0) {
|
|
1675
|
+
connection.agent = true;
|
|
1676
|
+
if (connection.agentName === void 0) {
|
|
1677
|
+
connection.agentName = named;
|
|
1678
|
+
log.info("an agent connection named itself", { code: "ALP_AGENT_CONNECTION", agentName: named, client: connection.client });
|
|
1679
|
+
} else if (connection.agentName !== named) log.warn("an agent connection gave a second name; the first stays", { code: "ALP_AGENT_CONNECTION_RENAME", agentName: connection.agentName, refused: named });
|
|
1680
|
+
}
|
|
1631
1681
|
const terminalLimits = await terminals?.advertised();
|
|
1632
1682
|
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal, CAPABILITY.terminalCapture, CAPABILITY.terminalWatch] : capabilities, ...attachments ? { attachmentLimits: attachments.limits } : {}, ...terminalLimits ? { terminalLimits } : {} } });
|
|
1633
1683
|
return;
|
package/dist/terminals.d.ts
CHANGED
|
@@ -28,13 +28,23 @@ type Disposable = {
|
|
|
28
28
|
};
|
|
29
29
|
/** Native owner interface; injected owners are used only by tests. */
|
|
30
30
|
export type PtyProcess = {
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* The shell's pid, read live on every access: never copy it at spawn. The win32 owner reports 0
|
|
33
|
+
* until node-pty's ConPTY output worker connects, then the real pid (windows-terminal.ts).
|
|
34
|
+
*/
|
|
35
|
+
readonly pid: number;
|
|
32
36
|
/** The PTY's device (node-pty's UnixTerminal), such as /dev/ttys004 or /dev/pts/3. */
|
|
33
37
|
readonly ptsName?: string;
|
|
34
38
|
write(data: string): void;
|
|
35
39
|
resize(cols: number, rows: number): void;
|
|
36
40
|
kill(signal?: string): void;
|
|
37
41
|
cleanup?: () => Promise<CleanupResult>;
|
|
42
|
+
/**
|
|
43
|
+
* The win32 owner (no native cleanup): resolves once node-pty reports the killed shell's exit, or
|
|
44
|
+
* after `ms`. `kill` only asks node-pty to end the shell; until Windows has closed the shell's
|
|
45
|
+
* handles, its working directory (the workspace) stays open and cannot be removed (EBUSY, t-bfbd).
|
|
46
|
+
*/
|
|
47
|
+
exited?: (ms: number) => Promise<void>;
|
|
38
48
|
onData(listener: (data: string) => void): Disposable;
|
|
39
49
|
onExit(listener: (event: {
|
|
40
50
|
exitCode: number | null;
|
|
@@ -186,7 +196,7 @@ export declare function createTerminalService(options: TerminalServiceOptions):
|
|
|
186
196
|
sweep: () => Promise<void>;
|
|
187
197
|
/** alpd stops: every terminal ends (reason `shutdown`) and its tree is killed. */
|
|
188
198
|
shutdown(): Promise<void>;
|
|
189
|
-
/** Test hook: pids of every running terminal's shell. */
|
|
199
|
+
/** Test hook: pids of every running terminal's shell (read live: the win32 owner learns it after spawn). */
|
|
190
200
|
pids(): number[];
|
|
191
201
|
};
|
|
192
202
|
export type TerminalService = ReturnType<typeof createTerminalService>;
|
package/dist/terminals.js
CHANGED
|
@@ -167,6 +167,7 @@ function createTerminalService(options) {
|
|
|
167
167
|
async function cleanup(owner, id) {
|
|
168
168
|
if (!owner.cleanup) {
|
|
169
169
|
owner.kill();
|
|
170
|
+
await owner.exited?.(killGraceMs);
|
|
170
171
|
return;
|
|
171
172
|
}
|
|
172
173
|
const result = await owner.cleanup();
|
|
@@ -403,7 +404,6 @@ function createTerminalService(options) {
|
|
|
403
404
|
cols: params.cols,
|
|
404
405
|
rows: params.rows,
|
|
405
406
|
pty: process_,
|
|
406
|
-
pid: process_.pid,
|
|
407
407
|
screen: new TerminalScreen(params.cols, params.rows),
|
|
408
408
|
...typeof process_.ptsName === "string" && process_.ptsName.startsWith("/dev/") ? { tty: process_.ptsName.slice("/dev/".length) } : {},
|
|
409
409
|
createdAt: at,
|
|
@@ -556,9 +556,9 @@ function createTerminalService(options) {
|
|
|
556
556
|
watchers.clear();
|
|
557
557
|
if (cleanupFault || outcomes.some((result) => result.status === "rejected")) throw refused("terminal_cleanup_uncertain");
|
|
558
558
|
},
|
|
559
|
-
/** Test hook: pids of every running terminal's shell. */
|
|
559
|
+
/** Test hook: pids of every running terminal's shell (read live: the win32 owner learns it after spawn). */
|
|
560
560
|
pids() {
|
|
561
|
-
return [...terminals.values()].filter((terminal) => !terminal.exit).map((terminal) => terminal.pid);
|
|
561
|
+
return [...terminals.values()].filter((terminal) => !terminal.exit).map((terminal) => terminal.pty.pid);
|
|
562
562
|
}
|
|
563
563
|
};
|
|
564
564
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { PtySpawn } from './terminals.js';
|
|
2
|
-
|
|
2
|
+
/** The node-pty surface the win32 owner uses. */
|
|
3
|
+
export type NodePty = {
|
|
3
4
|
spawn(file: string, args: string[], options: Record<string, unknown>): {
|
|
4
5
|
pid: number;
|
|
5
6
|
write(data: string): void;
|
|
@@ -18,12 +19,14 @@ type NodePty = {
|
|
|
18
19
|
};
|
|
19
20
|
/** node-pty, or undefined when it cannot load on this host. */
|
|
20
21
|
export declare function loadNodePty(): NodePty | undefined;
|
|
21
|
-
|
|
22
|
+
/** `load` is a test hook (tests/windows-terminal.test.js); production loads the installed node-pty. */
|
|
23
|
+
export declare function windowsTerminalCapability(load?: () => NodePty | undefined): {
|
|
22
24
|
available: boolean;
|
|
23
25
|
protection?: 'none';
|
|
24
26
|
reason?: string;
|
|
25
27
|
};
|
|
26
28
|
/** The shell for a Windows terminal: COMSPEC when absolute, else cmd.exe. */
|
|
27
29
|
export declare function windowsShell(env?: NodeJS.ProcessEnv): string;
|
|
30
|
+
/** The win32 owner over `load`'s node-pty; `load` is a test hook, production uses {@link windowsPtySpawn}. */
|
|
31
|
+
export declare const createWindowsPtySpawn: (load?: () => NodePty | undefined) => PtySpawn;
|
|
28
32
|
export declare const windowsPtySpawn: PtySpawn;
|
|
29
|
-
export {};
|
package/dist/windows-terminal.js
CHANGED
|
@@ -1,39 +1,42 @@
|
|
|
1
1
|
// packages/daemon/src/windows-terminal.ts
|
|
2
|
-
import { existsSync } from "node:fs";
|
|
3
2
|
import { createRequire } from "node:module";
|
|
4
|
-
import path from "node:path";
|
|
5
|
-
function packagedNodePty() {
|
|
6
|
-
const assets = globalThis[Symbol.for("alp.packaged")]?.assetDir?.();
|
|
7
|
-
const entry = assets ? path.join(assets, "node-pty", "lib", "index.js") : void 0;
|
|
8
|
-
return entry && existsSync(entry) ? entry : void 0;
|
|
9
|
-
}
|
|
10
3
|
var loaded;
|
|
11
4
|
function loadNodePty() {
|
|
12
5
|
if (loaded === void 0) {
|
|
13
6
|
try {
|
|
14
|
-
loaded = createRequire(import.meta.url)(
|
|
7
|
+
loaded = createRequire(import.meta.url)("node-pty");
|
|
15
8
|
} catch {
|
|
16
9
|
loaded = null;
|
|
17
10
|
}
|
|
18
11
|
}
|
|
19
12
|
return loaded ?? void 0;
|
|
20
13
|
}
|
|
21
|
-
function windowsTerminalCapability() {
|
|
22
|
-
return
|
|
14
|
+
function windowsTerminalCapability(load = loadNodePty) {
|
|
15
|
+
return load() ? { available: true, protection: "none" } : { available: false, reason: "node_pty_unavailable" };
|
|
23
16
|
}
|
|
24
17
|
function windowsShell(env = process.env) {
|
|
25
18
|
const candidate = env.ComSpec ?? env.COMSPEC;
|
|
26
19
|
return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : "cmd.exe";
|
|
27
20
|
}
|
|
28
|
-
var
|
|
21
|
+
var createWindowsPtySpawn = (load = loadNodePty) => (file, args, options) => {
|
|
29
22
|
if (options.signal?.aborted) throw new Error("Terminal startup cancelled");
|
|
30
|
-
const pty =
|
|
23
|
+
const pty = load();
|
|
31
24
|
if (!pty) throw new Error("node-pty is unavailable on this host");
|
|
32
|
-
const
|
|
33
|
-
const child = typeof process.versions.bun === "string" ? spawnUnderBun(pty, file, args, spawnOptions) : pty.spawn(file, args, spawnOptions);
|
|
25
|
+
const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
|
|
34
26
|
let killed = false;
|
|
27
|
+
let exit = false;
|
|
28
|
+
const exited = new Promise((resolve) => {
|
|
29
|
+
child.onExit(() => {
|
|
30
|
+
exit = true;
|
|
31
|
+
resolve();
|
|
32
|
+
});
|
|
33
|
+
});
|
|
35
34
|
return {
|
|
36
|
-
pid
|
|
35
|
+
// node-pty reports the ConPTY shell's pid only once its output worker connects (0 until then), so
|
|
36
|
+
// the pid is read live rather than copied at spawn.
|
|
37
|
+
get pid() {
|
|
38
|
+
return child.pid;
|
|
39
|
+
},
|
|
37
40
|
write(data) {
|
|
38
41
|
if (!killed) child.write(data);
|
|
39
42
|
},
|
|
@@ -52,69 +55,23 @@ var windowsPtySpawn = (file, args, options) => {
|
|
|
52
55
|
} catch {
|
|
53
56
|
}
|
|
54
57
|
},
|
|
58
|
+
// Bounded: node-pty defers a kill until the terminal is ready (its first output) and may never report
|
|
59
|
+
// an exit (a terminal that never becomes ready, a lost callback); that does not hold up close.
|
|
60
|
+
async exited(ms) {
|
|
61
|
+
if (exit) return;
|
|
62
|
+
let timer;
|
|
63
|
+
await Promise.race([exited, new Promise((resolve) => {
|
|
64
|
+
timer = setTimeout(resolve, ms);
|
|
65
|
+
})]);
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
},
|
|
55
68
|
onData: (listener) => child.onData(listener),
|
|
56
69
|
onExit: (listener) => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal }))
|
|
57
70
|
};
|
|
58
71
|
};
|
|
59
|
-
|
|
60
|
-
const load = createRequire(import.meta.url);
|
|
61
|
-
const fs = load("node:fs");
|
|
62
|
-
const net = load("node:net");
|
|
63
|
-
const Socket = net.Socket;
|
|
64
|
-
function InputSocket(...rest) {
|
|
65
|
-
const [opts] = rest;
|
|
66
|
-
if (opts && typeof opts.fd === "number" && opts.writable === true && opts.readable === false) return fdWriter(fs, opts.fd);
|
|
67
|
-
return new Socket(...rest);
|
|
68
|
-
}
|
|
69
|
-
InputSocket.prototype = Socket.prototype;
|
|
70
|
-
net.Socket = InputSocket;
|
|
71
|
-
try {
|
|
72
|
-
return pty.spawn(file, args, options);
|
|
73
|
-
} finally {
|
|
74
|
-
net.Socket = Socket;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
function fdWriter(fs, fd) {
|
|
78
|
-
let queue = Promise.resolve();
|
|
79
|
-
let closed = false;
|
|
80
|
-
let failed = false;
|
|
81
|
-
const writer = {
|
|
82
|
-
readable: false,
|
|
83
|
-
writable: true,
|
|
84
|
-
setEncoding() {
|
|
85
|
-
return writer;
|
|
86
|
-
},
|
|
87
|
-
write(data) {
|
|
88
|
-
if (closed || failed) return false;
|
|
89
|
-
const bytes = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
|
|
90
|
-
queue = queue.then(() => new Promise((resolve) => {
|
|
91
|
-
const rest = (offset) => {
|
|
92
|
-
if (closed || failed || offset >= bytes.length) return resolve();
|
|
93
|
-
fs.write(fd, bytes, offset, bytes.length - offset, null, (error, written) => {
|
|
94
|
-
if (error) {
|
|
95
|
-
failed = true;
|
|
96
|
-
writer.writable = false;
|
|
97
|
-
return resolve();
|
|
98
|
-
}
|
|
99
|
-
rest(offset + written);
|
|
100
|
-
});
|
|
101
|
-
};
|
|
102
|
-
rest(0);
|
|
103
|
-
}));
|
|
104
|
-
return true;
|
|
105
|
-
},
|
|
106
|
-
destroy() {
|
|
107
|
-
if (closed) return writer;
|
|
108
|
-
closed = true;
|
|
109
|
-
writer.writable = false;
|
|
110
|
-
void queue.then(() => fs.close(fd, () => {
|
|
111
|
-
}));
|
|
112
|
-
return writer;
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
return writer;
|
|
116
|
-
}
|
|
72
|
+
var windowsPtySpawn = createWindowsPtySpawn();
|
|
117
73
|
export {
|
|
74
|
+
createWindowsPtySpawn,
|
|
118
75
|
loadNodePty,
|
|
119
76
|
windowsPtySpawn,
|
|
120
77
|
windowsShell,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anhlp/alp-daemon",
|
|
3
|
-
"version": "0.0.1-beta.
|
|
3
|
+
"version": "0.0.1-beta.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "ALP daemon module",
|
|
6
6
|
"files": [
|
|
@@ -129,13 +129,13 @@
|
|
|
129
129
|
"node": ">=22.12"
|
|
130
130
|
},
|
|
131
131
|
"dependencies": {
|
|
132
|
-
"@anhlp/alp-core": "0.0.1-beta.
|
|
133
|
-
"@anhlp/alp-runtime": "0.0.1-beta.
|
|
134
|
-
"@anhlp/alp-client": "0.0.1-beta.
|
|
135
|
-
"@anhlp/alp-protocol": "0.0.1-beta.
|
|
132
|
+
"@anhlp/alp-core": "0.0.1-beta.8",
|
|
133
|
+
"@anhlp/alp-runtime": "0.0.1-beta.8",
|
|
134
|
+
"@anhlp/alp-client": "0.0.1-beta.8",
|
|
135
|
+
"@anhlp/alp-protocol": "0.0.1-beta.8",
|
|
136
136
|
"@anthropic-ai/sdk": "^0.131.0",
|
|
137
137
|
"ws": "^8.22.0",
|
|
138
|
-
"zod": "4.
|
|
138
|
+
"zod": "4.6.7",
|
|
139
139
|
"@anthropic-ai/claude-agent-sdk": "^0.3.292",
|
|
140
140
|
"@xterm/headless": "6.0.0"
|
|
141
141
|
},
|