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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.1-beta.6",
2
+ "version": "0.0.1-beta.7",
3
3
  "entries": {
4
4
  "packages/daemon/dist/alpd.js": {
5
5
  "inputs": [
package/dist/main.js CHANGED
@@ -21,7 +21,7 @@ import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } fr
21
21
  import { migrateState } from "@anhlp/alp-core/migrations";
22
22
  import { createLogger } from "@anhlp/alp-core/log";
23
23
  import { selfCommand, selfEntry } from "@anhlp/alp-core/packaged";
24
- var VERSION = true ? "0.0.1-beta.6" : "0.0.0-dev";
24
+ var VERSION = true ? "0.0.1-beta.7" : "0.0.0-dev";
25
25
  var LOG_BYTES = 10 * 1024 * 1024;
26
26
  var LOG_FILES = 3;
27
27
  var log = createLogger({ component: "alpd" });
@@ -9,9 +9,8 @@ var sha = (value) => createHash("sha256").update(value).digest("hex");
9
9
  function binary() {
10
10
  const libc = process.platform === "linux" ? process.report?.getReport()?.header?.glibcVersionRuntime ? "glibc" : "musl" : void 0;
11
11
  const slot = [process.platform, process.arch, libc].filter(Boolean).join("-");
12
- const assets = globalThis[Symbol.for("alp.packaged")]?.assetDir?.();
13
- const adjacent = assets ? path.join(assets, "terminal-native") : path.join(path.dirname(fileURLToPath(import.meta.url)), "terminal-native");
14
- const dir = assets || existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../native");
12
+ const adjacent = path.join(path.dirname(fileURLToPath(import.meta.url)), "terminal-native");
13
+ const dir = existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../native");
15
14
  const file = path.join(dir, "prebuilt", slot, "terminal-owner");
16
15
  const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), "manifest.json"), "utf8"));
17
16
  if (!statSync(file).isFile() || manifest.protocol !== 1 || manifest.slot !== slot || manifest.source !== sha(readFileSync(path.join(dir, "terminal-owner.c"))) || manifest.sha256 !== sha(readFileSync(file))) throw new Error("Native helper manifest mismatch");
package/dist/server.js CHANGED
@@ -1328,6 +1328,20 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1328
1328
  throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
1329
1329
  }
1330
1330
  },
1331
+ /** The slash commands and skills a live session's composer offers after "/" (t-f628). */
1332
+ async "session.commands"(_connection, { sessionId }) {
1333
+ if (typeof sessionId !== "string" || !sessionId) throw new RpcError(-32602, "sessionId is required");
1334
+ if (!runtime.commands) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd lists no commands (capability session.commands is not listed)");
1335
+ if (!runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: "not_found" });
1336
+ try {
1337
+ const listed = await runtime.commands(sessionId);
1338
+ const seen2 = /* @__PURE__ */ new Set();
1339
+ const commands = listed.filter((command) => /^[^\s\u0000-\u001f\u007f]{1,256}$/.test(command.name) && !seen2.has(command.name) && seen2.add(command.name)).slice(0, 1e3).map((command) => ({ name: command.name, description: command.description.slice(0, 4096), ...command.argumentHint ? { argumentHint: command.argumentHint.slice(0, 256) } : {}, kind: command.kind }));
1340
+ return { commands };
1341
+ } catch (error) {
1342
+ throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error));
1343
+ }
1344
+ },
1331
1345
  /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1332
1346
  async "session.resumeCommand"(_connection, { sessionId }) {
1333
1347
  if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, "This alpd has no resume command (capability session.resumeCommand is not listed)");
