@anhlp/alp-daemon 0.0.0-beta.2 → 0.0.1-beta.10

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.
Files changed (104) hide show
  1. package/README.md +4 -0
  2. package/dist/THIRD-PARTY-NOTICES.txt +27 -2
  3. package/dist/alpd.js +39374 -17503
  4. package/dist/attachments.d.ts +187 -0
  5. package/dist/attachments.js +856 -0
  6. package/dist/build-manifest.json +41 -2
  7. package/dist/conversation.d.ts +119 -0
  8. package/dist/conversation.js +688 -0
  9. package/dist/disk.d.ts +67 -0
  10. package/dist/disk.js +152 -0
  11. package/dist/files.d.ts +156 -3
  12. package/dist/files.js +402 -59
  13. package/dist/git.d.ts +98 -0
  14. package/dist/git.js +1246 -0
  15. package/dist/gitignore.d.ts +5 -0
  16. package/dist/gitignore.js +26 -7
  17. package/dist/history.d.ts +24 -0
  18. package/dist/history.js +149 -0
  19. package/dist/index.d.ts +7 -0
  20. package/dist/index.js +21 -1
  21. package/dist/lifecycle.d.ts +101 -0
  22. package/dist/lifecycle.js +239 -0
  23. package/dist/main.js +146 -21
  24. package/dist/model-catalog.d.ts +2 -0
  25. package/dist/model-catalog.js +44 -0
  26. package/dist/native-entry.d.ts +2 -0
  27. package/dist/native-entry.js +3 -0
  28. package/dist/native-register.d.ts +1 -0
  29. package/dist/native-register.js +13 -0
  30. package/dist/native-terminal.d.ts +45 -0
  31. package/dist/native-terminal.js +201 -0
  32. package/dist/operations.d.ts +20 -3
  33. package/dist/operations.js +62 -21
  34. package/dist/registry.d.ts +89 -0
  35. package/dist/registry.js +343 -0
  36. package/dist/scheduler.d.ts +96 -0
  37. package/dist/scheduler.js +298 -0
  38. package/dist/schedules.d.ts +70 -0
  39. package/dist/schedules.js +246 -0
  40. package/dist/server.d.ts +14 -2
  41. package/dist/server.js +903 -97
  42. package/dist/store.d.ts +72 -2
  43. package/dist/store.js +111 -4
  44. package/dist/terminal-native/README.md +201 -0
  45. package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
  46. package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
  47. package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
  48. package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
  49. package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  50. package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  51. package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  52. package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  53. package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  54. package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  55. package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
  56. package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  57. package/dist/terminal-native/terminal-owner.c +389 -0
  58. package/dist/terminal-screen.d.ts +24 -0
  59. package/dist/terminal-screen.js +99 -0
  60. package/dist/terminals.d.ts +203 -0
  61. package/dist/terminals.js +570 -0
  62. package/dist/windows-terminal.d.ts +32 -0
  63. package/dist/windows-terminal.js +79 -0
  64. package/dist/worktrees.d.ts +65 -0
  65. package/dist/worktrees.js +318 -0
  66. package/native/README.md +201 -0
  67. package/native/prebuilt/darwin-arm64/manifest.json +11 -0
  68. package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
  69. package/native/prebuilt/darwin-x64/manifest.json +11 -0
  70. package/native/prebuilt/darwin-x64/terminal-owner +0 -0
  71. package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
  72. package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
  73. package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
  74. package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
  75. package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
  76. package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
  77. package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
  78. package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
  79. package/native/terminal-owner.c +389 -0
  80. package/package.json +71 -8
  81. package/src/attachments.ts +908 -0
  82. package/src/conversation.ts +857 -0
  83. package/src/disk.ts +175 -0
  84. package/src/files.ts +535 -71
  85. package/src/git.ts +1220 -0
  86. package/src/gitignore.ts +25 -8
  87. package/src/history.ts +118 -0
  88. package/src/index.ts +7 -0
  89. package/src/lifecycle.ts +283 -0
  90. package/src/main.ts +154 -23
  91. package/src/model-catalog.ts +36 -0
  92. package/src/native-entry.ts +5 -0
  93. package/src/native-register.ts +21 -0
  94. package/src/native-terminal.ts +127 -0
  95. package/src/operations.ts +53 -22
  96. package/src/registry.ts +238 -0
  97. package/src/scheduler.ts +438 -0
  98. package/src/schedules.ts +297 -0
  99. package/src/server.ts +1019 -109
  100. package/src/store.ts +117 -4
  101. package/src/terminal-screen.ts +74 -0
  102. package/src/terminals.ts +653 -0
  103. package/src/windows-terminal.ts +74 -0
  104. package/src/worktrees.ts +382 -0
