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

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.1-beta.5",
2
+ "version": "0.0.1-beta.7",
3
3
  "entries": {
4
4
  "packages/daemon/dist/alpd.js": {
5
5
  "inputs": [
package/dist/main.js CHANGED
@@ -21,10 +21,18 @@ import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } fr
21
21
  import { migrateState } from "@anhlp/alp-core/migrations";
22
22
  import { createLogger } from "@anhlp/alp-core/log";
23
23
  import { selfCommand, selfEntry } from "@anhlp/alp-core/packaged";
24
- var VERSION = true ? "0.0.1-beta.5" : "0.0.0-dev";
24
+ var VERSION = true ? "0.0.1-beta.7" : "0.0.0-dev";
25
25
  var LOG_BYTES = 10 * 1024 * 1024;
26
26
  var LOG_FILES = 3;
27
27
  var log = createLogger({ component: "alpd" });
28
+ var LEFT_REASONS = {
29
+ invalid: () => "it is not a working git worktree (its git metadata is missing or broken)",
30
+ "not-linked": () => "it is a git repository of its own, not a worktree of one",
31
+ "other-branch": (entry) => entry.branch ? `it is on branch ${entry.branch}, not its alp branch` : "its HEAD is detached, so no branch holds its work",
32
+ "commit-failed": (entry) => `its work could not be committed${entry.detail ? ` (${entry.detail})` : ""}`,
33
+ uncommitted: () => "it still has changes that are not committed",
34
+ "ignored-files": (entry) => entry.files?.length ? `its work is committed to ${entry.branch}, but it holds ignored files that exist nowhere else: ${entry.files.join(", ")}` : `its ignored files could not be checked${entry.detail ? ` (${entry.detail})` : ""}`
35
+ };
28
36
  async function rotate(log2) {
29
37
  const size = await stat(log2).then((info) => info.size, () => 0);
30
38
  if (size < LOG_BYTES) return;
@@ -182,7 +190,18 @@ async function run(home2) {
182
190
  await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), groupLeader: leadsGroup() }), { mode: 384 });
183
191
  const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home2, "runs");
184
192
  const worktreeDir = path.join(home2, "worktrees");
185
- for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [])) log.info(`kept interrupted work on branch ${branch}`, { event: "worktree.kept", branch });
193
+ const reclaimed = await reclaimWorktrees(worktreeDir).catch(() => ({ kept: [], left: [] }));
194
+ for (const branch of reclaimed.kept) log.info(`kept interrupted work on branch ${branch}`, { event: "worktree.kept", branch });
195
+ for (const entry of reclaimed.left) {
196
+ log.warn(`left worktree ${entry.path} in place: ${LEFT_REASONS[entry.reason](entry)}`, {
197
+ event: "worktree.left",
198
+ path: entry.path,
199
+ reason: entry.reason,
200
+ ...entry.branch ? { branch: entry.branch } : {},
201
+ ...entry.detail ? { detail: entry.detail } : {},
202
+ ...entry.files ? { files: entry.files } : {}
203
+ });
204
+ }
186
205
  const copyDir = path.join(home2, "copies");
187
206
  await reclaimCopies(copyDir).catch(() => 0);
188
207
  const settings = await userSettings(home2);
@@ -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 assets = globalThis[Symbol.for("alp.packaged")]?.assetDir?.();
13
- const adjacent = assets ? path.join(assets, "terminal-native") : path.join(path.dirname(fileURLToPath(import.meta.url)), "terminal-native");
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");
@@ -20,6 +20,10 @@ export type Caller = {
20
20
  agent?: boolean;
21
21
  };
22
22
  type Handler = (params: any, caller?: Caller) => Promise<unknown>;
23
+ /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
24
+ export declare function fromCore(error: any, context?: {
25
+ notFound?: 'not_found' | 'invalid_entry';
26
+ }): unknown;
23
27
  export declare function createOperations({ home, templates, knownProjects, onGateChange }?: OperationsOptions): {
24
28
  handlers: {
25
29
  [x: string]: Handler;
@@ -182,7 +182,7 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
182
182
  return { id: task.id, status: task.status, rev: task.rev, ...landed ? { landed } : {} };
183
183
  }),