@@ -1583,7 +1597,7 @@ ${session.id}`.toLowerCase().includes(word))).sort((a, b) => listCursor.compare(
1583
1597
  throw new RpcError(ERROR.failed, "alpd could not read the workspace file");
1584
1598
  }
1585
1599
  }
1586
- const capabilities = [...runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : [], CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : [], ...schedules ? [CAPABILITY.schedule] : [], ...registry ? ["workspace.registry", CAPABILITY.workspaceGit] : [], CAPABILITY.workspaceGitFacts, ...worktrees ? ["workspace.worktree"] : [], ...attachments ? [CAPABILITY.attachments] : [], ...conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : [], ...conversation?.reloads ? [CAPABILITY.sessionReload] : [], ...conversation?.configures ? [CAPABILITY.sessionConfigureLive] : [], ...conversation ? [CAPABILITY.sessionResumeCommand] : [], ...modelCatalog ? [CAPABILITY.catalogLive] : [], ...operations.capabilities];
1600
+ const capabilities = [...runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : [], ...runtime.commands ? [CAPABILITY.sessionCommands] : [], CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : [], ...schedules ? [CAPABILITY.schedule] : [], ...registry ? ["workspace.registry", CAPABILITY.workspaceGit] : [], CAPABILITY.workspaceGitFacts, ...worktrees ? ["workspace.worktree"] : [], ...attachments ? [CAPABILITY.attachments] : [], ...conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : [], ...conversation?.reloads ? [CAPABILITY.sessionReload] : [], ...conversation?.configures ? [CAPABILITY.sessionConfigureLive] : [], ...conversation ? [CAPABILITY.sessionResumeCommand] : [], ...modelCatalog ? [CAPABILITY.catalogLive] : [], ...operations.capabilities];
1587
1601
  function fits(response) {
1588
1602
  if (frameBytes(response) <= MAX_FRAME) return response;
1589
1603
  log.warn("a response exceeded the frame size limit", { code: "ALP_IPC_RESPONSE_TOO_LARGE", requestId: String(response.id) });
@@ -1,17 +1,10 @@
1
1
  // packages/daemon/src/windows-terminal.ts
2
- import { existsSync } from "node:fs";
3
2
  import { createRequire } from "node:module";
4
- import path from "node:path";
5
- function packagedNodePty() {
6
- const assets = globalThis[Symbol.for("alp.packaged")]?.assetDir?.();
7
- const entry = assets ? path.join(assets, "node-pty", "lib", "index.js") : void 0;
8
- return entry && existsSync(entry) ? entry : void 0;
9
- }
10
3
  var loaded;
11
4
  function loadNodePty() {
12
5
  if (loaded === void 0) {
13
6
  try {
14
- loaded = createRequire(import.meta.url)(packagedNodePty() ?? "node-pty");
7
+ loaded = createRequire(import.meta.url)("node-pty");
15
8
  } catch {
16
9
  loaded = null;
17
10
  }
@@ -29,8 +22,7 @@ var windowsPtySpawn = (file, args, options) => {
29
22
  if (options.signal?.aborted) throw new Error("Terminal startup cancelled");
30
23
  const pty = loadNodePty();
31
24
  if (!pty) throw new Error("node-pty is unavailable on this host");
32
- const spawnOptions = { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true, ...packagedNodePty() ? { useConptyDll: true } : {} };
33
- const child = typeof process.versions.bun === "string" ? spawnUnderBun(pty, file, args, spawnOptions) : pty.spawn(file, args, spawnOptions);
25
+ const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
34
26
  let killed = false;
35
27
  return {
36
28
  pid: child.pid,
@@ -56,64 +48,6 @@ var windowsPtySpawn = (file, args, options) => {
56
48
  onExit: (listener) => child.onExit(({ exitCode, signal }) => listener({ exitCode, signal }))
57
49
  };
58
50
  };
59
- function spawnUnderBun(pty, file, args, options) {
60
- const load = createRequire(import.meta.url);
61
- const fs = load("node:fs");
62
- const net = load("node:net");
63
- const Socket = net.Socket;
64
- function InputSocket(...rest) {
65
- const [opts] = rest;
66
- if (opts && typeof opts.fd === "number" && opts.writable === true && opts.readable === false) return fdWriter(fs, opts.fd);
67
- return new Socket(...rest);
68
- }
69
- InputSocket.prototype = Socket.prototype;
70
- net.Socket = InputSocket;
71
- try {
72
- return pty.spawn(file, args, options);
73
- } finally {
74
- net.Socket = Socket;
75
- }
76
- }
77
- function fdWriter(fs, fd) {
78
- let queue = Promise.resolve();
79
- let closed = false;
80
- let failed = false;
81
- const writer = {
82
- readable: false,
83
- writable: true,
84
- setEncoding() {
85
- return writer;
86
- },
87
- write(data) {
88
- if (closed || failed) return false;
89
- const bytes = typeof data === "string" ? Buffer.from(data, "utf8") : Buffer.from(data);
90
- queue = queue.then(() => new Promise((resolve) => {
91
- const rest = (offset) => {
92
- if (closed || failed || offset >= bytes.length) return resolve();
93
- fs.write(fd, bytes, offset, bytes.length - offset, null, (error, written) => {
94
- if (error) {
95
- failed = true;
96
- writer.writable = false;
97
- return resolve();
98
- }
99
- rest(offset + written);
100
- });
101
- };
102
- rest(0);
103
- }));
104
- return true;
105
- },
106
- destroy() {
107
- if (closed) return writer;
108
- closed = true;
109
- writer.writable = false;
110
- void queue.then(() => fs.close(fd, () => {
111
- }));
112
- return writer;
113
- }
114
- };
115
- return writer;
116
- }
117
51
  export {
118
52
  loadNodePty,
119
53
  windowsPtySpawn,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-daemon",
3
- "version": "0.0.1-beta.6",
3
+ "version": "0.0.1-beta.7",
4
4
  "type": "module",
5
5
  "description": "ALP daemon module",
6
6
  "files": [
@@ -129,10 +129,10 @@
129
129
  "node": ">=22.12"
130
130
  },
131
131
  "dependencies": {
132
- "@anhlp/alp-core": "0.0.1-beta.6",
133
- "@anhlp/alp-runtime": "0.0.1-beta.6",
134
- "@anhlp/alp-client": "0.0.1-beta.6",
135
- "@anhlp/alp-protocol": "0.0.1-beta.6",
132
+ "@anhlp/alp-core": "0.0.1-beta.7",
133
+ "@anhlp/alp-runtime": "0.0.1-beta.7",
134
+ "@anhlp/alp-client": "0.0.1-beta.7",
135
+ "@anhlp/alp-protocol": "0.0.1-beta.7",
136
136
  "@anthropic-ai/sdk": "^0.131.0",
137
137
  "ws": "^8.22.0",
138
138
  "zod": "4.4.3",
@@ -12,11 +12,8 @@ const sha = (value: Buffer) => createHash('sha256').update(value).digest('hex');
12
12
  function binary() {
13
13
  const libc = process.platform === 'linux' ? (process.report?.getReport() as { header?: { glibcVersionRuntime?: string } })?.header?.glibcVersionRuntime ? 'glibc' : 'musl' : undefined;
14
14
  const slot = [process.platform, process.arch, libc].filter(Boolean).join('-');
15
- // The ALP executable (t-1e02) extracts its helper; registerPackaged in @anhlp/alp-core/packaged publishes assetDir here.
16
- // Read through globalThis so this shipped adapter stays free of package imports.
17
- const assets = (globalThis as { [key: symbol]: { assetDir?: () => string | undefined } | undefined })[Symbol.for('alp.packaged')]?.assetDir?.();
18
- const adjacent = assets ? path.join(assets, 'terminal-native') : path.join(path.dirname(fileURLToPath(import.meta.url)), 'terminal-native');
19
- const dir = assets || existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../native');
15
+ const adjacent = path.join(path.dirname(fileURLToPath(import.meta.url)), 'terminal-native');
16
+ const dir = existsSync(adjacent) ? adjacent : path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../native');
20
17
  const file = path.join(dir, 'prebuilt', slot, 'terminal-owner');
21
18
  const manifest = JSON.parse(readFileSync(path.join(path.dirname(file), 'manifest.json'), 'utf8'));
22
19
  if (!statSync(file).isFile() || manifest.protocol !== 1 || manifest.slot !== slot || manifest.source !== sha(readFileSync(path.join(dir, 'terminal-owner.c'))) || manifest.sha256 !== sha(readFileSync(file))) throw new Error('Native helper manifest mismatch');
package/src/server.ts CHANGED
@@ -1600,6 +1600,20 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1600
1600
  catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
1601
1601
  },
1602
1602
 
1603
+ /** The slash commands and skills a live session's composer offers after "/" (t-f628). */
1604
+ async 'session.commands'(_connection, { sessionId }) {
1605
+ if (typeof sessionId !== 'string' || !sessionId) throw new RpcError(-32602, 'sessionId is required');
1606
+ if (!runtime.commands) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd lists no commands (capability session.commands is not listed)');
1607
+ if (!runtime.snapshot(sessionId)) throw new RpcError(ERROR.notFound, `No session ${sessionId}`, { reason: 'not_found' });
1608
+ try {
1609
+ const listed = await runtime.commands(sessionId);
1610
+ const seen = new Set<string>();
1611
+ const commands = listed.filter(command => /^[^\s\u0000-\u001f\u007f]{1,256}$/.test(command.name) && !seen.has(command.name) && seen.add(command.name)).slice(0, 1000)
1612
+ .map(command => ({ name: command.name, description: command.description.slice(0, 4096), ...(command.argumentHint ? { argumentHint: command.argumentHint.slice(0, 256) } : {}), kind: command.kind }));
1613
+ return { commands };
1614
+ } catch (error) { throw new RpcError(ERROR.unavailable, error instanceof Error ? error.message : String(error)); }
1615
+ },
1616
+
1603
1617
  /** The ALP CLI command that follows a session in a terminal, for the clipboard (§12.8). */
1604
1618
  async 'session.resumeCommand'(_connection, { sessionId }) {
1605
1619
  if (!conversation) throw new RpcError(RPC_ERROR.methodNotFound, 'This alpd has no resume command (capability session.resumeCommand is not listed)');
@@ -1888,7 +1902,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1888
1902
  }
1889
1903
 
1890
1904
  /** 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];
1905
+ const capabilities = [...(runtime.interruptTurn ? [CAPABILITY.sessionInterruptTurn] : []), ...(runtime.commands ? [CAPABILITY.sessionCommands] : []), CAPABILITY.attachAfter, CAPABILITY.extensionMethods, CAPABILITY.sessionListPage, CAPABILITY.questionWatch, CAPABILITY.questionWatchTurns, CAPABILITY.sessionAttention, CAPABILITY.workspaceFiles, CAPABILITY.workspaceFilesRead, CAPABILITY.workspaceFilesBrowse, CAPABILITY.hostDirectories, CAPABILITY.promptImages, ...(store ? [CAPABILITY.promptReceipts, CAPABILITY.sessionHistory] : []), ...(schedules ? [CAPABILITY.schedule] : []), ...(registry ? ['workspace.registry', CAPABILITY.workspaceGit] : []), CAPABILITY.workspaceGitFacts, ...(worktrees ? ['workspace.worktree'] : []), ...(attachments ? [CAPABILITY.attachments] : []), ...(conversation?.enabled ? [CAPABILITY.sessionFork, CAPABILITY.sessionRewind] : []), ...(conversation?.reloads ? [CAPABILITY.sessionReload] : []), ...(conversation?.configures ? [CAPABILITY.sessionConfigureLive] : []), ...(conversation ? [CAPABILITY.sessionResumeCommand] : []), ...(modelCatalog ? [CAPABILITY.catalogLive] : []), ...operations.capabilities];
1892
1906
 
1893
1907
  /** A response too large for the wire becomes an error the client can read. */
1894
1908
  function fits(response: { jsonrpc: '2.0'; id: string | number | null; result?: unknown; error?: unknown }) {
@@ -3,9 +3,7 @@
3
3
  * There is no protection helper on Windows: closing a terminal kills its pty (node-pty `kill`),
4
4
  * which ends the shell; processes it started may keep running. Terminals report `protection: 'none'`.
5
5
  */
6
- import { existsSync } from 'node:fs';
7
6
  import { createRequire } from 'node:module';
8
- import path from 'node:path';
9
7
  import type { PtySpawn } from './terminals.js';
10
8
 
11
9
  type NodePty = { spawn(file: string, args: string[], options: Record<string, unknown>): {
@@ -13,22 +11,11 @@ type NodePty = { spawn(file: string, args: string[], options: Record<string, unk
13
11
  onData(listener: (data: string) => void): { dispose(): void }; onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };
14
12
  } };
15
13
 
16
- /**
17
- * In the ALP executable (t-1e02) node-pty is not in node_modules: the build embeds its JavaScript and
18
- * the win32 prebuilt (conpty.node, conpty/conpty.dll, OpenConsole.exe), extracted with the other
19
- * assets. registerPackaged publishes assetDir on globalThis; read it there so this adapter needs no package import.
20
- */
21
- function packagedNodePty(): string | undefined {
22
- const assets = (globalThis as { [key: symbol]: { assetDir?: () => string | undefined } | undefined })[Symbol.for('alp.packaged')]?.assetDir?.();
23
- const entry = assets ? path.join(assets, 'node-pty', 'lib', 'index.js') : undefined;
24
- return entry && existsSync(entry) ? entry : undefined;
25
- }
26
-
27
14
  let loaded: NodePty | null | undefined;
28
15
  /** node-pty, or undefined when it cannot load on this host. */
29
16
  export function loadNodePty(): NodePty | undefined {
30
17
  if (loaded === undefined) {
31
- try { loaded = createRequire(import.meta.url)(packagedNodePty() ?? 'node-pty') as NodePty; } catch { loaded = null; }
18
+ try { loaded = createRequire(import.meta.url)('node-pty') as NodePty; } catch { loaded = null; }
32
19
  }
33
20
  return loaded ?? undefined;
34
21
  }
@@ -47,11 +34,7 @@ export const windowsPtySpawn: PtySpawn = (file, args, options) => {
47
34
  if (options.signal?.aborted) throw new Error('Terminal startup cancelled');
48
35
  const pty = loadNodePty();
49
36
  if (!pty) throw new Error('node-pty is unavailable on this host');
50
- // The executable uses the conpty.dll and OpenConsole.exe it embeds: with the system ConPTY, node-pty's
51
- // kill() forks a console-list helper through process.execPath, which there is alp.exe (it would refuse
52
- // the script and leave node-pty waiting 5 s). With the DLL, kill() ends the session by closing input.
53
- const spawnOptions = { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true, ...(packagedNodePty() ? { useConptyDll: true } : {}) };
54
- const child = typeof process.versions.bun === 'string' ? spawnUnderBun(pty, file, args, spawnOptions) : pty.spawn(file, args, spawnOptions);
37
+ const child = pty.spawn(file, args, { name: options.name, cols: options.cols, rows: options.rows, cwd: options.cwd, env: options.env, useConpty: true });
55
38
  let killed = false;
56
39
  return {
57
40
  pid: child.pid,
@@ -64,60 +47,3 @@ export const windowsPtySpawn: PtySpawn = (file, args, options) => {
64
47
  };
65
48
  };
66
49
 
67
- /**
68
- * The ALP executable runs on Bun (t-1e02), where node-pty's input stream, `new net.Socket({ fd })`
69
- * around the fd it opens on ConPTY's input pipe, takes the fd but never writes to it (output, read
70
- * by a worker, works; probed on windows-2022 with Bun 1.4.2). While node-pty spawns (synchronously),
71
- * hand it a small writer for that fd instead: the same calls node-pty makes on its input socket
72
- * (setEncoding, write, destroy, readable), with writes in order through fs.write and the fd closed
73
- * once on destroy.
74
- */
75
- function spawnUnderBun(pty: NodePty, file: string, args: string[], options: Record<string, unknown>) {
76
- const load = createRequire(import.meta.url);
77
- const fs = load('node:fs') as typeof import('node:fs');
78
- const net = load('node:net') as { Socket: new (...args: unknown[]) => unknown };
79
- const Socket = net.Socket;
80
- function InputSocket(this: unknown, ...rest: unknown[]) {
81
- const [opts] = rest as [{ fd?: unknown; writable?: boolean; readable?: boolean } | undefined];
82
- if (opts && typeof opts.fd === 'number' && opts.writable === true && opts.readable === false) return fdWriter(fs, opts.fd);
83
- return new Socket(...rest);
84
- }
85
- InputSocket.prototype = Socket.prototype;
86
- net.Socket = InputSocket as unknown as typeof Socket;
87
- try { return pty.spawn(file, args, options); } finally { net.Socket = Socket; }
88
- }
89
-
90
- /** A write-only stand-in for net.Socket over a pipe fd: ordered writes, closed once; after a failed write it drops the rest. */
91
- function fdWriter(fs: typeof import('node:fs'), fd: number) {
92
- let queue: Promise<void> = Promise.resolve();
93
- let closed = false;
94
- let failed = false;
95
- const writer = {
96
- readable: false,
97
- writable: true,
98
- setEncoding() { return writer; },
99
- write(data: string | Uint8Array) {
100
- if (closed || failed) return false;
101
- const bytes = typeof data === 'string' ? Buffer.from(data, 'utf8') : Buffer.from(data);
102
- queue = queue.then(() => new Promise<void>(resolve => {
103
- const rest = (offset: number): void => {
104
- if (closed || failed || offset >= bytes.length) return resolve();
105
- fs.write(fd, bytes, offset, bytes.length - offset, null, (error, written) => {
106
- if (error) { failed = true; writer.writable = false; return resolve(); }
107
- rest(offset + written);
108
- });
109
- };
110
- rest(0);
111
- }));
112
- return true;
113
- },
114
- destroy() {
115
- if (closed) return writer;
116
- closed = true;
117
- writer.writable = false;
118
- void queue.then(() => fs.close(fd, () => {}));
119
- return writer;
120
- },
121
- };
122
- return writer;
123
- }