package/src/main.ts CHANGED
@@ -1,18 +1,23 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { openSync, writeSync } from 'node:fs';
2
+ import { fstatSync, openSync, writeSync } from 'node:fs';
3
3
  import { mkdir, open, readFile, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import templates from 'alp:templates';
7
- import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION } from '@anhlp/alp-client/index';
8
- import { createAlpRuntime, reclaimCopies, reclaimWorktrees } from '@anhlp/alp-runtime/index';
7
+ import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION, withDaemonLifecycle } from '@anhlp/alp-client/index';
8
+ import { attachmentStageDir, createAlpRuntime, 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';
13
+ import { createDiskGuard, guardOutput, isDiskError } from './disk.js';
14
+ import { readAttachmentConfig } from './attachments.js';
12
15
  import { validateUserSettings } from '@anhlp/alp-core/validation';
13
16
  import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } from '@anhlp/alp-core/backup';
14
17
  import { migrateState } from '@anhlp/alp-core/migrations';
15
18
  import { createLogger } from '@anhlp/alp-core/log';
19
+ import { createModelCatalog } from './model-catalog.js';
20
+ import { selfCommand, selfEntry } from '@anhlp/alp-core/packaged';
16
21
 
17
22
  declare const __ALP_VERSION__: string;
18
23
  const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev';
@@ -20,6 +25,18 @@ const LOG_BYTES = 10 * 1024 * 1024;
20
25
  const LOG_FILES = 3;
21
26
  const log = createLogger({ component: 'alpd' });
22
27
 
28
+ /** Why reclaimWorktrees left a directory in $ALP_HOME/worktrees, for the `worktree.left` line. */
29
+ const LEFT_REASONS: Record<LeftWorktree['reason'], (entry: LeftWorktree) => string> = {
30
+ invalid: () => 'it is not a working git worktree (its git metadata is missing or broken)',
31
+ 'not-linked': () => 'it is a git repository of its own, not a worktree of one',
32
+ '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',
33
+ 'commit-failed': entry => `its work could not be committed${entry.detail ? ` (${entry.detail})` : ''}`,
34
+ uncommitted: () => 'it still has changes that are not committed',
35
+ 'ignored-files': entry => entry.files?.length
36
+ ? `its work is committed to ${entry.branch}, but it holds ignored files that exist nowhere else: ${entry.files.join(', ')}`
37
+ : `its ignored files could not be checked${entry.detail ? ` (${entry.detail})` : ''}`,
38
+ };
39
+
23
40
  async function rotate(log: string) {
24
41
  const size = await stat(log).then(info => info.size, () => 0);
25
42
  if (size < LOG_BYTES) return;
@@ -28,21 +45,62 @@ async function rotate(log: string) {
28
45
  }
29
46
  }
30
47
 
31
- /** Starts the daemon in a new session and returns at once, so it is not part of the caller's process tree. */
48
+ /** What a detached alpd that failed to start tells its launcher over IPC. */
49
+ type StartupFailure = { code: string; message: string };
50
+
51
+ /** alpd failed to start and said why; the launcher reports it with alpd's own code. */
52
+ class ChildStartupError extends Error {
53
+ constructor(readonly failure: StartupFailure, exit: number | string | null) {
54
+ super(`alpd exited during startup (${exit}): ${failure.message}`);
55
+ }
56
+ }
57
+
58
+ /** The launcher owns its detached child until that child acknowledges readiness or exits.
59
+ * A ready lock belonging to some other process cannot settle this launch.
60
+ */
32
61
  async function detach(home: string) {
33
62
  await assertPrivateDirectory(home, { create: true });
34
63
  const { log } = daemonPaths(home);
35
64
  await assertPrivateDirectory(path.dirname(log), { create: true });
36
65
  await rotate(log);
37
66
  const output = await open(log, 'a', 0o600);
38
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
67
+ const self = selfCommand('daemon', { script: fileURLToPath(import.meta.url) });
68
+ const child = spawn(self.command, self.args, {
39
69
  detached: true,
40
- stdio: ['ignore', output.fd, output.fd],
70
+ stdio: ['ignore', output.fd, output.fd, 'ipc'],
41
71
  env: process.env,
42
72
  windowsHide: true,
43
73
  });
44
- child.unref();
45
74
  await output.close();
75
+ await new Promise<void>((resolve, reject) => {
76
+ const requested = Number(process.argv.find(arg => arg.startsWith('--startup-timeout='))?.split('=')[1]);
77
+ const timeoutMs = Number.isFinite(requested) && requested > 0 ? requested : 15_000;
78
+ let timedOut = false;
79
+ let force: ReturnType<typeof setTimeout> | undefined;
80
+ const timer = setTimeout(() => {
81
+ timedOut = true;
82
+ child.kill();
83
+ force = setTimeout(() => child.kill('SIGKILL'), 1_000);
84
+ }, timeoutMs);
85
+ child.once('error', error => { clearTimeout(timer); clearTimeout(force); reject(error); });
86
+ // Why alpd failed, from alpd itself: on a full disk its log line may never reach the log.
87
+ let failed: StartupFailure | undefined;
88
+ child.once('exit', (code, signal) => {
89
+ clearTimeout(timer);
90
+ clearTimeout(force);
91
+ reject(timedOut ? new Error(`alpd startup timed out after ${timeoutMs} ms`)
92
+ : failed ? new ChildStartupError(failed, code ?? signal)
93
+ : new Error(`alpd exited during startup (${code ?? signal})`));
94
+ });
95
+ child.on('message', (message: any) => {
96
+ if (message?.type === 'alpd.failed' && typeof message.code === 'string' && typeof message.message === 'string') { failed = { code: message.code, message: message.message }; return; }
97
+ if (message !== 'alpd.ready' || timedOut) return;
98
+ clearTimeout(timer);
99
+ child.disconnect();
100
+ child.unref();
101
+ resolve();
102
+ });
103
+ });
46
104
  }