184
184
  // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
185
- // the runtime is told, so main gets the decision by mail once and the gate's card settles.
185
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
186
186
  "task.gate.resolve": guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = "web" }, caller) => {
187
187
  const root = await project(projectRoot);
188
188
  if (caller?.agent) {
@@ -281,5 +281,6 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
281
281
  };
282
282
  }
283
283
  export {
284
- createOperations
284
+ createOperations,
285
+ fromCore
285
286
  };
package/dist/server.js CHANGED
@@ -15,7 +15,7 @@ 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";
17
17
  import { RpcError } from "./rpc-error.js";
18
- import { createOperations } from "./operations.js";
18
+ import { createOperations, fromCore } from "./operations.js";
19
19
  import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from "./files.js";
20
20
  import { createGitReader } from "./git.js";
21
21
  import { createScheduleStore, projectKey } from "./schedules.js";
@@ -1025,14 +1025,18 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1025
1025
  throw new RpcError(ERROR.failed, error?.message ?? String(error));
1026
1026
  }
1027
1027
  },
1028
- "question.answer"(connection, { questionId, text, dismiss = false, reason }) {
1028
+ async "question.answer"(connection, { questionId, text, dismiss = false, reason }) {
1029
1029
  if (connection.agent) throw new RpcError(ERROR.forbidden, "Only the user answers a question; this connection was opened by an ALP agent", { reason: "user_only" });
1030
1030
  if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
1031
1031
  if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
1032
1032
  const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
1033
1033
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
1034
1034
  const channel = connection.client?.startsWith("alp-paseo") ? "paseo" : "web";
1035
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1035
+ const decided = runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1036
+ if (decided) await decided.catch((error) => {
1037
+ if (error?.code === "GATE_BUSY" || error?.code === "GATE_DECIDED") throw new RpcError(ERROR.conflict, error.message, { reason: "task_state" });
1038
+ throw fromCore(error);
1039
+ });
1036
1040
  return { questionId: matches[0].id };
1037
1041
  },
1038
1042
  "daemon.shutdown": () => {
@@ -1324,6 +1328,20 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1324
1328
  throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
1325
1329
  }
1326
1330
  },
1331
+ /** The slash commands and skills a live session's composer offers after "/" (t-f628). */
1332
+ async "session.commands"(_connection, { sessionId }) {
1333
+ if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
1334
+ if (!runtime.commands) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd lists no commands (capability session.commands is not listed)");
1335
+ if (!runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
1336
+ try {
1337
+ const listed = await runtime.commands(sessionId);
1338
+ const seen2 = /* @__PURE__ */ new Set();
1339
+ 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 }));
1340
+ return { commands };
1341
+ } catch (error) {
1342
+ throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
1343
+ }
1344
+ },
1327
1345
  /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1328
1346
  async "session.resumeCommand"(_connection, { sessionId }) {
1329
1347
  if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd has no resume command (capability session.resumeCommand is not listed)");
@@ -1579,7 +1597,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1579
1597
  throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
1580
1598
  }
1581
1599
  }
1582
- 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];
1600
+ 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];
1583
1601
  function fits(response) {
1584
1602
  if (frameBytes(response) <= MAX_FRAME) return response;
1585
1603
  log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
@@ -1,17 +1,10 @@
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)(packagedNodePty() ?? "node-pty");
7
+ loaded = createRequire(import.meta.url)("node-pty");
15
8
  } catch {
16
9
  loaded = null;
17
10
  }
@@ -29,8 +22,7 @@ var windowsPtySpawn = (file, args, options) => {
29
22
  if (options.signal?.aborted) throw new Error("Terminal startup cancelled");
30
23
  const pty = loadNodePty();
31
24
  if (!pty) throw new Error("node-pty is unavailable on this host");
32
- const spawnOptions = { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true, ...packagedNodePty() ? { useConptyDll: true } : {} };
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;
35
27
  return {
36
28
  pid: child.pid,
@@ -56,64 +48,6 @@ var windowsPtySpawn = (file, args, options) => {
56
48
  onExit: (listener) => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal }))
57
49
  };
58
50
  };
