@anhlp/alp-daemon 0.0.1-beta.7 → 0.0.1-beta.9

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.
@@ -0,0 +1,2 @@
1
+ import { ModelCatalog } from '@anhlp/alp-runtime/index';
2
+ export declare function createModelCatalog(home: string, warn?: (message: string) => void): ModelCatalog;
@@ -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
+ };
@@ -0,0 +1,2 @@
1
+ import './native-register.js';
2
+ import './main.js';
@@ -0,0 +1,3 @@
1
+ // packages/daemon/src/native-entry.ts
2
+ import "./native-register.js";
3
+ import "./main.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ // packages/daemon/src/native-register.ts
2
+ import { bundleDist, bundleInfo, registerNativeDaemon } from "@anhlp/alp-core/packaged";
3
+ if (process.argv.length === 3 && process.argv[2] === "--version") {
4
+ process.stdout.write(`${true ? "0.0.1-beta.9" : "0.0.0-dev"}
5
+ `);
6
+ process.exit(0);
7
+ }
8
+ var bundle = bundleInfo();
9
+ registerNativeDaemon({
10
+ modules: { claudeAgentSdk: () => import("@anthropic-ai/claude-agent-sdk") },
11
+ // The terminal helper (native-terminal.ts) lies in the bundle's @anhlp/alp-cli dist, not beside alpd.
12
+ distDir: () => bundle ? bundleDist(bundle) : void 0
13
+ });
@@ -9,8 +9,12 @@ 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 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");
12
+ const native = globalThis[Symbol.for("alp.nativeDaemon")];
13
+ const bundled = native?.distDir?.();
14
+ if (native && !bundled) throw new Error("The native alpd runs outside an ALP bundle: no terminal helper");
15
+ const here = bundled ?? path.dirname(fileURLToPath(import.meta.url));
16
+ const adjacent = path.join(here, "terminal-native");
17
+ const dir = existsSync(adjacent) || bundled ? adjacent : path.resolve(here, "../native");
14
18
  const file = path.join(dir, "prebuilt", slot, "terminal-owner");
15
19
  const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), "manifest.json"), "utf8"));
16
20
  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");
@@ -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
  };
@@ -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
- return deleteEntry(kind, name, { ...options, scope, policy, ...revision !== void 0 ? { revision: current.revision } : {} });
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
- return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope, policy })).revision) };
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
- return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope, policy })).revision) };
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({ home, templates, knownProjects: () => new Set([...records.values()].flatMap((record) => record.session?.projectRoot ? [record.session.projectRoot] : [])), onGateChange: (root) => runtime.syncGates?.(root) });
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,28 +1326,33 @@ 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"(_connection, params) {
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"(_connection, params) {
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"(_connection, params) {
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"(_connection, { sessionId }) {
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);
1327
1353
  } catch (error) {
1328
- throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(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);
1329
1356
  }
1330
1357
  },
1331
1358
  /** The slash commands and skills a live session's composer offers after "/" (t-f628). */
@@ -1557,7 +1584,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1557
1584
  async function invokeExtended(owner, caller, method, params) {
1558
1585
  if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, "too many pending extension calls");
1559
1586
  const id = ++owner.nextId;
1560
- 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 } : {} } } };
1561
1588
  if (Buffer.byteLength(encodeFrame(invocation), "utf8") > MAX_FRAME) throw new RpcError(-32600, "ALP daemon frame exceeds size limit");
1562
1589
  return new Promise((resolve, reject) => {
1563
1590
  const timer = setTimeout(() => {
@@ -1639,9 +1666,18 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1639
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] });
1640
1667
  const issues2 = validateParams(method, params);
1641
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" });
1642
1671
  connection.helloed = true;
1643
1672
  connection.agent = connection.agent === true || Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY);
1644
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
+ }
1645
1681
  const terminalLimits = await terminals?.advertised();
1646
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 } : {} } });
1647
1683
  return;
@@ -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
- pid: number;
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
- type NodePty = {
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
- export declare function windowsTerminalCapability(): {
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 {};
@@ -11,21 +11,32 @@ function loadNodePty() {
11
11
  }
12
12
  return loaded ?? void 0;
13
13
  }
14
- function windowsTerminalCapability() {
15
- return loadNodePty() ? { available: true, protection: "none" } : { available: false, reason: "node_pty_unavailable" };
14
+ function windowsTerminalCapability(load = loadNodePty) {
15
+ return load() ? { available: true, protection: "none" } : { available: false, reason: "node_pty_unavailable" };
16
16
  }
17
17
  function windowsShell(env = process.env) {
18
18
  const candidate = env.ComSpec ?? env.COMSPEC;
19
19
  return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : "cmd.exe";
20
20
  }
21
- var windowsPtySpawn = (file, args, options) => {
21
+ var createWindowsPtySpawn = (load = loadNodePty) => (file, args, options) => {
22
22
  if (options.signal?.aborted) throw new Error("Terminal startup cancelled");
23
- const pty = loadNodePty();
23
+ const pty = load();
24
24
  if (!pty) throw new Error("node-pty is unavailable on this host");
25
25
  const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
26
26
  let killed = false;
27
+ let exit = false;
28
+ const exited = new Promise((resolve) => {
29
+ child.onExit(() => {
30
+ exit = true;
31
+ resolve();
32
+ });
33
+ });
27
34
  return {
28
- pid: child.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
+ },
29
40
  write(data) {
30
41
  if (!killed) child.write(data);
31
42
  },
@@ -44,11 +55,23 @@ var windowsPtySpawn = (file, args, options) => {
44
55
  } catch {
45
56
  }
46
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
+ },
47
68
  onData: (listener) => child.onData(listener),
48
69
  onExit: (listener) => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal }))
49
70
  };
50
71
  };
72
+ var windowsPtySpawn = createWindowsPtySpawn();
51
73
  export {
74
+ createWindowsPtySpawn,
52
75
  loadNodePty,
53
76
  windowsPtySpawn,
54
77
  windowsShell,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-daemon",
3
- "version": "0.0.1-beta.7",
3
+ "version": "0.0.1-beta.9",
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.7",
133
- "@anhlp/alp-runtime": "0.0.1-beta.7",
134
- "@anhlp/alp-client": "0.0.1-beta.7",
135
- "@anhlp/alp-protocol": "0.0.1-beta.7",
132
+ "@anhlp/alp-core": "0.0.1-beta.9",
133
+ "@anhlp/alp-runtime": "0.0.1-beta.9",
134
+ "@anhlp/alp-client": "0.0.1-beta.9",
135
+ "@anhlp/alp-protocol": "0.0.1-beta.9",
136
136
  "@anthropic-ai/sdk": "^0.131.0",
137
137
  "ws": "^8.22.0",
138
- "zod": "4.4.3",
138
+ "zod": "4.6.7",
139
139
  "@anthropic-ai/claude-agent-sdk": "^0.3.292",
140
140
  "@xterm/headless": "6.0.0"
141
141
  },