@anhlp/alp-daemon 0.0.0-stage → 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.
- package/LICENSE +202 -0
- package/NOTICE +7 -0
- package/README.md +14 -2
- package/dist/THIRD-PARTY-NOTICES.txt +456 -0
- package/dist/alp-templates.d.ts +5 -0
- package/dist/alpd.js +64050 -0
- package/dist/attachments.d.ts +187 -0
- package/dist/attachments.js +856 -0
- package/dist/build-manifest.json +150 -0
- package/dist/conversation.d.ts +119 -0
- package/dist/conversation.js +688 -0
- package/dist/disk.d.ts +67 -0
- package/dist/disk.js +152 -0
- package/dist/files.d.ts +262 -0
- package/dist/files.js +674 -0
- package/dist/git.d.ts +98 -0
- package/dist/git.js +1246 -0
- package/dist/gitignore.d.ts +62 -0
- package/dist/gitignore.js +254 -0
- package/dist/history.d.ts +24 -0
- package/dist/history.js +149 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +28 -0
- package/dist/lifecycle.d.ts +101 -0
- package/dist/lifecycle.js +239 -0
- package/dist/lock.d.ts +21 -0
- package/dist/lock.js +42 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +363 -0
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +44 -0
- package/dist/native-entry.d.ts +2 -0
- package/dist/native-entry.js +3 -0
- package/dist/native-register.d.ts +1 -0
- package/dist/native-register.js +13 -0
- package/dist/native-terminal.d.ts +45 -0
- package/dist/native-terminal.js +201 -0
- package/dist/operations.d.ts +40 -0
- package/dist/operations.js +313 -0
- package/dist/registry.d.ts +89 -0
- package/dist/registry.js +343 -0
- package/dist/rpc-error.d.ts +6 -0
- package/dist/rpc-error.js +11 -0
- package/dist/scheduler.d.ts +96 -0
- package/dist/scheduler.js +298 -0
- package/dist/schedules.d.ts +70 -0
- package/dist/schedules.js +246 -0
- package/dist/server.d.ts +60 -0
- package/dist/server.js +1958 -0
- package/dist/store.d.ts +178 -0
- package/dist/store.js +386 -0
- package/dist/terminal-native/README.md +201 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/darwin-x64/manifest.json +11 -0
- package/dist/terminal-native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/dist/terminal-native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/dist/terminal-native/terminal-owner.c +389 -0
- package/dist/terminal-screen.d.ts +24 -0
- package/dist/terminal-screen.js +99 -0
- package/dist/terminals.d.ts +203 -0
- package/dist/terminals.js +570 -0
- package/dist/windows-terminal.d.ts +32 -0
- package/dist/windows-terminal.js +79 -0
- package/dist/worktrees.d.ts +65 -0
- package/dist/worktrees.js +318 -0
- package/native/README.md +201 -0
- package/native/prebuilt/darwin-arm64/manifest.json +11 -0
- package/native/prebuilt/darwin-arm64/terminal-owner +0 -0
- package/native/prebuilt/darwin-x64/manifest.json +11 -0
- package/native/prebuilt/darwin-x64/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-arm64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-arm64-musl/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-glibc/manifest.json +10 -0
- package/native/prebuilt/linux-x64-glibc/terminal-owner +0 -0
- package/native/prebuilt/linux-x64-musl/manifest.json +10 -0
- package/native/prebuilt/linux-x64-musl/terminal-owner +0 -0
- package/native/terminal-owner.c +389 -0
- package/package.json +163 -4
- package/src/alp-templates.d.ts +5 -0
- package/src/attachments.ts +908 -0
- package/src/conversation.ts +857 -0
- package/src/disk.ts +175 -0
- package/src/files.ts +884 -0
- package/src/git.ts +1220 -0
- package/src/gitignore.ts +277 -0
- package/src/history.ts +118 -0
- package/src/index.ts +12 -0
- package/src/lifecycle.ts +283 -0
- package/src/lock.ts +53 -0
- package/src/main.ts +381 -0
- package/src/model-catalog.ts +36 -0
- package/src/native-entry.ts +5 -0
- package/src/native-register.ts +21 -0
- package/src/native-terminal.ts +127 -0
- package/src/operations.ts +329 -0
- package/src/registry.ts +238 -0
- package/src/rpc-error.ts +4 -0
- package/src/scheduler.ts +438 -0
- package/src/schedules.ts +297 -0
- package/src/server.ts +2238 -0
- package/src/store.ts +449 -0
- package/src/terminal-screen.ts +74 -0
- package/src/terminals.ts +653 -0
- package/src/windows-terminal.ts +74 -0
- package/src/worktrees.ts +382 -0
package/src/main.ts
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { fstatSync, openSync, writeSync } from 'node:fs';
|
|
3
|
+
import { mkdir, open, readFile, rename, stat, unlink, utimes, writeFile } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import templates from 'alp:templates';
|
|
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';
|
|
10
|
+
import { createDaemonServer } from './server.js';
|
|
11
|
+
import { acquireLock, heartbeat, releaseLock, updateLock } from './lock.js';
|
|
12
|
+
import { createStore } from './store.js';
|
|
13
|
+
import { createDiskGuard, guardOutput, isDiskError } from './disk.js';
|
|
14
|
+
import { readAttachmentConfig } from './attachments.js';
|
|
15
|
+
import { validateUserSettings } from '@anhlp/alp-core/validation';
|
|
16
|
+
import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } from '@anhlp/alp-core/backup';
|
|
17
|
+
import { migrateState } from '@anhlp/alp-core/migrations';
|
|
18
|
+
import { createLogger } from '@anhlp/alp-core/log';
|
|
19
|
+
import { createModelCatalog } from './model-catalog.js';
|
|
20
|
+
import { selfCommand, selfEntry } from '@anhlp/alp-core/packaged';
|
|
21
|
+
|
|
22
|
+
declare const __ALP_VERSION__: string;
|
|
23
|
+
const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev';
|
|
24
|
+
const LOG_BYTES = 10 * 1024 * 1024;
|
|
25
|
+
const LOG_FILES = 3;
|
|
26
|
+
const log = createLogger({ component: 'alpd' });
|
|
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
|
+
|
|
40
|
+
async function rotate(log: string) {
|
|
41
|
+
const size = await stat(log).then(info => info.size, () => 0);
|
|
42
|
+
if (size < LOG_BYTES) return;
|
|
43
|
+
for (let index = LOG_FILES - 1; index >= 1; index--) {
|
|
44
|
+
await rename(index === 1 ? log : `${log}.${index - 1}`, `${log}.${index}`).catch(() => {});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
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
|
+
*/
|
|
61
|
+
async function detach(home: string) {
|
|
62
|
+
await assertPrivateDirectory(home, { create: true });
|
|
63
|
+
const { log } = daemonPaths(home);
|
|
64
|
+
await assertPrivateDirectory(path.dirname(log), { create: true });
|
|
65
|
+
await rotate(log);
|
|
66
|
+
const output = await open(log, 'a', 0o600);
|
|
67
|
+
const self = selfCommand('daemon', { script: fileURLToPath(import.meta.url) });
|
|
68
|
+
const child = spawn(self.command, self.args, {
|
|
69
|
+
detached: true,
|
|
70
|
+
stdio: ['ignore', output.fd, output.fd, 'ipc'],
|
|
71
|
+
env: process.env,
|
|
72
|
+
windowsHide: true,
|
|
73
|
+
});
|
|
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
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Under a service manager (ALPD §37), which holds alpd's stdout open: alpd rotates its
|
|
108
|
+
* log at start as the detached launcher does, then writes its output there itself. The
|
|
109
|
+
* manager's own file keeps only what Node prints when it dies.
|
|
110
|
+
*/
|
|
111
|
+
async function serviceLog(home: string, onError: (error: unknown) => void) {
|
|
112
|
+
await assertPrivateDirectory(home, { create: true });
|
|
113
|
+
const { log } = daemonPaths(home);
|
|
114
|
+
await assertPrivateDirectory(path.dirname(log), { create: true });
|
|
115
|
+
await rotate(log);
|
|
116
|
+
const fd = openSync(log, 'a', 0o600);
|
|
117
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
118
|
+
stream.write = ((chunk: string | Uint8Array, encoding?: unknown, callback?: unknown) => {
|
|
119
|
+
try { if (typeof chunk === 'string') writeSync(fd, chunk); else writeSync(fd, chunk); } catch (error) { onError(error); }
|
|
120
|
+
const done = typeof encoding === 'function' ? encoding : callback;
|
|
121
|
+
if (typeof done === 'function') done();
|
|
122
|
+
return true;
|
|
123
|
+
}) as typeof stream.write;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The user's alpd settings in $ALP_HOME/settings.json; none when it is missing.
|
|
129
|
+
* Invalid settings are logged and alpd starts with the defaults, so a typo never
|
|
130
|
+
* keeps it from running; alp doctor reports them too.
|
|
131
|
+
*/
|
|
132
|
+
async function userSettings(home: string): Promise<any> {
|
|
133
|
+
const file = path.join(home, 'settings.json');
|
|
134
|
+
let text: string;
|
|
135
|
+
try { text = await readFile(file, 'utf8'); } catch { return {}; }
|
|
136
|
+
try { return validateUserSettings(JSON.parse(text), file); }
|
|
137
|
+
catch (error: any) {
|
|
138
|
+
log.warn(`ignoring ${file}: ${error?.message ?? error}`, { code: 'ALP_SETTINGS_INVALID' });
|
|
139
|
+
return {};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* How the previous alpd ended (ALPD §31). A running alpd keeps a marker file and
|
|
145
|
+
* touches it with its heartbeat; a clean stop removes it last. A marker found at
|
|
146
|
+
* start means the previous alpd crashed, around the marker's last touch.
|
|
147
|
+
*/
|
|
148
|
+
async function previousExit(marker: string): Promise<{ kind: 'clean' | 'crash'; at?: string }> {
|
|
149
|
+
const info = await stat(marker).catch(() => undefined);
|
|
150
|
+
return info ? { kind: 'crash', at: info.mtime.toISOString() } : { kind: 'clean' };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Whether a process group `id` exists; on POSIX a pid is never reused while its group lives. */
|
|
154
|
+
function groupAlive(id: number) {
|
|
155
|
+
try { process.kill(-id, 0); return true; } catch (error: any) { return error?.code === 'EPERM'; }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** alpd leads its own process group when started detached or by a service manager. */
|
|
159
|
+
const leadsGroup = () => process.platform !== 'win32' && groupAlive(process.pid);
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Stops what a crashed alpd left running (ALPD §66): its provider processes normally exit
|
|
163
|
+
* when their stdin closes, but a stuck one, or a command an agent started, can outlive it.
|
|
164
|
+
* They stay in the crashed alpd's process group, so alpd ends that group when the crashed
|
|
165
|
+
* one led its group and this one leads its own (so it is not a member). Not on Windows.
|
|
166
|
+
*/
|
|
167
|
+
async function stopLeftovers(previous: { pid?: number; groupLeader?: boolean } | undefined) {
|
|
168
|
+
const pid = previous?.pid;
|
|
169
|
+
if (!previous?.groupLeader || !Number.isSafeInteger(pid) || pid === process.pid || !leadsGroup() || !groupAlive(pid!)) return;
|
|
170
|
+
log.warn(`stopping processes the previous alpd (pid ${pid}) left running`, { code: 'ALP_LEFTOVER_PROCESSES', previousPid: pid });
|
|
171
|
+
const signal = (name: NodeJS.Signals) => { try { process.kill(-pid!, name); } catch {} };
|
|
172
|
+
signal('SIGTERM');
|
|
173
|
+
for (let waited = 0; waited < 3000 && groupAlive(pid!); waited += 50) await new Promise(resolve => setTimeout(resolve, 50));
|
|
174
|
+
if (groupAlive(pid!)) signal('SIGKILL');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Where start-up stands, so a failure says which step it stopped at. */
|
|
178
|
+
type Phase = 'home' | 'lock' | 'state' | 'recovery' | 'listen' | 'ready';
|
|
179
|
+
let phase: Phase = 'home';
|
|
180
|
+
const STARTUP_CODES = { home: 'ALP_HOME_UNUSABLE', lock: 'ALP_LOCK_FAILED', state: 'ALP_STATE_UNUSABLE', recovery: 'ALP_STARTUP_FAILED', listen: 'ALP_IPC_LISTEN_FAILED', ready: 'ALP_STARTUP_FAILED' } as const;
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Before anything reads or writes the state (ALPD §68): a restore cut short is settled, a
|
|
184
|
+
* state of a newer schema is refused untouched, an older one is migrated forward, and a
|
|
185
|
+
* restore's marker says to continue no work by itself this time; it is cleared once alpd is
|
|
186
|
+
* ready, so a start that fails keeps it for the next.
|
|
187
|
+
*/
|
|
188
|
+
async function openState(home: string) {
|
|
189
|
+
const settled = await recoverInterruptedRestore(home);
|
|
190
|
+
if (settled) log.warn(`a restore from ${settled.file} was cut short and has been ${settled.outcome}`, { code: 'ALP_RESTORE_SETTLED', outcome: settled.outcome });
|
|
191
|
+
const migrated = await migrateState(home, { by: `alpd ${VERSION}`, log });
|
|
192
|
+
for (const step of migrated.steps) log.info(`state migrated from schema ${step.from} to ${step.to} (${step.name}); the state before it is in ${step.backup}`, { code: 'ALP_STATE_MIGRATED', from: step.from, to: step.to, migration: step.name });
|
|
193
|
+
const restored = await readRestoredMarker(home);
|
|
194
|
+
if (restored) log.info(`state restored${restored.from ? ` from ${restored.from}` : ''}; sessions that were working wait for the user`, { code: 'ALP_STATE_RESTORED' });
|
|
195
|
+
return { restored: !!restored };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function run(home: string) {
|
|
199
|
+
await assertPrivateDirectory(home, { create: true });
|
|
200
|
+
phase = 'lock';
|
|
201
|
+
const { socket } = daemonPaths(home);
|
|
202
|
+
let lock;
|
|
203
|
+
try {
|
|
204
|
+
lock = await acquireLock(home, { version: VERSION, protocolVersion: PROTOCOL_VERSION, socket });
|
|
205
|
+
} catch (error: any) {
|
|
206
|
+
// Under a service manager, another alpd serving this home is no failure to retry.
|
|
207
|
+
if (process.argv.includes('--service') && /already running|ALP is busy/.test(error?.message ?? '')) {
|
|
208
|
+
log.info(`${error.message}; this one exits`, { code: 'ALP_LOCK_HELD' });
|
|
209
|
+
process.exit(0);
|
|
210
|
+
}
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
phase = 'state';
|
|
214
|
+
let opened;
|
|
215
|
+
try {
|
|
216
|
+
opened = await openState(home);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
await releaseLock(home);
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
phase = 'recovery';
|
|
222
|
+
// First: nothing a crashed alpd left running may still write while this one recovers.
|
|
223
|
+
const marker = path.join(home, 'state', 'alpd.running');
|
|
224
|
+
const exit = await previousExit(marker);
|
|
225
|
+
if (exit.kind === 'crash') {
|
|
226
|
+
log.warn(`the previous alpd stopped unexpectedly around ${exit.at}`, { code: 'ALP_PREVIOUS_CRASH', at: exit.at });
|
|
227
|
+
await stopLeftovers(await readFile(marker, 'utf8').then(JSON.parse).catch(() => undefined));
|
|
228
|
+
}
|
|
229
|
+
await mkdir(path.dirname(marker), { recursive: true, mode: 0o700 });
|
|
230
|
+
await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), groupLeader: leadsGroup() }), { mode: 0o600 });
|
|
231
|
+
const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
|
|
232
|
+
const worktreeDir = path.join(home, 'worktrees');
|
|
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
|
+
}
|
|
243
|
+
// Review copies of interrupted assignments hold nothing to keep.
|
|
244
|
+
const copyDir = path.join(home, 'copies');
|
|
245
|
+
await reclaimCopies(copyDir).catch(() => 0);
|
|
246
|
+
// Requested starts lift the existing hold before launching. Never erase a stop
|
|
247
|
+
// published while this daemon was starting.
|
|
248
|
+
const settings = await userSettings(home);
|
|
249
|
+
const runtime = createAlpRuntime({
|
|
250
|
+
templates, runLogDir, worktreeDir, copyDir, boardDir: path.join(home, 'boards'), libraryDir: home,
|
|
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'),
|
|
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),
|
|
257
|
+
});
|
|
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); } });
|
|
262
|
+
let stopping: Promise<void> | undefined;
|
|
263
|
+
const shutdown = (code = 0) => {
|
|
264
|
+
stopping ??= (async () => {
|
|
265
|
+
const force = setTimeout(() => process.exit(code), 10_000);
|
|
266
|
+
force.unref();
|
|
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(() => {});
|
|
271
|
+
await server.close().catch(() => {});
|
|
272
|
+
await runtime.shutdown().catch(() => {});
|
|
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())]);
|
|
278
|
+
// Last: what remains is a clean stop.
|
|
279
|
+
await unlink(marker).catch(() => {});
|
|
280
|
+
await releaseLock(home);
|
|
281
|
+
log.info('alpd stopped', { event: 'stopped', exitCode: code });
|
|
282
|
+
process.exit(code);
|
|
283
|
+
})();
|
|
284
|
+
return stopping;
|
|
285
|
+
};
|
|
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() });
|
|
297
|
+
const beat = setInterval(() => {
|
|
298
|
+
void heartbeat(home).then(owned => { if (!owned) void shutdown(1); });
|
|
299
|
+
const now = new Date();
|
|
300
|
+
void utimes(marker, now, now).catch(() => {});
|
|
301
|
+
}, 30_000);
|
|
302
|
+
beat.unref();
|
|
303
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
|
|
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); });
|
|
307
|
+
phase = 'listen';
|
|
308
|
+
try {
|
|
309
|
+
await server.listen();
|
|
310
|
+
} catch (error) {
|
|
311
|
+
await releaseLock(home);
|
|
312
|
+
throw error;
|
|
313
|
+
}
|
|
314
|
+
phase = 'ready';
|
|
315
|
+
// Web app and relay are owned by the optional Paseo integration process.
|
|
316
|
+
await updateLock(home, { ...lock, ready: true });
|
|
317
|
+
// Clients that cannot locate alpd themselves (the Paseo plugin) start it from here next time.
|
|
318
|
+
const { install } = daemonPaths(home);
|
|
319
|
+
await writeFile(`${install}.tmp`, JSON.stringify({ entry: selfEntry(fileURLToPath(import.meta.url)), version: VERSION }), { mode: 0o600 })
|
|
320
|
+
.then(() => rename(`${install}.tmp`, install))
|
|
321
|
+
.catch(error => log.warn('could not record alpd\'s location', { code: 'ALP_INSTALL_RECORD_FAILED', error }));
|
|
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');
|
|
325
|
+
log.info(`alpd ${VERSION} ready on ${socket} (pid ${process.pid})`, { event: 'ready', version: VERSION, pid: process.pid });
|
|
326
|
+
}
|
|
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
|
+
|
|
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 });
|
|
341
|
+
try {
|
|
342
|
+
if (process.argv.includes('--detach')) await detach(home);
|
|
343
|
+
else {
|
|
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
|
+
}
|
|
356
|
+
}
|
|
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
|
+
}
|
|
363
|
+
// The log says where start-up stopped; alp doctor reads it from there.
|
|
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);
|
|
368
|
+
// Opening the state fails with the state's own code (a newer schema, a failed migration).
|
|
369
|
+
const code = disk ? 'ALP_DISK_FULL'
|
|
370
|
+
: /already running|ALP is busy/.test(error?.message ?? '') ? 'ALP_LOCK_HELD'
|
|
371
|
+
: stoppedIn === 'state' && typeof error?.code === 'string' && /^[A-Z_]+$/.test(error.code) ? `ALP_${error.code}` : STARTUP_CODES[stoppedIn];
|
|
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
|
+
});
|
|
380
|
+
process.exit(1);
|
|
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
|
+
}
|