59
- function spawnUnderBun(pty, file, args, options) {
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
- }
117
51
  export {
118
52
  loadNodePty,
119
53
  windowsPtySpawn,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-daemon",
3
- "version": "0.0.1-beta.5",
3
+ "version": "0.0.1-beta.7",
4
4
  "type": "module",
5
5
  "description": "ALP daemon module",
6
6
  "files": [
@@ -129,10 +129,10 @@
129
129
  "node": ">=22.12"
130
130
  },
131
131
  "dependencies": {
132
- "@anhlp/alp-core": "0.0.1-beta.5",
133
- "@anhlp/alp-runtime": "0.0.1-beta.5",
134
- "@anhlp/alp-client": "0.0.1-beta.5",
135
- "@anhlp/alp-protocol": "0.0.1-beta.5",
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",
136
136
  "@anthropic-ai/sdk": "^0.131.0",
137
137
  "ws": "^8.22.0",
138
138
  "zod": "4.4.3",
package/src/main.ts CHANGED
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  import templates from 'alp:templates';
7
7
  import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION, withDaemonLifecycle } from '@anhlp/alp-client/index';
8
8
  import { attachmentStageDir, createAlpRuntime, liveProbes, ModelCatalog, reclaimCopies, reclaimWorktrees, setActiveCatalog } from '@anhlp/alp-runtime/index';
9
+ import type { LeftWorktree } from '@anhlp/alp-runtime/index';
9
10
  import { createDaemonServer } from './server.js';
10
11
  import { acquireLock, heartbeat, releaseLock, updateLock } from './lock.js';
11
12
  import { createStore } from './store.js';
@@ -23,6 +24,18 @@ const LOG_BYTES = 10 * 1024 * 1024;
23
24
  const LOG_FILES = 3;
24
25
  const log = createLogger({ component: 'alpd' });
25
26
 
27
+ /** Why reclaimWorktrees left a directory in $ALP_HOME/worktrees, for the `worktree.left` line. */
28
+ const LEFT_REASONS: Record<LeftWorktree['reason'], (entry: LeftWorktree) => string> = {
29
+ invalid: () => 'it is not a working git worktree (its git metadata is missing or broken)',
30
+ 'not-linked': () => 'it is a git repository of its own, not a worktree of one',
31
+ 'other-branch': entry => entry.branch ? `it is on branch ${entry.branch}, not its alp branch` : 'its HEAD is detached, so no branch holds its work',
32
+ 'commit-failed': entry => `its work could not be committed${entry.detail ? ` (${entry.detail})` : ''}`,
33
+ uncommitted: () => 'it still has changes that are not committed',
34
+ 'ignored-files': entry => entry.files?.length
35
+ ? `its work is committed to ${entry.branch}, but it holds ignored files that exist nowhere else: ${entry.files.join(', ')}`
36
+ : `its ignored files could not be checked${entry.detail ? ` (${entry.detail})` : ''}`,
37
+ };
38
+
26
39
  async function rotate(log: string) {
27
40
  const size = await stat(log).then(info => info.size, () => 0);
28
41
  if (size < LOG_BYTES) return;
@@ -201,8 +214,16 @@ async function run(home: string) {
201
214
  await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), groupLeader: leadsGroup() }), { mode: 0o600 });
202
215
  const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
203
216
  const worktreeDir = path.join(home, 'worktrees');
204
- // Worktrees of assignments a crash interrupted: their work goes to their branches.
205
- for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
217
+ // Worktrees of assignments a crash interrupted: their work goes to their branches. What
218
+ // reclaim leaves in place stays in $ALP_HOME/worktrees until the user looks: say where and why.
219
+ const reclaimed = await reclaimWorktrees(worktreeDir).catch(() => ({ kept: [] as string[], left: [] }));
220
+ for (const branch of reclaimed.kept) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
221
+ for (const entry of reclaimed.left) {
222
+ log.warn(`left worktree ${entry.path} in place: ${LEFT_REASONS[entry.reason](entry)}`, {
223
+ event: 'worktree.left', path: entry.path, reason: entry.reason,
224
+ ...(entry.branch ? { branch: entry.branch } : {}), ...(entry.detail ? { detail: entry.detail } : {}), ...(entry.files ? { files: entry.files } : {}),
225
+ });
226
+ }
206
227
  // Review copies of interrupted assignments hold nothing to keep.