47
105
 
48
106
  /**
@@ -50,7 +108,7 @@ async function detach(home: string) {
50
108
  * log at start as the detached launcher does, then writes its output there itself. The
51
109
  * manager's own file keeps only what Node prints when it dies.
52
110
  */
53
- async function serviceLog(home: string) {
111
+ async function serviceLog(home: string, onError: (error: unknown) => void) {
54
112
  await assertPrivateDirectory(home, { create: true });
55
113
  const { log } = daemonPaths(home);
56
114
  await assertPrivateDirectory(path.dirname(log), { create: true });
@@ -58,7 +116,7 @@ async function serviceLog(home: string) {
58
116
  const fd = openSync(log, 'a', 0o600);
59
117
  for (const stream of [process.stdout, process.stderr]) {
60
118
  stream.write = ((chunk: string | Uint8Array, encoding?: unknown, callback?: unknown) => {
61
- try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch {}
119
+ try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch (error) { onError(error); }
62
120
  const done = typeof encoding === 'function' ? encoding : callback;
63
121
  if (typeof done === 'function') done();
64
122
  return true;
@@ -172,29 +230,51 @@ async function run(home: string) {
172
230
  await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), groupLeader: leadsGroup() }), { mode: 0o600 });
173
231
  const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
174
232
  const worktreeDir = path.join(home, 'worktrees');
175
- // Worktrees of assignments a crash interrupted: their work goes to their branches.
176
- for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
233
+ // Worktrees of assignments a crash interrupted: their work goes to their branches. What
234
+ // reclaim leaves in place stays in $ALP_HOME/worktrees until the user looks: say where and why.
235
+ const reclaimed = await reclaimWorktrees(worktreeDir).catch(() => ({ kept: [] as string[], left: [] }));
236
+ for (const branch of reclaimed.kept) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
237
+ for (const entry of reclaimed.left) {
238
+ log.warn(`left worktree ${entry.path} in place: ${LEFT_REASONS[entry.reason](entry)}`, {
239
+ event: 'worktree.left', path: entry.path, reason: entry.reason,
240
+ ...(entry.branch ? { branch: entry.branch } : {}), ...(entry.detail ? { detail: entry.detail } : {}), ...(entry.files ? { files: entry.files } : {}),
241
+ });
242
+ }
177
243
  // Review copies of interrupted assignments hold nothing to keep.
178
244
  const copyDir = path.join(home, 'copies');
179
245
  await reclaimCopies(copyDir).catch(() => 0);
180
- // A hold (ALPD §40) only means something while alpd is stopped.
181
- await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
246
+ // Requested starts lift the existing hold before launching. Never erase a stop
247
+ // published while this daemon was starting.
182
248
  const settings = await userSettings(home);
183
249
  const runtime = createAlpRuntime({
184
250
  templates, runLogDir, worktreeDir, copyDir, boardDir: path.join(home, 'boards'), libraryDir: home,
185
- recallFile: path.join(home, 'state', 'recall.json'), pauseFile: path.join(home, 'state', 'pause.json'), liveFile: path.join(home, 'state', 'live.json'),
251
+ // Read-only copies of attached files for the sessions' tools (§12.6); not on Windows, as the store.
252
+ ...(process.platform !== 'win32' ? { attachmentStageDir: attachmentStageDir(home) } : {}),
253
+ assignmentResultFile: path.join(home, 'state', 'assignment-results.json'), recallFile: path.join(home, 'state', 'recall.json'), pauseFile: path.join(home, 'state', 'pause.json'), liveFile: path.join(home, 'state', 'live.json'),
186
254
  autoResume: settings?.limits?.autoResume !== false, recoveryResume: settings?.recovery?.autoResume !== false && !opened.restored, previousExit: exit,
255
+ // Pause, live, recall and result writes the disk refused hold work at once, not at the next check (t-e80a).
256
+ onWriteError: error => diskReport(error),
187
257
  });
188
- const store = createStore(path.join(home, 'state'));
258
+ // A full disk pauses ALP's work instead of stopping alpd (t-2831).
259
+ const disk = createDiskGuard({ home, runtime, log, ...(Number(process.env.ALP_DISK_CHECK_MS) > 0 ? { intervalMs: Number(process.env.ALP_DISK_CHECK_MS) } : {}) });
260
+ diskReport = error => { disk.report(error); };
261
+ const store = createStore(path.join(home, 'state'), { onWriteError: error => { disk.report(error); } });
189
262
  let stopping: Promise<void> | undefined;
190
263
  const shutdown = (code = 0) => {
191
264
  stopping ??= (async () => {
192
265
  const force = setTimeout(() => process.exit(code), 10_000);
193
266
  force.unref();
194
267
  clearInterval(beat);
268
+ disk.stop();
269
+ // Stops the timer and listeners now; its promise settles once the cache writes under way are done.
270
+ const catalogStopped = modelCatalog?.stop().catch(() => {});
195
271
  await server.close().catch(() => {});
196
272
  await runtime.shutdown().catch(() => {});
197
273
  await store.flush();
274
+ // Before the lock goes, so the next alpd never writes the cache beside this one (t-5294.2). Bounded:
275
+ // stop() also waits for a provider probe under way. Past 2 s alpd stops anyway; the write is a
276
+ // temporary file and a rename, so the cache keeps its previous content and a stray .tmp may remain.
277
+ if (catalogStopped) await Promise.race([catalogStopped, new Promise(resolve => setTimeout(resolve, 2_000).unref())]);
198
278
  // Last: what remains is a clean stop.
199
279
  await unlink(marker).catch(() => {});
200
280
  await releaseLock(home);
@@ -203,7 +283,17 @@ async function run(home: string) {
203
283
  })();
204
284
  return stopping;
205
285
  };
206
- const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, home, templates, onShutdown: () => void shutdown() });
286
+ // The operator may lower the attachment limits (never raise them): <ALP_HOME>/attachments.json.
287
+ const attachmentConfig = await readAttachmentConfig(home);
288
+ for (const problem of attachmentConfig.problems) log.warn(problem, { code: 'ALP_ATTACHMENT_CONFIG' });
289
+ // The live model catalog (t-e5ee): static rows at once, provider lists in the background, every 6 h.
290
+ // ALP_MODEL_CATALOG=static keeps the static rows only (tests, offline hosts).
291
+ // ACP providers (t-d0b0) are listed from providers/<id>.json without starting any; one is probed only on
292
+ // catalog.refresh or when the user enables it, and learns its models from its first session otherwise.
293
+ const modelCatalog = process.env.ALP_MODEL_CATALOG === 'static' ? undefined : createModelCatalog(home);
294
+ setActiveCatalog(modelCatalog);
295
+ void modelCatalog?.start().catch(() => {});
296
+ const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, home, templates, attachmentOptions: { limits: attachmentConfig.limits }, modelCatalog, onShutdown: () => void shutdown() });
207
297
  const beat = setInterval(() => {
208
298
  void heartbeat(home).then(owned => { if (!owned) void shutdown(1); });
209
299
  const now = new Date();
@@ -211,8 +301,9 @@ async function run(home: string) {
211
301
  }, 30_000);
212
302
  beat.unref();
213
303
  for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
214
- process.on('uncaughtException', error => { log.error('uncaught exception; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
215
- process.on('unhandledRejection', error => { log.error('unhandled rejection; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
304
+ // A write the disk refused is no reason to stop: the disk guard pauses work until it takes writes again.
305
+ process.on('uncaughtException', error => { if (disk.report(error)) return; log.error('uncaught exception; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
306
+ process.on('unhandledRejection', error => { if (disk.report(error)) return; log.error('unhandled rejection; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
216
307
  phase = 'listen';
217
308
  try {
218
309
  await server.listen();
@@ -225,26 +316,66 @@ async function run(home: string) {
225
316
  await updateLock(home, { ...lock, ready: true });
226
317
  // Clients that cannot locate alpd themselves (the Paseo plugin) start it from here next time.
227
318
  const { install } = daemonPaths(home);
228
- await writeFile(`${install}.tmp`, JSON.stringify({ entry: fileURLToPath(import.meta.url), version: VERSION }), { mode: 0o600 })
319
+ await writeFile(`${install}.tmp`, JSON.stringify({ entry: selfEntry(fileURLToPath(import.meta.url)), version: VERSION }), { mode: 0o600 })
229
320
  .then(() => rename(`${install}.tmp`, install))
230
321
  .catch(error => log.warn('could not record alpd\'s location', { code: 'ALP_INSTALL_RECORD_FAILED', error }));
231
322
  if (opened.restored) await clearRestoredMarker(home).catch(error => log.warn('could not clear the restore marker', { code: 'ALP_STATE_RESTORED', error }));
323
+ disk.start();
324
+ if (process.connected) process.send?.('alpd.ready');
232
325
  log.info(`alpd ${VERSION} ready on ${socket} (pid ${process.pid})`, { event: 'ready', version: VERSION, pid: process.pid });
233
326
  }
234
327
 
328
+ /** Why a start-up write failed on a disk that takes none, and what helps. */
329
+ function diskStartupReason(error: any, home: string) {
330
+ let current = error;
331
+ for (let depth = 0; current && depth < 4 && !['ENOSPC', 'EDQUOT', 'EROFS'].includes(current.code); depth++) current = current.cause;
332
+ const what = current?.code === 'EROFS' ? 'the disk is read-only' : current?.code === 'EDQUOT' ? 'the disk quota is used up' : 'the disk is full';
333
+ return `${what} (${current?.code}${current?.path ? ` writing ${current.path}` : ''}); free space on the disk that holds ${home}, then start alpd again`;
334
+ }
335
+
235
336
  const home = alpHome();
337
+ /** Where a failed write to alpd's own output goes once the disk guard exists. */
338
+ let diskReport = (_error: unknown) => {};
339
+ // Before anything logs: a log write the full disk refused must not end alpd (t-2831).
340
+ guardOutput(error => { if (isDiskError(error)) diskReport(error); }, { fstatSync, writeSync });
236
341
  try {
237
342
  if (process.argv.includes('--detach')) await detach(home);
238
343
  else {
239
- if (process.argv.includes('--service')) await serviceLog(home);
240
- await run(home);
344
+ // A direct foreground/login invocation is an explicit start. Do this before
345
+ // admission registration, so a stop published during startup is preserved.
346
+ if (!process.connected) await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
347
+ if (process.argv.includes('--service')) await serviceLog(home, error => { if (isDiskError(error)) diskReport(error); });
348
+ if (process.connected) await run(home);
349
+ else {
350
+ // Retain admission through readiness even if the requesting service client
351
+ // times out. An invocation without a requester (including login) is explicit.
352
+ await withDaemonLifecycle(home, 'start', async () => {
353
+ await run(home);
354
+ }, { joinStart: true });
355
+ }
241
356
  }
242
357
  } catch (error: any) {
358
+ // The launcher of a detached alpd that failed: alpd's own reason and code, which its log may lack.
359
+ if (error instanceof ChildStartupError) {
360
+ log.error(error.message, { code: error.failure.code, phase: 'home' });
361
+ process.exit(1);
362
+ }
243
363
  // The log says where start-up stopped; alp doctor reads it from there.
244
364
  const stoppedIn = phase as Phase;
365
+ // A full disk is named as such (t-e80a): alpd cannot take its lock or write its marker, and
366
+ // nothing but freeing space helps. The lock stays exclusive; alpd only says why it stopped.
367
+ const disk = isDiskError(error);
245
368
  // Opening the state fails with the state's own code (a newer schema, a failed migration).
246
- const code = /already running|ALP is busy/.test(error?.message ?? '') ? 'ALP_LOCK_HELD'
369
+ const code = disk ? 'ALP_DISK_FULL'
370
+ : /already running|ALP is busy/.test(error?.message ?? '') ? 'ALP_LOCK_HELD'
247
371
  : stoppedIn === 'state' && typeof error?.code === 'string' && /^[A-Z_]+$/.test(error.code) ? `ALP_${error.code}` : STARTUP_CODES[stoppedIn];
248
- log.error(`alpd failed to start while ${{ home: 'preparing its home', lock: 'taking its lock', state: 'opening its state', recovery: 'recovering earlier work', listen: 'opening its IPC endpoint', ready: 'finishing start-up' }[stoppedIn]}${stoppedIn === 'state' ? `: ${error?.message ?? error}` : ''}`, { code, phase: stoppedIn, error });
372
+ const step = { home: 'preparing its home', lock: 'taking its lock', state: 'opening its state', recovery: 'recovering earlier work', listen: 'opening its IPC endpoint', ready: 'finishing start-up' }[stoppedIn];
373
+ const message = `alpd failed to start while ${step}${disk ? `: ${diskStartupReason(error, home)}` : stoppedIn === 'state' ? `: ${error?.message ?? error}` : ''}`;
374
+ log.error(message, { code, phase: stoppedIn, error });
375
+ // A detached alpd tells its launcher too, which passes it to the client that started it.
376
+ if (process.connected) await new Promise<void>(resolve => {
377
+ const timer = setTimeout(resolve, 1_000);
378
+ try { process.send!({ type: 'alpd.failed', code, message }, () => { clearTimeout(timer); resolve(); }); } catch { clearTimeout(timer); resolve(); }
379
+ });
249
380
  process.exit(1);
250
381
  }
@@ -0,0 +1,36 @@
1
+ /** Production catalog wiring, shared with daemon integration tests. No model prompts. */
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
+
9
+ export function createModelCatalog(home: string, warn: (message: string) => void = console.error) {
10
+ let warnings = new Set<string>();
11
+ const probes = liveProbes();
12
+ probes.antigravity = async signal => {
13
+ const provider = await loadProvider(home, 'antigravity');
14
+ if (provider?.enabled === false) return [];
15
+ return antigravityProbe(provider?.command, { ...process.env, ...provider?.env }, provider?.args)(signal);
16
+ };
17
+ return new ModelCatalog({ home, probes,
18
+ acpProviders: async () => {
19
+ const errors: string[] = [];
20
+ const current = new Set<string>();
21
+ const providers = await listProviders(home, { onError: (error: unknown, name: string) => {
22
+ const message = `skipping provider ${name}: ${error instanceof Error ? error.message : String(error)}`;
23
+ errors.push(message); current.add(message);
24
+ if (!warnings.has(message)) warn(`alpd: ${message}`);
25
+ } });
26
+ warnings = current;
27
+ return { providers, ...(errors.length ? { error: errors.join('\n') } : {}) };
28
+ },
29
+ acpProbe: async (provider, signal) => {
30
+ signal.throwIfAborted();
31
+ const cwd = await mkdtemp(path.join(os.tmpdir(), 'alp-model-probe-'));
32
+ try { return (await probeAcp(provider as Parameters<typeof probeAcp>[0], { cwd, signal, discover: true, timeoutMs: 15_000 })).models ?? []; }
33
+ finally { await rm(cwd, { recursive: true, force: true }); }
34
+ },
35
+ });
36
+ }
@@ -0,0 +1,5 @@
1
+ // Entry of the native alpd (t-81b0.9): `bun build --compile` of this file is `<bundle>/bin/alpd`
2
+ // (scripts/build-alpd-native.mjs). The registration must load before alpd: ES modules evaluate in
3
+ // import order.
4
+ import './native-register.js';
5
+ import './main.js';
@@ -0,0 +1,21 @@
1
+ // The native alpd (t-81b0.9, scripts/build-alpd-native.mjs): registers this process as the native
2
+ // alpd before alpd's own modules load (native-entry.ts imports this first). The Claude Agent SDK is
3
+ // imported here by its literal name so the build embeds it in the executable; claude-transport.ts
4
+ // reaches it through this registration instead of its computed import.
5
+ import { bundleDist, bundleInfo, registerNativeDaemon } from '@anhlp/alp-core/packaged';
6
+
7
+ declare const __ALP_VERSION__: string;
8
+ // `alpd --version` answers before alpd loads, so install.sh, alp update and the build can check that this
9
+ // executable runs on the machine without starting a daemon.
10
+ if (process.argv.length === 3 && process.argv[2] === '--version') {
11
+ process.stdout.write(`${typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev'}\n`);
12
+ process.exit(0);
13
+ }
14
+ // The bundle is read once at start: a later reinstall of the same version moves this directory aside.
15
+ const bundle = bundleInfo();
16
+
17
+ registerNativeDaemon({
18
+ modules: { claudeAgentSdk: () => import('@anthropic-ai/claude-agent-sdk') },
19
+ // The terminal helper (native-terminal.ts) lies in the bundle's @anhlp/alp-cli dist, not beside alpd.
20
+ distDir: () => bundle ? bundleDist(bundle) : undefined,
21
+ });
@@ -0,0 +1,127 @@
1
+ /** Identity-bound native PTY owner; shipped helper only, never runtime compilation. */
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { existsSync, readFileSync, statSync } from 'node:fs';
5
+ import { fileURLToPath } from 'node:url';
6
+ import path from 'node:path';
7
+ import { StringDecoder } from 'node:string_decoder';
8
+ export type CleanupResult = { observed: number; live: number; uncertain: number; coverage?: 'root-only'; outputOpen?: boolean };
9
+ type Exit = { exitCode: number | null; signal?: number };
10
+ type Listener<T> = (event: T) => void;
11
+ const sha = (value: Buffer) => createHash('sha256').update(value).digest('hex');
12
+ function binary() {
13
+ const libc = process.platform === 'linux' ? (process.report?.getReport() as { header?: { glibcVersionRuntime?: string } })?.header?.glibcVersionRuntime ? 'glibc' : 'musl' : undefined;
14
+ const slot = [process.platform, process.arch, libc].filter(Boolean).join('-');
15
+ // The native alpd (t-81b0.9) has no directory of its own (import.meta.url is inside its executable):
16
+ // it uses the helper in its bundle's @anhlp/alp-cli dist; outside a bundle it has none.
17
+ // This file stays self-contained (it is shipped and tested on its own), so it reads the native alpd's
18
+ // registration (@anhlp/alp-core/packaged, native-register.ts) from its global directly.
19
+ const native = (globalThis as { [key: symbol]: { distDir?: () => string | undefined } | undefined })[Symbol.for('alp.nativeDaemon')];
20
+ const bundled = native?.distDir?.();
21
+ if (native && !bundled) throw new Error('The native alpd runs outside an ALP bundle: no terminal helper');
22
+ const here = bundled ?? path.dirname(fileURLToPath(import.meta.url));
23
+ const adjacent = path.join(here, 'terminal-native');
24
+ const dir = existsSync(adjacent) || bundled ? adjacent : path.resolve(here, '../native');
25
+ const file = path.join(dir, 'prebuilt', slot, 'terminal-owner');
26
+ const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), 'manifest.json'), 'utf8'));
27
+ 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');
28
+ return file;
29
+ }
30
+ /** Only an authenticated helper's exact capability record can select compatibility. */
31
+ export function nativeCapabilityOf(probe: { status: number | null; stdout: string }, platform: NodeJS.Platform): { available: boolean; protection?: 'root-only'; reason?: string } {
32
+ if (probe.status === 0 && probe.stdout.trim() === 'alp-terminal-owner:1') return { available: true };
33
+ if (platform === 'linux' && probe.status === 0 && probe.stdout.trim() === 'alp-terminal-owner:1:root-only') return { available: true, protection: 'root-only', reason: 'bound_signal_unavailable' };
34
+ return { available: false, reason: 'native_capability_unavailable' };
35
+ }
36
+ export function nativeTerminalCapability(): ReturnType<typeof nativeCapabilityOf> {
37
+ try {
38
+ const probe = spawnSync(binary(), ['--capability'], { encoding: 'utf8', timeout: 2_000, maxBuffer: 4096 });
39
+ return nativeCapabilityOf(probe, process.platform);
40
+ } catch { return { available: false, reason: 'native_prebuilt_unavailable' }; }
41
+ }
42
+ export async function nativePtySpawn(file: string, args: string[], options: { name: string; cols: number; rows: number; cwd: string; env: Record<string, string>; killGraceMs?: number; signal?: AbortSignal; protection?: 'root-only' | 'none' }) {
43
+ if (options.signal?.aborted) throw new Error('Native terminal startup cancelled');
44
+ const child = spawn(binary(), [...(options.protection === 'root-only' ? ['--root-only'] : []), String(options.cols), String(options.rows), String(options.killGraceMs ?? 1000), options.cwd, file, ...args], { env: options.env, stdio: ['pipe', 'pipe', 'pipe', 'pipe', 'pipe'] });
45
+ const control = child.stdio[4] as import('node:stream').Writable;
46
+ const events = child.stdio[3] as import('node:stream').Readable;
47
+ const data = new Set<Listener<string>>(), exits = new Set<Listener<Exit>>();
48
+ const decoder = new StringDecoder('utf8'); let buffered = '', protocol = '', exit: Exit | undefined, pid = 0;
49
+ let readyResolve!: () => void, readyReject!: (error: Error) => void, finish!: (result: CleanupResult) => void;
50
+ const ready = new Promise<void>((resolve, reject) => { readyResolve = resolve; readyReject = reject; });
51
+ const finished = new Promise<CleanupResult>(resolve => { finish = resolve; });
52
+ let result: CleanupResult | undefined, completed = false, closing = false, adapterFailed = false;
53
+ let controlBlocked = false, pendingResize: string | undefined;
54
+ const resizeCommand = (command: string) => {
55
+ if (closing || result) return;
56
+ if (controlBlocked) { pendingResize = command; return; }
57
+ controlBlocked = !control.write(command);
58
+ };
59
+ control.on('drain', () => {
60
+ controlBlocked = false;
61
+ const next = pendingResize; pendingResize = undefined;
62
+ if (next) resizeCommand(next);
63
+ });
64
+ const closeOwner = () => {
65
+ if (closing || result) return;
66
+ closing = true; pendingResize = undefined;
67
+ // No queue of resizes can stand ahead of cleanup: closing fd4 wakes native POLLHUP.
68
+ control.destroy(); child.stdin?.end();
69
+ };
70
+ const fail = (reason: string) => {
71
+ adapterFailed = true;
72
+ readyReject(new Error(reason));
73
+ // No bare child PID signaling. Closing owner input/control asks native bound cleanup.
74
+ closeOwner();
75
+ };
76
+ const timer = setTimeout(() => fail('Native terminal startup timed out'), 5000);
77
+ const complete = (value: CleanupResult) => { if (!completed) { completed = true; result = adapterFailed ? { ...value, uncertain: Math.max(1, value.uncertain) } : value; finish(result); } };
78
+ child.on('error', error => { fail(error.message); complete({ observed: 0, live: 0, uncertain: 1 }); });
79
+ child.on('close', () => {
80
+ clearTimeout(timer);
81
+ if (!pid) readyReject(new Error('Native terminal refused startup'));
82
+ // close follows every stdio end: service exit disposal cannot discard trailing PTY output.
83
+ exit ??= { exitCode: null };
84
+ for (const listener of exits) listener(exit);
85
+ complete(result ?? { observed: 0, live: 0, uncertain: 1 });
86
+ });
87
+ child.stderr?.resume();
88
+ // Pipes may fail after native exit. Native protocol/close supplies the authoritative outcome.
89
+ child.stdin?.on('error', () => {}); control.on('error', () => {});
90
+ child.stdout?.on('data', (chunk: Buffer) => {
91
+ const text = decoder.write(chunk);
92
+ if (data.size) for (const listener of data) listener(text);
93
+ else if (Buffer.byteLength(buffered) + Buffer.byteLength(text) <= 1024*1024) buffered += text;
94
+ else fail('Native terminal output limit exceeded');
95
+ });
96
+ events.on('data', (chunk: Buffer) => {
97
+ protocol += chunk.toString('utf8');
98
+ if (protocol.length > 8192) { fail('Invalid native protocol'); return; }
99
+ let newline;
100
+ while ((newline = protocol.indexOf('\n')) >= 0) {
101
+ const line = protocol.slice(0, newline); protocol = protocol.slice(newline + 1);
102
+ try {
103
+ const value = JSON.parse(line);
104
+ if (value.ready && value.protocol === 1 && Number.isSafeInteger(value.ready) && value.ready > 1) { pid = value.ready; clearTimeout(timer); readyResolve(); }
105
+ else if ('exitCode' in value) { exit = { exitCode: value.exitCode, signal: value.signal }; }
106
+ else if (value.cleanup === true && ['observed', 'live', 'uncertain'].every(key => Number.isSafeInteger(value[key]) && value[key] >= 0)) result = value;
107
+ else if (value.refused === 'terminal_protection_ack_required' || value.refused === 'terminal_unsupported') { readyReject(Object.assign(new Error('Native terminal capability changed before startup'), { terminalReason: value.refused })); }
108
+ else if (value.error) fail(String(value.error));
109
+ else fail('Invalid native event');
110
+ } catch { fail('Invalid native JSON'); }
111
+ }
112
+ });
113
+ const abort = () => fail('Native terminal startup cancelled');
114
+ options.signal?.addEventListener('abort', abort, { once: true });
115
+ if (options.signal?.aborted) abort();
116
+ try { await ready; } catch (error) { const cleanupResult = await finished; throw Object.assign(error instanceof Error ? error : new Error(String(error)), { cleanupResult }); }
117
+ finally { options.signal?.removeEventListener('abort', abort); }
118
+ return {
119
+ pid,
120
+ write(value: string) { if (closing || result) return; if ((child.stdin?.writableLength ?? 0) + Buffer.byteLength(value) > 1024*1024) { fail('Native input limit exceeded'); return; } child.stdin?.write(value); },
121
+ resize(cols: number, rows: number) { if (Number.isInteger(cols) && Number.isInteger(rows) && cols > 0 && cols <= 1000 && rows > 0 && rows <= 1000) resizeCommand(`R ${cols} ${rows}\n`); },
122
+ kill() { closeOwner(); },
123
+ cleanup() { closeOwner(); return finished; },
124
+ onData(listener: Listener<string>) { data.add(listener); if (buffered) { const value = buffered; buffered = ''; queueMicrotask(() => { if (data.has(listener)) listener(value); }); } return { dispose() { data.delete(listener); } }; },
125
+ onExit(listener: Listener<Exit>) { exits.add(listener); if (exit && completed) { const value = exit; queueMicrotask(() => { if (exits.has(listener)) listener(value); }); } return { dispose() { exits.delete(listener); } }; },
126
+ };
127
+ }