@anhlp/alp-daemon 0.0.1-beta.7 → 0.0.1-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-NOTICES.txt +1 -1
- package/dist/alpd.js +11807 -5372
- 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-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.js +6 -2
- package/dist/operations.d.ts +8 -1
- package/dist/operations.js +32 -5
- package/dist/scheduler.js +2 -0
- package/dist/server.js +47 -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 +28 -5
- 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-entry.ts +5 -0
- package/src/native-register.ts +21 -0
- package/src/native-terminal.ts +10 -2
- package/src/operations.ts +18 -5
- package/src/scheduler.ts +6 -0
- package/src/server.ts +51 -11
- package/src/terminals.ts +18 -6
- package/src/windows-terminal.ts +31 -6
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,38 @@ 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
|
+
}
|
|
1601
1629
|
},
|
|
1602
1630
|
|
|
1603
1631
|
/** The slash commands and skills a live session's composer offers after "/" (t-f628). */
|
|
@@ -1853,7 +1881,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1853
1881
|
async function invokeExtended(owner: Connection, caller: Connection, method: string, params: any) {
|
|
1854
1882
|
if (owner.pending.size >= 128) throw new RpcError(ERROR.conflict, 'too many pending extension calls');
|
|
1855
1883
|
const id = ++owner.nextId;
|
|
1856
|
-
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 } : {}) } } };
|
|
1857
1885
|
if (Buffer.byteLength(encodeFrame(invocation), 'utf8') > MAX_FRAME) throw new RpcError(-32600, 'ALP daemon frame exceeds size limit');
|
|
1858
1886
|
return new Promise((resolve, reject) => {
|
|
1859
1887
|
const timer = setTimeout(() => {
|
|
@@ -1952,10 +1980,22 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
|
|
|
1952
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] });
|
|
1953
1981
|
const issues = validateParams(method, params)!;
|
|
1954
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' });
|
|
1955
1986
|
connection.helloed = true;
|
|
1956
1987
|
// Sticky: a later hello never sheds it.
|
|
1957
1988
|
connection.agent = connection.agent === true || (Array.isArray(params?.capabilities) && params.capabilities.includes(AGENT_CAPABILITY));
|
|
1958
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
|
+
}
|
|
1959
1999
|
// Terminals are listed only while the host's switch is on (and the PTY module loads).
|
|
1960
2000
|
const terminalLimits = await terminals?.advertised();
|
|
1961
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
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
import { createRequire } from 'node:module';
|
|
7
7
|
import type { PtySpawn } from './terminals.js';
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
/** The node-pty surface the win32 owner uses. */
|
|
10
|
+
export type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
|
|
10
11
|
pid: number; write(data: string): void; resize(cols: number, rows: number): void; kill(signal?: string): void;
|
|
11
12
|
onData(listener: (data: string) => void): { dispose(): void }; onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
|
|
12
13
|
} };
|
|
@@ -20,8 +21,9 @@ export function loadNodePty(): NodePty | undefined {
|
|
|
20
21
|
return loaded ?? undefined;
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
|
|
24
|
-
|
|
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' };
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
/** The shell for a Windows terminal: COMSPEC when absolute, else cmd.exe. */
|
|
@@ -30,20 +32,43 @@ export function windowsShell(env: NodeJS.ProcessEnv = process.env): string {
|
|
|
30
32
|
return candidate && /^[a-zA-Z]:[\\/]/.test(candidate) ? candidate : 'cmd.exe';
|
|
31
33
|
}
|
|
32
34
|
|
|
33
|
-
|
|
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) => {
|
|
34
37
|
if (options.signal?.aborted) throw new Error('Terminal startup cancelled');
|
|
35
|
-
const pty =
|
|
38
|
+
const pty = load();
|
|
36
39
|
if (!pty) throw new Error('node-pty is unavailable on this host');
|
|
37
40
|
const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
|
|
38
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(); }); });
|
|
39
53
|
return {
|
|
40
|
-
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; },
|
|
41
57
|
write(data: string) { if (!killed) child.write(data); },
|
|
42
58
|
resize(cols: number, rows: number) { if (!killed) try { child.resize(cols, rows); } catch { /* exited */ } },
|
|
43
59
|
// Best-effort: node-pty ends the ConPTY session and its shell; descendants are not guaranteed.
|
|
44
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
|
+
},
|
|
45
69
|
onData: listener => child.onData(listener),
|
|
46
70
|
onExit: listener => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal })),
|
|
47
71
|
};
|
|
48
72
|
};
|
|
49
73
|
|
|
74
|
+
export const windowsPtySpawn: PtySpawn = createWindowsPtySpawn();
|