207
228
  const copyDir = path.join(home, 'copies');
208
229
  await reclaimCopies(copyDir).catch(() => 0);
@@ -12,11 +12,8 @@ const sha = (value: Buffer) => createHash('sha256').update(value).digest('hex');
12
12
  function binary() {
13
13
  const libc = process.platform === 'linux' ? (process.report?.getReport() as { header?: { glibcVersionRuntime?: string } })?.header?.glibcVersionRuntime ? 'glibc' : 'musl' : undefined;
14
14
  const slot = [process.platform, process.arch, libc].filter(Boolean).join('-');
15
- // The ALP executable (t-1e02) extracts its helper; registerPackaged in @anhlp/alp-core/packaged publishes assetDir here.
16
- // Read through globalThis so this shipped adapter stays free of package imports.
17
- const assets = (globalThis as { [key: symbol]: { assetDir?: () => string | undefined } | undefined })[Symbol.for('alp.packaged')]?.assetDir?.();
18
- const adjacent = assets ? path.join(assets, 'terminal-native') : path.join(path.dirname(fileURLToPath(import.meta.url)), 'terminal-native');
19
- const dir = assets || existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../native');
15
+ const adjacent = path.join(path.dirname(fileURLToPath(import.meta.url)), 'terminal-native');
16
+ const dir = existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../native');
20
17
  const file = path.join(dir, 'prebuilt', slot, 'terminal-owner');
21
18
  const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), 'manifest.json'), 'utf8'));
22
19
  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/src/operations.ts CHANGED
@@ -51,7 +51,7 @@ const SECRET_MAPS: Record<string, string[][]> = {
51
51
  const failure = (code: number, reason: string, message: string, extra: object = {}) => new RpcError(code, message, { reason, ...extra });
52
52
 
53
53
  /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
54
- function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
54
+ export function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
55
55
  if (error instanceof RpcError || typeof error?.code !== 'string' || error?.name !== 'AlpError') return error;
56
56
  const message = error.message as string;
57
57
  switch (error.code) {
@@ -208,7 +208,7 @@ export function createOperations({ home, templates, knownProjects = () => [], on
208
208
  }),
209
209
 
210
210
  // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
211
- // the runtime is told, so main gets the decision by mail once and the gate's card settles.
211
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
212
212
  'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = 'web' }, caller) => {
213
213
  const root = await project(projectRoot);
214
214
  // Only the user decides a human gate: never a connection an ALP agent opened (t-ca1f).
package/src/server.ts CHANGED
@@ -17,7 +17,7 @@ import type { Receipt, SessionRecord, SessionStatus, Store, UnreadableReceipt }
17
17
  import type { PromptContent, SessionSummary } from '@anhlp/alp-protocol/session';
18
18
  import type { ScheduleJob, TurnAttention } from '@anhlp/alp-protocol/index';
19
19
  import { RpcError } from './rpc-error.js';
20
- import { createOperations, type OperationsOptions } from './operations.js';
20
+ import { createOperations, fromCore, type OperationsOptions } from './operations.js';
21
21
  import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from './files.js';
22
22
  import { createGitReader } from './git.js';
23
23
  import { createScheduleStore, projectKey } from './schedules.js';
@@ -1298,7 +1298,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1298
1298
  }
1299
1299
  },
1300
1300
 
1301
- 'question.answer'(connection, { questionId, text, dismiss = false, reason }) {
1301
+ async 'question.answer'(connection, { questionId, text, dismiss = false, reason }) {
1302
1302
  // An answer speaks for the user (a gate card's answer decides the gate): never from a connection an ALP agent opened (t-ca1f).
1303
1303
  if (connection.agent) throw new RpcError(ERROR.forbidden, 'Only the user answers a question; this connection was opened by an ALP agent', { reason: 'user_only' });
1304
1304
  if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
@@ -1307,7 +1307,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1307
1307
  const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
1308
1308
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
1309
1309
  const channel = connection.client?.startsWith('alp-paseo') ? 'paseo' as const : 'web' as const;
1310
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1310
+ // A gate card's answer settles once its decision is written; one that decides nothing is refused (t-595d).
1311
+ const decided = runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1312
+ if (decided) await decided.catch((error: any) => {
1313
+ // Another answer is being recorded, or another channel decided first: as task.gate.resolve says it.
1314
+ if (error?.code === 'GATE_BUSY' || error?.code === 'GATE_DECIDED') throw new RpcError(ERROR.conflict, error.message, { reason: 'task_state' });
1315
+ throw fromCore(error);
1316
+ });
1311
1317
  return { questionId: matches[0].id };
1312
1318
  },
1313
1319
 
@@ -1594,6 +1600,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1594
1600
  catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
1595
1601
  },
