@anhlp/alp-daemon 0.0.1-beta.6 → 0.0.1-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/alpd.js +10508 -4233
- package/dist/build-manifest.json +8 -2
- package/dist/git.d.ts +6 -1
- package/dist/git.js +86 -32
- package/dist/main.js +51 -10
- package/dist/model-catalog.d.ts +2 -0
- package/dist/model-catalog.js +44 -0
- package/dist/native-terminal.js +2 -3
- package/dist/operations.d.ts +8 -1
- package/dist/operations.js +32 -5
- package/dist/scheduler.js +2 -0
- package/dist/server.js +61 -11
- package/dist/terminals.d.ts +12 -2
- package/dist/terminals.js +3 -3
- package/dist/windows-terminal.d.ts +6 -3
- package/dist/windows-terminal.js +30 -73
- package/package.json +6 -6
- package/src/git.ts +102 -22
- package/src/main.ts +56 -7
- package/src/model-catalog.ts +36 -0
- package/src/native-terminal.ts +2 -5
- package/src/operations.ts +18 -5
- package/src/scheduler.ts +6 -0
- package/src/server.ts +66 -12
- package/src/terminals.ts +18 -6
- package/src/windows-terminal.ts +33 -82
package/src/server.ts
CHANGED
|
@@ -9,7 +9,7 @@ import os from 'node:os';
|
|
|
9
9
|
import { assertPrivateDirectory, assertPrivateSocket } from '@anhlp/alp-client/index';
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { createLogger } from '@anhlp/alp-core/log';
|
|
12
|
-
import { AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from '@anhlp/alp-protocol';
|
|
12
|
+
import { AGENT_NAME, AlpRpcError, CAPABILITY, MAX_FRAME, PROMPT_IMAGES, PROTOCOL_VERSION, ERROR, RPC_ERROR, RPC_METHODS, base64Bytes, encodeFrame } from '@anhlp/alp-protocol';
|
|
13
13
|
import { validateParams } from '@anhlp/alp-protocol/contract';
|
|
14
14
|
export { ERROR } from '@anhlp/alp-protocol';
|
|
15
15
|
import { DEFAULT_MODEL, models, modes, type ModelCatalog, thinkingOptions, type AlpEvent, type AlpRuntime, type Envelope, type SessionSnapshot } from '@anhlp/alp-runtime/index';
|
|
@@ -119,6 +119,8 @@ type Connection = {
|
|
|
119
119
|
helloed: boolean;
|
|
120
120
|
/** It said in daemon.hello that an ALP agent started it (t-ca1f): refused what only the user may do. */
|
|
121
121
|
agent?: boolean;
|
|
122
|
+
/** The agent's name an agent connection gave in daemon.hello (`principal.agent`, t-1c59): who it is, for the logs; never grants anything. Sticky: the first name stays. */
|
|
123
|
+
agentName?: string;
|
|
122
124
|
/** The client name daemon.hello gave: a gate card answered from alp-paseo* is recorded as paseo, else web. */
|
|
123
125
|
client?: string;
|
|
124
126
|
roots: Set<string>;
|
|
@@ -240,8 +242,15 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
240
242
|
const connections = new Set<Connection>();
|
|
241
243
|
const catalogResult = () => {
|
|
242
244
|
const state = modelCatalog?.state();
|
|
243
|
-
|
|
244
|
-
|
|
245
|
+
// ACP providers' rows (t-d0b0), from their files and what sessions or an explicit probe taught.
|
|
246
|
+
const acpRows = modelCatalog?.acpRows() ?? [];
|
|
247
|
+
const acpModels = acpRows.map(row => ({ id: `acp:${row.id}`, label: row.label, description: row.description, thinkingOptions: [], runtime: 'acp', provider: row.provider, source: row.source, enabled: row.enabled, status: row.status }));
|
|
248
|
+
const acpProviders = Object.fromEntries([...new Set(acpRows.map(row => row.provider))].map(id => {
|
|
249
|
+
const acp = state?.acp?.[id];
|
|
250
|
+
return [`acp:${id}`, { status: acp?.status ?? 'unprobed', ...(acp?.fetchedAt ? { fetchedAt: acp.fetchedAt } : {}), ...(acp?.error ? { error: acp.error } : {}) }];
|
|
251
|
+
}));
|
|
252
|
+
return { models: [...models, ...acpModels], modes, thinkingOptions, defaultModel: `codex:${DEFAULT_MODEL}`,
|
|
253
|
+
...(state ? { fetchedAt: state.fetchedAt, providers: { ...Object.fromEntries(Object.entries(state.providers).map(([runtime, provider]) => [runtime, { status: provider!.status, fetchedAt: provider!.fetchedAt, ...(provider!.error ? { error: provider!.error } : {}) }])), ...acpProviders, ...(modelCatalog?.acpLoadError() ? { acp: { status: 'failed', error: modelCatalog.acpLoadError() } } : {}) } } : {}) };
|
|
245
254
|
};
|
|
246
255
|
// Every helloed connection learns that the catalog changed, and re-reads it (catalog.updated).
|
|
247
256
|
const unsubscribeCatalog = modelCatalog?.onUpdated(snapshot => {
|
|
@@ -1117,12 +1126,17 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1117
1126
|
if (!gitReader) throw new RpcError(ERROR.unavailable, 'Registry needs ALP_HOME');
|
|
1118
1127
|
return run(gitReader);
|
|
1119
1128
|
};
|
|
1120
|
-
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])), onGateChange: root => runtime.syncGates?.(root)
|
|
1129
|
+
const operations = createOperations({ home, templates, knownProjects: () => new Set([...records.values()].flatMap(record => record.session?.projectRoot ? [record.session.projectRoot] : [])), onGateChange: root => runtime.syncGates?.(root),
|
|
1130
|
+
// A provider file saved: reread the ACP rows; one the user just enabled is probed for its models (t-d0b0).
|
|
1131
|
+
learnedModels: id => modelCatalog?.acpModels(id) ?? [],
|
|
1132
|
+
onProviderSaved: (id, enabled) => { if (!modelCatalog) return; void (enabled ? modelCatalog.refreshAcp([id]) : modelCatalog.loadAcp()).catch(() => {}); } });
|
|
1121
1133
|
const extensionOwners = new Map<string, Connection>();
|
|
1122
1134
|
/** workspace.files.find's snapshots, each for the connection that asked. */
|
|
1123
1135
|
const findPages = createFindPages();
|
|
1124
1136
|
const handlers: Record<string, (connection: Connection, params: any) => Promise<unknown> | unknown> = {
|
|
1125
1137
|
'extension.register': async (connection, params) => {
|
|
1138
|
+
// An agent could claim a user's method (web.pairing) while its owner is down (t-d08b).
|
|
1139
|
+
agentRefused(connection, 'extension.register');
|
|
1126
1140
|
const method = params?.method;
|
|
1127
1141
|
if (typeof method !== 'string' || !/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(method) || method === '__proto__' || method === 'constructor' || method === 'toString') throw new RpcError(ERROR.protocol, 'extension.register requires a safe method name');
|
|
1128
1142
|
if (method.length > 128 || (reservedNamespaces.has(method.split('.')[0]) && !originalMethods.has(method))) throw new RpcError(ERROR.protocol, 'extension.register requires an extension namespace and a name of at most 128 characters');
|
|
@@ -1347,7 +1361,9 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1347
1361
|
'catalog.get': () => catalogResult(),
|
|
1348
1362
|
'catalog.refresh': async () => {
|
|
1349
1363
|
if (!modelCatalog) throw new RpcError(ERROR.unavailable, 'The live model catalog is not available');
|
|
1350
|
-
|
|
1364
|
+
// The one place, with a provider's enabling, where ALP starts ACP providers to list their models.
|
|
1365
|
+
// An ACP failure must not hide the providers' refresh: each records its own error.
|
|
1366
|
+
await Promise.all([modelCatalog.refresh(), modelCatalog.refreshAcp().catch(() => {})]);
|
|
1351
1367
|
return catalogResult();
|
|
1352
1368
|
},
|
|
1353
1369
|
// attachment.* (§12.6): each call acts for its principal context; without the store (no home or
|
|
@@ -1533,6 +1549,9 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1533
1549
|
async 'session.prompt'(_connection, { sessionId, clientMessageId, delivery = 'auto', content, ...context }) {
|
|
1534
1550
|
if (typeof clientMessageId !== 'string' || !Array.isArray(content)) throw new RpcError(-32602, 'clientMessageId and content are required');
|
|
1535
1551
|
if (delivery !== 'auto' && delivery !== 'steer') throw new RpcError(-32602, 'delivery must be auto or steer');
|
|
1552
|
+
// t-e906: a native command ALP cannot follow (Claude's /clear) is refused here, never sent.
|
|
1553
|
+
const refused = runtime.refusesPrompt?.(sessionId, content);
|
|
1554
|
+
if (refused) throw new RpcError(-32602, refused, { reason: 'native_command_unsupported' });
|
|
1536
1555
|
// Images are inline only (the schema refuses a path or URL); here their number and decoded size.
|
|
1537
1556
|
const images = content.filter((part: { type?: string }) => part?.type === 'image');
|
|
1538
1557
|
if (images.length > PROMPT_IMAGES.maxCount) throw new RpcError(-32602, `A prompt takes at most ${PROMPT_IMAGES.maxCount} images`);
|
|
@@ -1575,29 +1594,52 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1575
1594
|
},
|
|
1576
1595
|
|
|
1577
1596
|
/** A new root from a root's conversation cut at a turn, or from a branch a rewind set aside (§12.7). */
|
|
1578
|
-
async 'session.fork'(
|
|
1597
|
+
async 'session.fork'(connection, params) {
|
|
1598
|
+
agentRefused(connection, 'session.fork');
|
|
1579
1599
|
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not fork conversations (capability session.fork is not listed)');
|
|
1580
1600
|
return conversation.fork({ ...params, principal: principalOf(params) });
|
|
1581
1601
|
},
|
|
1582
1602
|
|
|
1583
1603
|
/** The root's conversation from before a turn on, same id; the later turns stay a recoverable branch, files untouched (§12.7). */
|
|
1584
|
-
async 'session.rewind'(
|
|
1604
|
+
async 'session.rewind'(connection, params) {
|
|
1605
|
+
agentRefused(connection, 'session.rewind');
|
|
1585
1606
|
if (!conversation?.enabled) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not rewind conversations (capability session.rewind is not listed)');
|
|
1586
1607
|
return conversation.rewind(params);
|
|
1587
1608
|
},
|
|
1588
1609
|
|
|
1589
1610
|
/** Restarts a live root's native process on its own conversation at the idle barrier (§12.8). */
|
|
1590
|
-
async 'session.reload'(
|
|
1611
|
+
async 'session.reload'(connection, params) {
|
|
1612
|
+
agentRefused(connection, 'session.reload');
|
|
1591
1613
|
if (!conversation?.reloads) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not reload sessions (capability session.reload is not listed)');
|
|
1592
1614
|
return conversation.reload(params);
|
|
1593
1615
|
},
|
|
1594
1616
|
|
|
1595
1617
|
/** Compacts a live root's context now or at its next turn boundary (t-0e56). */
|
|
1596
|
-
async 'session.compact'(
|
|
1618
|
+
async 'session.compact'(connection, { sessionId }) {
|
|
1619
|
+
// Compaction rewrites the user's conversation context; an agent's connection may not (t-de1a review).
|
|
1620
|
+
agentRefused(connection, 'session.compact');
|
|
1597
1621
|
if (typeof sessionId !== 'string' || !sessionId) throw new RpcError(-32602, 'sessionId is required');
|
|
1598
1622
|
if (!runtime.compact) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd does not compact sessions');
|
|
1599
1623
|
try { return runtime.compact(sessionId); }
|
|
1600
|
-
catch (error) {
|
|
1624
|
+
catch (error) {
|
|
1625
|
+
// A refusal keeps its reason (session_busy, runtime_unsupported), so a client can word it (t-de1a).
|
|
1626
|
+
const reason = (error as { data?: { reason?: unknown } })?.data?.reason;
|
|
1627
|
+
throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error), typeof reason === 'string' ? { reason } : undefined);
|
|
1628
|
+
}
|
|
1629
|
+
},
|
|
1630
|
+
|
|
1631
|
+
/** The slash commands and skills a live session's composer offers after "/" (t-f628). */
|
|
1632
|
+
async 'session.commands'(_connection, { sessionId }) {
|
|
1633
|
+
if (typeof sessionId !== 'string' || !sessionId) throw new RpcError(-32602, 'sessionId is required');
|
|
1634
|
+
if (!runtime.commands) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd lists no commands (capability session.commands is not listed)');
|
|
1635
|
+
if (!runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
|
|
1636
|
+
try {
|
|
1637
|
+
const listed = await runtime.commands(sessionId);
|
|
1638
|
+
const seen = new Set<string>();
|
|
1639
|
+
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)
|
|
1640
|
+
.map(command => ({ name: command.name, description: command.description.slice(0, 4096), ...(command.argumentHint ? { argumentHint: command.argumentHint.slice(0, 256) } : {}), kind: command.kind }));
|
|
1641
|
+
return { commands };
|
|
1642
|
+
} catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
|
|
1601
1643
|
},
|
|
1602
1644
|
|
|
1603
1645
|
/** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
|
|
@@ -1839,7 +1881,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1839
1881
|
async function invokeExtended(owner: Connection, caller: Connection, method: string, params: any) {
|
|
1840
1882
|
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, 'too many pending extension calls');
|
|
1841
1883
|
const id = ++owner.nextId;
|
|
1842
|
-
const invocation = { jsonrpc: '2.0', id, method: 'extension.invoke', params: { method, params } };
|
|
1884
|
+
const invocation = { jsonrpc: '2.0', id, method: 'extension.invoke', params: { method, params, caller: { agent: caller.agent === true, ...(caller.agentName !== undefined ? { agentName: caller.agentName } : {}) } } };
|
|
1843
1885
|
if (Buffer.byteLength(encodeFrame(invocation), 'utf8') > MAX_FRAME) throw new RpcError(-32600, 'ALP daemon frame exceeds size limit');
|
|
1844
1886
|
return new Promise((resolve, reject) => {
|
|
1845
1887
|
const timer = setTimeout(() => {
|
|
@@ -1888,7 +1930,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1888
1930
|
}
|
|
1889
1931
|
|
|
1890
1932
|
/** What this daemon lists in daemon.hello: only features it serves now (docs/protocol/alp-json-rpc-v1.md §6). */
|
|
1891
|
-
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];
|
|
1933
|
+
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];
|
|
1892
1934
|
|
|
1893
1935
|
/** A response too large for the wire becomes an error the client can read. */
|
|
1894
1936
|
function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
|
|
@@ -1938,10 +1980,22 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1938
1980
|
if (params?.protocolVersion !== PROTOCOL_VERSION) throw new RpcError(ERROR.protocol, `ALP daemon speaks protocol ${PROTOCOL_VERSION}; restart it after upgrading (alp daemon restart)`, { reason: 'protocol_version', supported: [PROTOCOL_VERSION] });
|
|
1939
1981
|
const issues = validateParams(method, params)!;
|
|
1940
1982
|
if (issues.length) throw invalidParams(issues);
|
|
1983
|
+
// Checked before the connection changes, so a refused hello changes nothing. The gateway checks a credential's agent with the same AGENT_NAME.
|
|
1984
|
+
const named = params?.principal?.agent;
|
|
1985
|
+
if (named !== undefined && (typeof named !== 'string' || !AGENT_NAME.test(named))) throw new RpcError(RPC_ERROR.invalidParams, 'principal.agent must be an agent name', { reason: 'invalid_params' });
|
|
1941
1986
|
connection.helloed = true;
|
|
1942
1987
|
// Sticky: a later hello never sheds it.
|
|
1943
1988
|
connection.agent = connection.agent === true || (Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY));
|
|
1944
1989
|
if (typeof params?.client?.name === 'string') connection.client = params.client.name;
|
|
1990
|
+
// A named principal (t-1c59: the gateway sends a named agent credential's name) is an agent's
|
|
1991
|
+
// too: naming one only ever takes away. The name is a label for the logs, not a credential.
|
|
1992
|
+
if (named !== undefined) {
|
|
1993
|
+
connection.agent = true;
|
|
1994
|
+
if (connection.agentName === undefined) {
|
|
1995
|
+
connection.agentName = named;
|
|
1996
|
+
log.info('an agent connection named itself', { code: 'ALP_AGENT_CONNECTION', agentName: named, client: connection.client });
|
|
1997
|
+
} else if (connection.agentName !== named) log.warn('an agent connection gave a second name; the first stays', { code: 'ALP_AGENT_CONNECTION_RENAME', agentName: connection.agentName, refused: named });
|
|
1998
|
+
}
|
|
1945
1999
|
// Terminals are listed only while the host's switch is on (and the PTY module loads).
|
|
1946
2000
|
const terminalLimits = await terminals?.advertised();
|
|
1947
2001
|
respond({ result: { protocolVersion: PROTOCOL_VERSION, daemonVersion: version, pid: process.pid, hostname: os.hostname(), capabilities: terminalLimits ? [...capabilities, CAPABILITY.terminal, CAPABILITY.terminalCapture, CAPABILITY.terminalWatch] : capabilities, ...(attachments ? { attachmentLimits: attachments.limits } : {}), ...(terminalLimits ? { terminalLimits } : {}) } });
|
package/src/terminals.ts
CHANGED
|
@@ -27,13 +27,23 @@ export type TerminalSink = { send(message: unknown): void; socket?: { writableLe
|
|
|
27
27
|
type Disposable = { dispose(): void };
|
|
28
28
|
/** Native owner interface; injected owners are used only by tests. */
|
|
29
29
|
export type PtyProcess = {
|
|
30
|
-
|
|
30
|
+
/**
|
|
31
|
+
* The shell's pid, read live on every access: never copy it at spawn. The win32 owner reports 0
|
|
32
|
+
* until node-pty's ConPTY output worker connects, then the real pid (windows-terminal.ts).
|
|
33
|
+
*/
|
|
34
|
+
readonly pid: number;
|
|
31
35
|
/** The PTY's device (node-pty's UnixTerminal), such as /dev/ttys004 or /dev/pts/3. */
|
|
32
36
|
readonly ptsName?: string;
|
|
33
37
|
write(data: string): void;
|
|
34
38
|
resize(cols: number, rows: number): void;
|
|
35
39
|
kill(signal?: string): void;
|
|
36
40
|
cleanup?: () => Promise<CleanupResult>;
|
|
41
|
+
/**
|
|
42
|
+
* The win32 owner (no native cleanup): resolves once node-pty reports the killed shell's exit, or
|
|
43
|
+
* after `ms`. `kill` only asks node-pty to end the shell; until Windows has closed the shell's
|
|
44
|
+
* handles, its working directory (the workspace) stays open and cannot be removed (EBUSY, t-bfbd).
|
|
45
|
+
*/
|
|
46
|
+
exited?: (ms: number) => Promise<void>;
|
|
37
47
|
onData(listener: (data: string) => void): Disposable;
|
|
38
48
|
onExit(listener: (event: { exitCode: number | null; signal?: number }) => void): Disposable;
|
|
39
49
|
};
|
|
@@ -77,7 +87,6 @@ type Terminal = {
|
|
|
77
87
|
rows: number;
|
|
78
88
|
pty: PtyProcess;
|
|
79
89
|
screen: TerminalScreen;
|
|
80
|
-
pid: number;
|
|
81
90
|
/** The PTY's device as ps names it (ttys004, pts/3): a controlling terminal outlives double forks. */
|
|
82
91
|
tty?: string;
|
|
83
92
|
createdAt: number;
|
|
@@ -257,7 +266,10 @@ export function createTerminalService(options: TerminalServiceOptions) {
|
|
|
257
266
|
const cancel = (entry: Pending, reason: string) => { entry.reason ??= reason; entry.controller.abort(); };
|
|
258
267
|
const refused = (reason: string) => new RpcError(ERROR.unavailable, 'Terminal startup was cancelled or its native owner is unavailable', { reason });
|
|
259
268
|
async function cleanup(owner: PtyProcess, id?: string) {
|
|
260
|
-
|
|
269
|
+
// Test owners and the win32 node-pty owner (best-effort): the win32 owner is waited for, so a
|
|
270
|
+
// closed terminal no longer holds its directory. No retry here: cleanup removes nothing; whoever
|
|
271
|
+
// removes the workspace afterwards (a worktree removal) reports its own failure.
|
|
272
|
+
if (!owner.cleanup) { owner.kill(); await owner.exited?.(killGraceMs); return; }
|
|
261
273
|
const result = await owner.cleanup();
|
|
262
274
|
if (result.coverage === 'root-only') log.info('terminal shell cleanup has reduced coverage; descendants are unmanaged', { code: 'ALPD_TERMINAL_ROOT_ONLY_CLEANUP', terminalId: id, outputOpen: result.outputOpen === true });
|
|
263
275
|
if (result.live || result.uncertain) {
|
|
@@ -491,7 +503,7 @@ export function createTerminalService(options: TerminalServiceOptions) {
|
|
|
491
503
|
}
|
|
492
504
|
const terminal: Terminal = {
|
|
493
505
|
id: `term_${randomBytes(16).toString('hex')}`, principal: { id: principal.id, epoch: principal.epoch }, workspaceId: params.workspaceId,
|
|
494
|
-
root, ...(protection ? { protection } : {}), title: path.basename(file).slice(0, 64), cols: params.cols, rows: params.rows, pty: process_,
|
|
506
|
+
root, ...(protection ? { protection } : {}), title: path.basename(file).slice(0, 64), cols: params.cols, rows: params.rows, pty: process_, screen: new TerminalScreen(params.cols, params.rows),
|
|
495
507
|
...(typeof process_.ptsName === 'string' && process_.ptsName.startsWith('/dev/') ? { tty: process_.ptsName.slice('/dev/'.length) } : {}),
|
|
496
508
|
createdAt: at, lastActivityAt: at, expiresAt: at + limits.maxLifetimeMs, requestKey, ring: [], ringBytes: 0, nextSeq: 1,
|
|
497
509
|
detachedAt: at, marker, disposables: [],
|
|
@@ -634,8 +646,8 @@ export function createTerminalService(options: TerminalServiceOptions) {
|
|
|
634
646
|
if (cleanupFault || outcomes.some(result => result.status === 'rejected')) throw refused('terminal_cleanup_uncertain');
|
|
635
647
|
},
|
|
636
648
|
|
|
637
|
-
/** Test hook: pids of every running terminal's shell. */
|
|
638
|
-
pids() { return [...terminals.values()].filter(terminal => !terminal.exit).map(terminal => terminal.pid); },
|
|
649
|
+
/** Test hook: pids of every running terminal's shell (read live: the win32 owner learns it after spawn). */
|
|
650
|
+
pids() { return [...terminals.values()].filter(terminal => !terminal.exit).map(terminal => terminal.pty.pid); },
|
|
639
651
|
};
|
|
640
652
|
}
|
|
641
653
|
export type TerminalService = ReturnType<typeof createTerminalService>;
|
package/src/windows-terminal.ts
CHANGED
|
@@ -3,38 +3,27 @@
|
|
|
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
|
+
/** The node-pty surface the win32 owner uses. */
|
|
10
|
+
export type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
|
|
12
11
|
pid: number; write(data: string): void; resize(cols: number, rows: number): void; kill(signal?: string): void;
|
|
13
12
|
onData(listener: (data: string) => void): { dispose(): void }; onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
|
|
14
13
|
} };
|
|
15
14
|
|
|
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
15
|
let loaded: NodePty | null | undefined;
|
|
28
16
|
/** node-pty, or undefined when it cannot load on this host. */
|
|
29
17
|
export function loadNodePty(): NodePty | undefined {
|
|
30
18
|
if (loaded === undefined) {
|
|
31
|
-
try { loaded = createRequire(import.meta.url)(
|
|
19
|
+
try { loaded = createRequire(import.meta.url)('node-pty') as NodePty; } catch { loaded = null; }
|
|
32
20
|
}
|
|
33
21
|
return loaded ?? undefined;
|
|
34
22
|
}
|
|
35
23
|
|
|
36
|
-
|
|
37
|
-
|
|
24
|
+
/** `load` is a test hook (tests/windows-terminal.test.js); production loads the installed node-pty. */
|
|
25
|
+
export function windowsTerminalCapability(load: () => NodePty | undefined = loadNodePty): { available: boolean; protection?: 'none'; reason?: string } {
|
|
26
|
+
return load() ? { available: true, protection: 'none' } : { available: false, reason: 'node_pty_unavailable' };
|
|
38
27
|
}
|
|
39
28
|
|
|
40
29
|
/** The shell for a Windows terminal: COMSPEC when absolute, else cmd.exe. */
|
|
@@ -43,81 +32,43 @@ export function windowsShell(env: NodeJS.ProcessEnv = process.env): string {
|
|
|
43
32
|
return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : 'cmd.exe';
|
|
44
33
|
}
|
|
45
34
|
|
|
46
|
-
|
|
35
|
+
/** The win32 owner over `load`'s node-pty; `load` is a test hook, production uses {@link windowsPtySpawn}. */
|
|
36
|
+
export const createWindowsPtySpawn = (load: () => NodePty | undefined = loadNodePty): PtySpawn => (file, args, options) => {
|
|
47
37
|
if (options.signal?.aborted) throw new Error('Terminal startup cancelled');
|
|
48
|
-
const pty =
|
|
38
|
+
const pty = load();
|
|
49
39
|
if (!pty) throw new Error('node-pty is unavailable on this host');
|
|
50
|
-
|
|
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);
|
|
40
|
+
const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
|
|
55
41
|
let killed = false;
|
|
42
|
+
// Waited for after kill so that a closed terminal no longer holds its working directory (t-bfbd).
|
|
43
|
+
// process.kill(pid, 0) is not that point: libuv reads the exit code, which Windows sets before it
|
|
44
|
+
// closes the shell's handles, the cwd among them (rmdir right after a TerminateProcess: EBUSY).
|
|
45
|
+
// node-pty emits exit when its output socket closes (after kill: ClosePseudoConsole, then the conout
|
|
46
|
+
// drain); the exit code it carries is set only by its native WaitForSingleObject on the shell's process
|
|
47
|
+
// handle, which returns once those handles are closed. A numeric exit code therefore means the
|
|
48
|
+
// directory was released; the order of the two is what node-pty does, not something it promises
|
|
49
|
+
// (every exit after a kill carried a numeric code here, 200 of 200 on Windows 10). Best-effort, like
|
|
50
|
+
// the rest of the Windows owner. Subscribed here, before any service listener.
|
|
51
|
+
let exit = false;
|
|
52
|
+
const exited = new Promise<void>(resolve => { child.onExit(() => { exit = true; resolve(); }); });
|
|
56
53
|
return {
|
|
57
|
-
pid
|
|
54
|
+
// node-pty reports the ConPTY shell's pid only once its output worker connects (0 until then), so
|
|
55
|
+
// the pid is read live rather than copied at spawn.
|
|
56
|
+
get pid() { return child.pid; },
|
|
58
57
|
write(data: string) { if (!killed) child.write(data); },
|
|
59
58
|
resize(cols: number, rows: number) { if (!killed) try { child.resize(cols, rows); } catch { /* exited */ } },
|
|
60
59
|
// Best-effort: node-pty ends the ConPTY session and its shell; descendants are not guaranteed.
|
|
61
60
|
kill() { if (killed) return; killed = true; try { child.kill(); } catch { /* already exited */ } },
|
|
61
|
+
// Bounded: node-pty defers a kill until the terminal is ready (its first output) and may never report
|
|
62
|
+
// an exit (a terminal that never becomes ready, a lost callback); that does not hold up close.
|
|
63
|
+
async exited(ms: number) {
|
|
64
|
+
if (exit) return;
|
|
65
|
+
let timer: NodeJS.Timeout | undefined;
|
|
66
|
+
await Promise.race([exited, new Promise<void>(resolve => { timer = setTimeout(resolve, ms); })]);
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
},
|
|
62
69
|
onData: listener => child.onData(listener),
|
|
63
70
|
onExit: listener => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal })),
|
|
64
71
|
};
|
|
65
72
|
};
|
|
66
73
|
|
|
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
|
-
}
|
|
74
|
+
export const windowsPtySpawn: PtySpawn = createWindowsPtySpawn();
|