1596
1602
 
1603
+ /** The slash commands and skills a live session's composer offers after "/" (t-f628). */
1604
+ async 'session.commands'(_connection, { sessionId }) {
1605
+ if (typeof sessionId !== 'string' || !sessionId) throw new RpcError(-32602, 'sessionId is required');
1606
+ if (!runtime.commands) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd lists no commands (capability session.commands is not listed)');
1607
+ if (!runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
1608
+ try {
1609
+ const listed = await runtime.commands(sessionId);
1610
+ const seen = new Set<string>();
1611
+ const commands = listed.filter(command => /^[^\s\u0000-\u001f\u007f]{1,256}$/.test(command.name) && !seen.has(command.name) && seen.add(command.name)).slice(0, 1000)
1612
+ .map(command => ({ name: command.name, description: command.description.slice(0, 4096), ...(command.argumentHint ? { argumentHint: command.argumentHint.slice(0, 256) } : {}), kind: command.kind }));
1613
+ return { commands };
1614
+ } catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
1615
+ },
1616
+
1597
1617
  /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1598
1618
  async 'session.resumeCommand'(_connection, { sessionId }) {
1599
1619
  if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd has no resume command (capability session.resumeCommand is not listed)');
@@ -1882,7 +1902,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1882
1902
  }
1883
1903
 
1884
1904
  /** What this daemon lists in daemon.hello: only features it serves now (docs/protocol/alp-json-rpc-v1.md §6). */
1885
- 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];
1905
+ 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];
1886
1906
 
1887
1907
  /** A response too large for the wire becomes an error the client can read. */
1888
1908
  function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
@@ -3,9 +3,7 @@
3
3
  * There is no protection helper on Windows: closing a terminal kills its pty (node-pty `kill`),
4
4
  * which ends the shell; processes it started may keep running. Terminals report `protection: 'none'`.
5
5
  */
6
- import { existsSync } from 'node:fs';
7
6
  import { createRequire } from 'node:module';
8
- import path from 'node:path';
9
7
  import type { PtySpawn } from './terminals.js';
10
8
 
11
9
  type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
@@ -13,22 +11,11 @@ type NodePty = { spawn(file: string, args: string[], options: Record<string, unk
13
11
  onData(listener: (data: string) => void): { dispose(): void }; onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
14
12
  } };
15
13
 
16
- /**
17
- * In the ALP executable (t-1e02) node-pty is not in node_modules: the build embeds its JavaScript and
18
- * the win32 prebuilt (conpty.node, conpty/conpty.dll, OpenConsole.exe), extracted with the other
19
- * assets. registerPackaged publishes assetDir on globalThis; read it there so this adapter needs no package import.
20
- */
21
- function packagedNodePty(): string | undefined {
22
- const assets = (globalThis as { [key: symbol]: { assetDir?: () => string | undefined } | undefined })[Symbol.for('alp.packaged')]?.assetDir?.();
23
- const entry = assets ? path.join(assets, 'node-pty', 'lib', 'index.js') : undefined;
24
- return entry && existsSync(entry) ? entry : undefined;
25
- }
26
-
27
14
  let loaded: NodePty | null | undefined;
28
15
  /** node-pty, or undefined when it cannot load on this host. */
29
16
  export function loadNodePty(): NodePty | undefined {
30
17
  if (loaded === undefined) {
31
- try { loaded = createRequire(import.meta.url)(packagedNodePty() ?? 'node-pty') as NodePty; } catch { loaded = null; }
18
+ try { loaded = createRequire(import.meta.url)('node-pty') as NodePty; } catch { loaded = null; }
32
19
  }
33
20
  return loaded ?? undefined;
34
21
  }
@@ -47,11 +34,7 @@ export const windowsPtySpawn: PtySpawn = (file, args, options) => {
47
34
  if (options.signal?.aborted) throw new Error('Terminal startup cancelled');
48
35
  const pty = loadNodePty();
49
36
  if (!pty) throw new Error('node-pty is unavailable on this host');
50
- // The executable uses the conpty.dll and OpenConsole.exe it embeds: with the system ConPTY, node-pty's
51
- // kill() forks a console-list helper through process.execPath, which there is alp.exe (it would refuse
52
- // the script and leave node-pty waiting 5 s). With the DLL, kill() ends the session by closing input.
53
- const spawnOptions = { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true, ...(packagedNodePty() ? { useConptyDll: true } : {}) };
54
- const child = typeof process.versions.bun === 'string' ? spawnUnderBun(pty, file, args, spawnOptions) : pty.spawn(file, args, spawnOptions);
37
+ const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
55
38
  let killed = false;
56
39
  return {
57
40
  pid: child.pid,
@@ -64,60 +47,3 @@ export const windowsPtySpawn: PtySpawn = (file, args, options) => {
64
47
  };
65
48
  };
66
49
 
67
- /**
68
- * The ALP executable runs on Bun (t-1e02), where node-pty's input stream, `new net.Socket({ fd })`
69
- * around the fd it opens on ConPTY's input pipe, takes the fd but never writes to it (output, read
70
- * by a worker, works; probed on windows-2022 with Bun 1.4.2). While node-pty spawns (synchronously),
71
- * hand it a small writer for that fd instead: the same calls node-pty makes on its input socket
72
- * (setEncoding, write, destroy, readable), with writes in order through fs.write and the fd closed
73
- * once on destroy.
74
- */
75
- function spawnUnderBun(pty: NodePty, file: string, args: string[], options: Record<string, unknown>) {
76
- const load = createRequire(import.meta.url);
77
- const fs = load('node:fs') as typeof import('node:fs');
78
- const net = load('node:net') as { Socket: new (...args: unknown[]) => unknown };
79
- const Socket = net.Socket;
80
- function InputSocket(this: unknown, ...rest: unknown[]) {
81
- const [opts] = rest as [{ fd?: unknown; writable?: boolean; readable?: boolean } | undefined];
82
- if (opts && typeof opts.fd === 'number' && opts.writable === true && opts.readable === false) return fdWriter(fs, opts.fd);
83
- return new Socket(...rest);
84
- }
85
- InputSocket.prototype = Socket.prototype;
86
- net.Socket = InputSocket as unknown as typeof Socket;
87
- try { return pty.spawn(file, args, options); } finally { net.Socket = Socket; }
88
- }
89
-
90
- /** A write-only stand-in for net.Socket over a pipe fd: ordered writes, closed once; after a failed write it drops the rest. */
91
- function fdWriter(fs: typeof import('node:fs'), fd: number) {
92
- let queue: Promise<void> = Promise.resolve();
93
- let closed = false;
94
- let failed = false;
95
- const writer = {
96
- readable: false,
97
- writable: true,
98
- setEncoding() { return writer; },
99
- write(data: string | Uint8Array) {
100
- if (closed || failed) return false;
101
- const bytes = typeof data === 'string' ? Buffer.from(data, 'utf8') : Buffer.from(data);
102
- queue = queue.then(() => new Promise<void>(resolve => {
103
- const rest = (offset: number): void => {
104
- if (closed || failed || offset >= bytes.length) return resolve();
105
- fs.write(fd, bytes, offset, bytes.length - offset, null, (error, written) => {
106
- if (error) { failed = true; writer.writable = false; return resolve(); }
107
- rest(offset + written);
108
- });
109
- };
110
- rest(0);
111
- }));
112
- return true;
113
- },
114
- destroy() {
115
- if (closed) return writer;
116
- closed = true;
117
- writer.writable = false;
118
- void queue.then(() => fs.close(fd, () => {}));
119
- return writer;
120
- },
121
- };
122
- return writer;
123
- }