@deepseek-ai/dsh-subprocess-local 0.2.2-alpha.3 → 0.2.2-rc.2
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/README.i18n.yaml +4 -4
- package/README.md +2 -2
- package/README.zh.md +2 -2
- package/lib/index.js +27 -13
- package/lib/{runner-launch-B2zsQ1Dz.js → runner-launch-CKTiL8M8.js} +41 -14
- package/lib/runner.js +8 -12
- package/lib/types/bin.d.ts.map +1 -0
- package/lib/types/bin.js.map +1 -0
- package/lib/types/control-spawn.d.ts.map +1 -0
- package/lib/types/control-spawn.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/linux-execve.d.ts +1 -1
- package/lib/types/linux-execve.d.ts.map +1 -0
- package/lib/types/linux-execve.js.map +1 -0
- package/lib/types/linux-scope-selector.d.ts.map +1 -0
- package/lib/types/linux-scope-selector.js.map +1 -0
- package/lib/types/linux-scope.d.ts.map +1 -0
- package/lib/types/linux-scope.js.map +1 -0
- package/lib/types/managed-owner.d.ts.map +1 -0
- package/lib/types/managed-owner.js.map +1 -0
- package/lib/types/output.d.ts.map +1 -0
- package/lib/types/output.js.map +1 -0
- package/lib/types/process-inspector.d.ts +9 -5
- package/lib/types/process-inspector.d.ts.map +1 -0
- package/lib/types/process-inspector.js.map +1 -0
- package/lib/types/runner-launch.d.ts +1 -1
- package/lib/types/runner-launch.d.ts.map +1 -0
- package/lib/types/runner-launch.js.map +1 -0
- package/lib/types/runner-protocol.d.ts +2 -0
- package/lib/types/runner-protocol.d.ts.map +1 -0
- package/lib/types/runner-protocol.js.map +1 -0
- package/lib/types/shell-activity.d.ts.map +1 -0
- package/lib/types/shell-activity.js.map +1 -0
- package/lib/types/spawn-runner.d.ts +2 -1
- package/lib/types/spawn-runner.d.ts.map +1 -0
- package/lib/types/spawn-runner.js.map +1 -0
- package/lib/types/spawn.d.ts +2 -2
- package/lib/types/spawn.d.ts.map +1 -0
- package/lib/types/spawn.js.map +1 -0
- package/lib/types/terminal.d.ts.map +1 -0
- package/lib/types/terminal.js.map +1 -0
- package/lib/types/windows-inspector.d.ts.map +1 -0
- package/lib/types/windows-inspector.js.map +1 -0
- package/lib/types/windows-job.d.ts.map +1 -0
- package/lib/types/windows-job.js.map +1 -0
- package/package.json +14 -11
- package/src/bin.ts +25 -0
- package/src/control-spawn.ts +35 -0
- package/src/index.ts +387 -0
- package/src/linux-execve.ts +92 -0
- package/src/linux-scope-selector.ts +101 -0
- package/src/linux-scope.ts +726 -0
- package/src/managed-owner.ts +56 -0
- package/src/output.ts +313 -0
- package/src/process-inspector.ts +560 -0
- package/src/runner-launch.ts +315 -0
- package/src/runner-protocol.ts +281 -0
- package/src/shell-activity.ts +131 -0
- package/src/spawn-runner.ts +488 -0
- package/src/spawn.ts +500 -0
- package/src/terminal.ts +479 -0
- package/src/windows-inspector.ts +346 -0
- package/src/windows-job.ts +269 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local Service Provider for the subprocess capability seam. Each spawn owns a
|
|
3
|
+
* platform-selected managed range with the spec's per-stream stdio dispositions.
|
|
4
|
+
* Normal disposal terminates and joins live ranges; Node's synchronous exit
|
|
5
|
+
* phase force-stops any ranges the service still owns. It has no config: every
|
|
6
|
+
* disposition and limit arrives on the spec, so deployment-varying choices
|
|
7
|
+
* stay with the caller's config (the bash executor's, the LSP host's, …).
|
|
8
|
+
* @module @deepseek-ai/dsh-subprocess-local
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { constants } from 'node:fs'
|
|
12
|
+
import { access, stat } from 'node:fs/promises'
|
|
13
|
+
import { userInfo } from 'node:os'
|
|
14
|
+
import { delimiter, extname, isAbsolute, resolve } from 'node:path'
|
|
15
|
+
import type { Duplex } from 'node:stream'
|
|
16
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
17
|
+
import type * as NodePty from 'node-pty'
|
|
18
|
+
import type { IPtyForkOptions, IWindowsPtyForkOptions } from 'node-pty'
|
|
19
|
+
import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require'
|
|
20
|
+
import { SubprocessRuntime, SubprocessError, SubprocessExecutableNotFoundError } from '@deepseek-ai/dsh-subprocess'
|
|
21
|
+
import type {
|
|
22
|
+
SubprocessHandle,
|
|
23
|
+
SubprocessSpawnSpec,
|
|
24
|
+
SubprocessTerminalHandle,
|
|
25
|
+
SubprocessTerminalEnvironment,
|
|
26
|
+
SubprocessTerminalSpawnSpec,
|
|
27
|
+
} from '@deepseek-ai/dsh-subprocess'
|
|
28
|
+
import {
|
|
29
|
+
bindManagedProcess,
|
|
30
|
+
childEnv,
|
|
31
|
+
spawnSubprocess,
|
|
32
|
+
validateSubprocessSpec,
|
|
33
|
+
} from './spawn.ts'
|
|
34
|
+
import { logSpillFailure, prepareManagedProcessBinding } from './output.ts'
|
|
35
|
+
import type { LocalSubprocessHandle, SpawnInternals } from './spawn.ts'
|
|
36
|
+
import {
|
|
37
|
+
confirmLinuxManager,
|
|
38
|
+
LinuxScopeNotStartedError,
|
|
39
|
+
launchLinuxScope,
|
|
40
|
+
linuxManagerListener,
|
|
41
|
+
prepareLinuxTerminalScope,
|
|
42
|
+
probeLinuxNative,
|
|
43
|
+
signalLinuxDirectProcess,
|
|
44
|
+
systemdRunIdentity,
|
|
45
|
+
} from './linux-scope.ts'
|
|
46
|
+
import { LinuxScopeSelector } from './linux-scope-selector.ts'
|
|
47
|
+
import type { LinuxScopeDecision } from './linux-scope-selector.ts'
|
|
48
|
+
import { launchWindowsJob, probeWindowsJob } from './windows-job.ts'
|
|
49
|
+
import { targetEnvironment } from './runner-launch.ts'
|
|
50
|
+
import { createProcessInspector } from './process-inspector.ts'
|
|
51
|
+
import type { ProcessInspector } from './process-inspector.ts'
|
|
52
|
+
import { LocalTerminalHandle } from './terminal.ts'
|
|
53
|
+
import { prepareShellActivity } from './shell-activity.ts'
|
|
54
|
+
|
|
55
|
+
const requireNodePty = createLazyRequire<typeof NodePty>('node-pty', import.meta.url)
|
|
56
|
+
|
|
57
|
+
/** Load node-pty, reporting a missing or unloadable native module as `SUBPROCESS_PTY_UNAVAILABLE`. */
|
|
58
|
+
function loadNodePty(): typeof NodePty {
|
|
59
|
+
try {
|
|
60
|
+
return requireNodePty()
|
|
61
|
+
} catch (error) {
|
|
62
|
+
throw new SubprocessError(
|
|
63
|
+
`subprocess-local: terminals are unavailable because node-pty cannot be loaded: ${String(error)}`,
|
|
64
|
+
'SUBPROCESS_PTY_UNAVAILABLE',
|
|
65
|
+
{ cause: error },
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Local subprocess service: platform-selected managed ranges, Node-shaped stdio
|
|
72
|
+
* dispositions (raw pipes, inherit, bounded tail-keep collection with spill
|
|
73
|
+
* files), credential-scrubbed environment, and provider-owned range signalling.
|
|
74
|
+
* POSIX paths stage TERM before KILL; Windows paths terminate immediately.
|
|
75
|
+
* JavaScript-observable host exit also performs synchronous final termination.
|
|
76
|
+
*/
|
|
77
|
+
export class LocalSubprocessRuntime extends SubprocessRuntime {
|
|
78
|
+
/** Live handles retained for normal disposal and synchronous host-exit finalization. */
|
|
79
|
+
private live = new Set<LocalSubprocessHandle>()
|
|
80
|
+
/** Live terminals retained through normal quiescence or host-exit finalization. */
|
|
81
|
+
private terminals = new Set<LocalTerminalHandle>()
|
|
82
|
+
/** Caller endpoints retained until close, independently of managed process lifetime. */
|
|
83
|
+
private controlChannels = new Set<Duplex>()
|
|
84
|
+
/** Test hook: process, spill, and platform operations forwarded to spawnSubprocess. */
|
|
85
|
+
internals: SpawnInternals = {}
|
|
86
|
+
/** Provider-lifetime latch suppressing repeated weaker-containment warnings. */
|
|
87
|
+
private fallbackWarningIssued = false
|
|
88
|
+
/**
|
|
89
|
+
* Linux native containment decisions. Each probe is a spawnSync that blocks the event loop and forks the
|
|
90
|
+
* host, so the selector reruns it only after an event invalidates the previous verdict.
|
|
91
|
+
*/
|
|
92
|
+
private readonly linuxScope = new LinuxScopeSelector({
|
|
93
|
+
probe: () => probeLinuxNative(),
|
|
94
|
+
managerListener: () => linuxManagerListener(),
|
|
95
|
+
confirmManager: () => confirmLinuxManager(),
|
|
96
|
+
launcherIdentity: () => systemdRunIdentity(),
|
|
97
|
+
})
|
|
98
|
+
/** Scope decision of the launch in progress; selectContainmentMode sets it immediately before the launch reads it. */
|
|
99
|
+
private linuxScopeDecision: Extract<LinuxScopeDecision, { kind: 'scope' }> | undefined
|
|
100
|
+
/** Test hook for platform process inspection; production resolves lazily on terminal spawn. */
|
|
101
|
+
terminalInspector: ProcessInspector | undefined
|
|
102
|
+
|
|
103
|
+
constructor(ctx: Context) {
|
|
104
|
+
super(ctx)
|
|
105
|
+
ctx.effect(() => {
|
|
106
|
+
const onHostExit = (): void => { this.terminateForHostExit() }
|
|
107
|
+
process.prependListener('exit', onHostExit)
|
|
108
|
+
return async () => {
|
|
109
|
+
await this.disposeManagedProcesses()
|
|
110
|
+
process.off('exit', onHostExit)
|
|
111
|
+
}
|
|
112
|
+
}, 'local subprocess teardown')
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Spill failures reach the plugin logger; the log line is the only trace of why a result has no spill path. */
|
|
116
|
+
private readonly reportSpillFailure = logSpillFailure(this.ctx.logger, 'subprocess-local')
|
|
117
|
+
|
|
118
|
+
private terminateForHostExit(): void {
|
|
119
|
+
for (const handle of this.live) {
|
|
120
|
+
try {
|
|
121
|
+
handle.terminateForHostExit()
|
|
122
|
+
} catch (_ordinaryRangeTerminationFailed) {
|
|
123
|
+
// Host exit cannot await or report one target; continue with the rest.
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (const terminal of this.terminals) {
|
|
127
|
+
try {
|
|
128
|
+
terminal.terminateForHostExit()
|
|
129
|
+
} catch (_terminalTerminationFailed) {
|
|
130
|
+
// One terminal must not prevent final termination of another target.
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private async disposeManagedProcesses(): Promise<void> {
|
|
136
|
+
// Request termination, then await MANAGED-RANGE exit — not just the
|
|
137
|
+
// direct command's settlement — so even a surviving descendant cannot
|
|
138
|
+
// outlive the fiber. Keep both sets authoritative while these waits are
|
|
139
|
+
// pending so a shorter process-level exit bound can still force-kill them.
|
|
140
|
+
const pending: Promise<unknown>[] = []
|
|
141
|
+
for (const handle of this.live) {
|
|
142
|
+
handle.terminate()
|
|
143
|
+
// Direct result and range observation are independent. Start both so an
|
|
144
|
+
// unreadable owner cannot hide behind a result that never settles.
|
|
145
|
+
pending.push(Promise.all([
|
|
146
|
+
handle.done.catch(() => {}),
|
|
147
|
+
handle.waitForExit(),
|
|
148
|
+
]).then(() => { this.live.delete(handle) }))
|
|
149
|
+
}
|
|
150
|
+
for (const terminal of this.terminals) {
|
|
151
|
+
pending.push(terminal.terminate().then(() => { this.terminals.delete(terminal) }))
|
|
152
|
+
}
|
|
153
|
+
const outcomes = await Promise.allSettled(pending)
|
|
154
|
+
await Promise.all([...this.controlChannels].map(control => new Promise<void>((resolveClose) => {
|
|
155
|
+
control.once('close', () => { resolveClose() })
|
|
156
|
+
control.destroy()
|
|
157
|
+
})))
|
|
158
|
+
this.controlChannels.clear()
|
|
159
|
+
const failures: unknown[] = []
|
|
160
|
+
for (const outcome of outcomes) {
|
|
161
|
+
if (outcome.status === 'rejected') failures.push(outcome.reason)
|
|
162
|
+
}
|
|
163
|
+
if (failures.length > 0) this.terminateForHostExit()
|
|
164
|
+
if (failures.length === 1) throw failures[0]
|
|
165
|
+
if (failures.length > 1) throw new AggregateError(failures, 'local subprocess teardown failed')
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async resolveExecutable(
|
|
169
|
+
command: string,
|
|
170
|
+
env?: Readonly<Record<string, string>>,
|
|
171
|
+
signal?: AbortSignal,
|
|
172
|
+
): Promise<string> {
|
|
173
|
+
if (command.length === 0) throw new Error('subprocess-local: executable must be non-empty')
|
|
174
|
+
signal?.throwIfAborted()
|
|
175
|
+
const environment = childEnv(env)
|
|
176
|
+
const absolute = isAbsolute(command)
|
|
177
|
+
if (!absolute && (command.includes('/') || (process.platform === 'win32' && command.includes('\\')))) {
|
|
178
|
+
throw new Error(
|
|
179
|
+
`subprocess-local: command ${JSON.stringify(command)} is a relative path; use an absolute path or a bare PATH name`,
|
|
180
|
+
)
|
|
181
|
+
}
|
|
182
|
+
const candidates = absolute ? [command] : this.executableCandidates(command, environment)
|
|
183
|
+
for (const candidate of candidates) {
|
|
184
|
+
signal?.throwIfAborted()
|
|
185
|
+
try {
|
|
186
|
+
const info = await stat(candidate)
|
|
187
|
+
if (!info.isFile()) continue
|
|
188
|
+
await access(candidate, constants.X_OK)
|
|
189
|
+
signal?.throwIfAborted()
|
|
190
|
+
return candidate
|
|
191
|
+
} catch {
|
|
192
|
+
// Try the next PATH candidate; the final miss receives one stable error.
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
signal?.throwIfAborted()
|
|
196
|
+
throw new SubprocessExecutableNotFoundError(absolute
|
|
197
|
+
? `subprocess-local: command ${JSON.stringify(command)} is not an executable file`
|
|
198
|
+
: `subprocess-local: command ${JSON.stringify(command)} was not found on PATH`)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
private executableCandidates(command: string, env: NodeJS.ProcessEnv): string[] {
|
|
202
|
+
const path = environmentValue(env, 'PATH') ?? ''
|
|
203
|
+
const extensions = process.platform === 'win32' && extname(command) === ''
|
|
204
|
+
? (environmentValue(env, 'PATHEXT') ?? '.COM;.EXE;.BAT;.CMD').split(';')
|
|
205
|
+
: ['']
|
|
206
|
+
return path.split(delimiter).flatMap(directory =>
|
|
207
|
+
extensions.map(extension => resolve(process.cwd(), directory, command + extension)))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
spawn(spec: SubprocessSpawnSpec): SubprocessHandle {
|
|
211
|
+
validateSubprocessSpec(spec)
|
|
212
|
+
const env = targetEnvironment(spec)
|
|
213
|
+
const containmentMode = this.selectContainmentMode('ordinary')
|
|
214
|
+
let handle: LocalSubprocessHandle
|
|
215
|
+
const internals: SpawnInternals = { ...this.internals, onSpillFailure: this.reportSpillFailure }
|
|
216
|
+
if (containmentMode === 'fallback') {
|
|
217
|
+
handle = spawnSubprocess(spec, internals)
|
|
218
|
+
} else {
|
|
219
|
+
const binding = prepareManagedProcessBinding(internals)
|
|
220
|
+
const linuxScope = containmentMode === 'linux-scope' ? this.linuxScopeDecision : undefined
|
|
221
|
+
const launch = linuxScope === undefined
|
|
222
|
+
? launchWindowsJob(spec, env)
|
|
223
|
+
: launchLinuxScope(spec, env, linuxScope.literalArgv)
|
|
224
|
+
handle = bindManagedProcess(spec, launch, binding)
|
|
225
|
+
if (linuxScope !== undefined) this.watchLinuxScopeStart(handle.done, linuxScope.generation)
|
|
226
|
+
}
|
|
227
|
+
this.live.add(handle)
|
|
228
|
+
const control = handle.control
|
|
229
|
+
if (control !== undefined) {
|
|
230
|
+
this.controlChannels.add(control)
|
|
231
|
+
control.once('close', () => { this.controlChannels.delete(control) })
|
|
232
|
+
}
|
|
233
|
+
// Release ownership only once the whole managed range is gone, not at direct-child
|
|
234
|
+
// settlement — a TERM-trapping helper that outlives the leader must stay
|
|
235
|
+
// owned so teardown can still escalate it. For the common no-survivor
|
|
236
|
+
// case waitForExit resolves immediately after settlement.
|
|
237
|
+
const release = (): Promise<void> =>
|
|
238
|
+
handle.waitForExit().then(() => { this.live.delete(handle) })
|
|
239
|
+
void handle.done.then(release, release).catch(() => {})
|
|
240
|
+
return handle
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Probe again before the next launch when a scope launched under generation never started its target. */
|
|
244
|
+
private watchLinuxScopeStart(done: Promise<unknown>, generation: number): void {
|
|
245
|
+
void done.catch((error: unknown) => {
|
|
246
|
+
if (error instanceof LinuxScopeNotStartedError) this.linuxScope.scopeNotStarted(generation)
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private selectContainmentMode(
|
|
251
|
+
kind: 'ordinary' | 'terminal',
|
|
252
|
+
): 'linux-scope' | 'windows-job' | 'fallback' {
|
|
253
|
+
const platform = this.internals.platform ?? process.platform
|
|
254
|
+
let fallbackReason: string | undefined
|
|
255
|
+
if (platform === 'linux') {
|
|
256
|
+
const decision = this.linuxScope.select()
|
|
257
|
+
const probe = decision.probe === undefined ? '' : `, probed after ${decision.probe}`
|
|
258
|
+
this.ctx.logger.debug(`linux native containment: ${decision.kind} (${decision.reason}${probe})`)
|
|
259
|
+
if (decision.kind === 'scope') {
|
|
260
|
+
this.linuxScopeDecision = decision
|
|
261
|
+
return 'linux-scope'
|
|
262
|
+
}
|
|
263
|
+
fallbackReason = 'the current user-systemd scope or private bootstrap is unavailable'
|
|
264
|
+
}
|
|
265
|
+
if (kind === 'ordinary' && platform === 'win32') {
|
|
266
|
+
const available = probeWindowsJob()
|
|
267
|
+
if (available) return 'windows-job'
|
|
268
|
+
}
|
|
269
|
+
this.warnFallback(platform, kind, fallbackReason)
|
|
270
|
+
return 'fallback'
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private warnFallback(
|
|
274
|
+
platform: NodeJS.Platform,
|
|
275
|
+
kind: 'ordinary' | 'terminal',
|
|
276
|
+
selectedReason?: string,
|
|
277
|
+
): void {
|
|
278
|
+
if (this.fallbackWarningIssued) return
|
|
279
|
+
this.fallbackWarningIssued = true
|
|
280
|
+
const reason = selectedReason ?? (platform === 'darwin'
|
|
281
|
+
? 'macOS has no supported persistent process-range owner'
|
|
282
|
+
: platform === 'win32'
|
|
283
|
+
? kind === 'terminal'
|
|
284
|
+
? 'Windows ConPTY remains outside Job containment'
|
|
285
|
+
: 'the Win32 Job runner is unavailable'
|
|
286
|
+
: `platform ${platform} has no native managed range`)
|
|
287
|
+
this.ctx.logger.warn(
|
|
288
|
+
`subprocess-local is using weaker process-tree containment because ${reason}; descendants that escape the process group or direct-parent tree are not guaranteed to terminate or delay waitForExit()`,
|
|
289
|
+
)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** @inheritdoc */
|
|
293
|
+
// oxlint-disable-next-line typescript/require-await -- Keep the provider promise rejection semantics for cancelled inspection.
|
|
294
|
+
async terminalEnvironment(signal?: AbortSignal): Promise<SubprocessTerminalEnvironment> {
|
|
295
|
+
signal?.throwIfAborted()
|
|
296
|
+
const platform = process.platform === 'win32' ? 'windows' : 'posix'
|
|
297
|
+
const defaultShell = platform === 'windows' ? process.env.ComSpec || undefined : process.env.SHELL || userInfo().shell || undefined
|
|
298
|
+
return { platform, ...defaultShell === undefined ? {} : { defaultShell } }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Local PTY allocation is synchronous, but the provider contract permits remote asynchronous allocation.
|
|
302
|
+
// oxlint-disable-next-line typescript/require-await -- Preserve promise rejection semantics at the async provider contract.
|
|
303
|
+
async spawnTerminal(spec: SubprocessTerminalSpawnSpec): Promise<SubprocessTerminalHandle> {
|
|
304
|
+
const file = spec.argv[0]
|
|
305
|
+
if (file === undefined || file.length === 0) {
|
|
306
|
+
throw new SubprocessError('subprocess-local: terminal argv must contain a program', 'SUBPROCESS_INVALID_ARGV')
|
|
307
|
+
}
|
|
308
|
+
spec.signal?.throwIfAborted()
|
|
309
|
+
const inspector = this.terminalInspector ?? createProcessInspector()
|
|
310
|
+
const containmentMode = this.selectContainmentMode('terminal')
|
|
311
|
+
const env = targetEnvironment(spec)
|
|
312
|
+
const platform = this.internals.platform ?? process.platform
|
|
313
|
+
const activity = prepareShellActivity(spec, env, platform)
|
|
314
|
+
const launch = activity === undefined ? spec : { ...spec, argv: activity.argv, env: activity.env }
|
|
315
|
+
const options: IPtyForkOptions | IWindowsPtyForkOptions = {
|
|
316
|
+
name: spec.terminalType,
|
|
317
|
+
rows: spec.rows,
|
|
318
|
+
cols: spec.cols,
|
|
319
|
+
cwd: spec.cwd,
|
|
320
|
+
env: { ...activity?.env ?? env, TERM: spec.terminalType },
|
|
321
|
+
// Windows' own console host (the standby pool runs Server 2022 and
|
|
322
|
+
// Windows 10 22H2) renders the persistent-pwsh prompt tail in a form the
|
|
323
|
+
// readiness path cannot match; the console host node-pty ships emits it
|
|
324
|
+
// verbatim, see [Agent Note](../../../../.agents/notes/implemented/bug-fix/2026-09-28-pty-bundled-console-host.md).
|
|
325
|
+
...(platform === 'win32' ? { useConptyDll: true } : {}),
|
|
326
|
+
}
|
|
327
|
+
const linuxScope = containmentMode === 'linux-scope' ? this.linuxScopeDecision : undefined
|
|
328
|
+
let scope: ReturnType<typeof prepareLinuxTerminalScope> | undefined
|
|
329
|
+
let terminal: NodePty.IPty
|
|
330
|
+
try {
|
|
331
|
+
scope = linuxScope === undefined
|
|
332
|
+
? undefined
|
|
333
|
+
: prepareLinuxTerminalScope(launch, { ...activity?.env ?? env, PWD: spec.cwd, TERM: spec.terminalType }, linuxScope.literalArgv)
|
|
334
|
+
if (scope !== undefined) { options.cwd = scope.cwd; options.env = scope.env }
|
|
335
|
+
terminal = loadNodePty().spawn(
|
|
336
|
+
scope?.command ?? file,
|
|
337
|
+
scope?.args ?? [...launch.argv.slice(1)],
|
|
338
|
+
options,
|
|
339
|
+
)
|
|
340
|
+
} catch (error) {
|
|
341
|
+
scope?.cleanup()
|
|
342
|
+
activity?.dispose()
|
|
343
|
+
throw error
|
|
344
|
+
}
|
|
345
|
+
// oxlint-disable-next-line eslint/prefer-const -- The owner can query readiness before the handle is published.
|
|
346
|
+
let handle: LocalTerminalHandle | undefined
|
|
347
|
+
const directSettlement = Promise.withResolvers<void>()
|
|
348
|
+
const owner = scope?.bindOwner({
|
|
349
|
+
running: () => handle?.running ?? true,
|
|
350
|
+
settled: directSettlement.promise,
|
|
351
|
+
// node-pty swallows signal errors; the scope owner requires their delivery result.
|
|
352
|
+
signal: signal => signalLinuxDirectProcess(terminal.pid, () => process.kill(terminal.pid, signal)),
|
|
353
|
+
})
|
|
354
|
+
handle = new LocalTerminalHandle(
|
|
355
|
+
terminal,
|
|
356
|
+
inspector,
|
|
357
|
+
spec.graceMs,
|
|
358
|
+
platform,
|
|
359
|
+
owner,
|
|
360
|
+
scope?.resolveOutcome,
|
|
361
|
+
activity,
|
|
362
|
+
() => { this.terminals.delete(handle as LocalTerminalHandle) },
|
|
363
|
+
spec.shellActivity === true,
|
|
364
|
+
)
|
|
365
|
+
this.terminals.add(handle)
|
|
366
|
+
if (linuxScope !== undefined) this.watchLinuxScopeStart(handle.done, linuxScope.generation)
|
|
367
|
+
const release = async (): Promise<void> => {
|
|
368
|
+
// terminate() can wait on this direct-exit promise.
|
|
369
|
+
directSettlement.resolve()
|
|
370
|
+
if (spec.shellActivity === true) return
|
|
371
|
+
await handle.terminate()
|
|
372
|
+
this.terminals.delete(handle)
|
|
373
|
+
}
|
|
374
|
+
void handle.done.then(release, release).catch(() => {})
|
|
375
|
+
return handle
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Read a Windows environment key using the platform's case-insensitive semantics. */
|
|
380
|
+
function environmentValue(env: NodeJS.ProcessEnv, name: 'PATH' | 'PATHEXT'): string | undefined {
|
|
381
|
+
const exact = env[name]
|
|
382
|
+
if (exact !== undefined || process.platform !== 'win32') return exact
|
|
383
|
+
const normalized = name.toUpperCase()
|
|
384
|
+
return Object.entries(env).find(([key]) => key.toUpperCase() === normalized)?.[1]
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export default LocalSubprocessRuntime
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/** Lazy libc execve and descriptor bindings used by the one-shot Linux bootstrap. */
|
|
2
|
+
|
|
3
|
+
import { getSystemErrorMessage, getSystemErrorName } from 'node:util'
|
|
4
|
+
import { SUBPROCESS_CONTROL_FD } from '@deepseek-ai/dsh-subprocess/control'
|
|
5
|
+
import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require'
|
|
6
|
+
|
|
7
|
+
const requireKoffi = createLazyRequire<typeof import('koffi')['default']>('koffi', import.meta.url)
|
|
8
|
+
|
|
9
|
+
/** Replace the current process image while preserving the supplied argv and environment. */
|
|
10
|
+
export type LinuxExecve = (
|
|
11
|
+
file: string,
|
|
12
|
+
argv: string[],
|
|
13
|
+
env: Record<string, string>,
|
|
14
|
+
control?: 'pipe',
|
|
15
|
+
pipeFds?: readonly number[],
|
|
16
|
+
) => never
|
|
17
|
+
|
|
18
|
+
type NativeExecve = (
|
|
19
|
+
file: string,
|
|
20
|
+
argv: Array<string | null>,
|
|
21
|
+
envp: Array<string | null>,
|
|
22
|
+
) => number
|
|
23
|
+
|
|
24
|
+
type NativeFcntl = (fd: number, command: number, argument: number) => number
|
|
25
|
+
|
|
26
|
+
const STANDARD_FILE_DESCRIPTORS = [0, 1, 2] as const
|
|
27
|
+
const F_GETFD = 1
|
|
28
|
+
const F_SETFD = 2
|
|
29
|
+
const FD_CLOEXEC = 1
|
|
30
|
+
const F_GETFL = 3
|
|
31
|
+
const F_SETFL = 4
|
|
32
|
+
const O_NONBLOCK = 0x800
|
|
33
|
+
|
|
34
|
+
let cachedExecve: LinuxExecve | undefined
|
|
35
|
+
|
|
36
|
+
function systemError(errno: number, syscall: string, path?: string): Error {
|
|
37
|
+
const uvError = -errno
|
|
38
|
+
const code = getSystemErrorName(uvError)
|
|
39
|
+
const detail = getSystemErrorMessage(uvError)
|
|
40
|
+
const subject = path === undefined ? syscall : `${syscall} '${path}'`
|
|
41
|
+
const error = Object.assign(new Error(`${code}: ${detail}, ${subject}`), {
|
|
42
|
+
code,
|
|
43
|
+
errno: uvError,
|
|
44
|
+
syscall,
|
|
45
|
+
})
|
|
46
|
+
return path === undefined ? error : Object.assign(error, { path })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Load libc's execve and fcntl symbols on first use and retain the native bindings.
|
|
51
|
+
* @returns a process-replacing execve operation that throws Node-style errors on failure.
|
|
52
|
+
*/
|
|
53
|
+
export function loadLinuxExecve(): LinuxExecve {
|
|
54
|
+
if (cachedExecve !== undefined) return cachedExecve
|
|
55
|
+
const koffi = requireKoffi()
|
|
56
|
+
const libc = koffi.load(null)
|
|
57
|
+
const nativeExecve = libc.func(
|
|
58
|
+
'int execve(const char *pathname, const char **argv, const char **envp)',
|
|
59
|
+
) as NativeExecve
|
|
60
|
+
const nativeFcntl = libc.func(
|
|
61
|
+
'int fcntl(int fd, int cmd, int arg)',
|
|
62
|
+
) as NativeFcntl
|
|
63
|
+
cachedExecve = (file, argv, env, control, pipeFds = []) => {
|
|
64
|
+
const descriptors = control === 'pipe'
|
|
65
|
+
? [...STANDARD_FILE_DESCRIPTORS, SUBPROCESS_CONTROL_FD]
|
|
66
|
+
: STANDARD_FILE_DESCRIPTORS
|
|
67
|
+
for (const fd of descriptors) {
|
|
68
|
+
const flags = nativeFcntl(fd, F_GETFD, 0)
|
|
69
|
+
if (flags === -1) throw systemError(koffi.errno(), 'fcntl')
|
|
70
|
+
if ((flags & FD_CLOEXEC) === 0) continue
|
|
71
|
+
if (nativeFcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) === -1) {
|
|
72
|
+
throw systemError(koffi.errno(), 'fcntl')
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
// F_SETFL changes the open file description in every process sharing it.
|
|
76
|
+
// Only pipes created for this child are safe to make blocking for native targets.
|
|
77
|
+
for (const fd of pipeFds) {
|
|
78
|
+
const flags = nativeFcntl(fd, F_GETFL, 0)
|
|
79
|
+
if (flags === -1) throw systemError(koffi.errno(), 'fcntl')
|
|
80
|
+
if ((flags & O_NONBLOCK) !== 0 && nativeFcntl(fd, F_SETFL, flags & ~O_NONBLOCK) === -1) {
|
|
81
|
+
throw systemError(koffi.errno(), 'fcntl')
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
nativeExecve(
|
|
85
|
+
file,
|
|
86
|
+
[...argv, null],
|
|
87
|
+
[...Object.entries(env).map(([key, value]) => `${key}=${value}`), null],
|
|
88
|
+
)
|
|
89
|
+
throw systemError(koffi.errno(), 'execve', file)
|
|
90
|
+
}
|
|
91
|
+
return cachedExecve
|
|
92
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Linux native containment decisions over injected host observations. */
|
|
2
|
+
|
|
3
|
+
import type { LiteralArgvOptions } from './linux-scope.ts'
|
|
4
|
+
|
|
5
|
+
/** Host observations behind each decision; the runtime supplies the real checks and tests script them. */
|
|
6
|
+
export interface LinuxScopeObservations {
|
|
7
|
+
/** Run the deep transient-scope probe: literal-argv options when a scope can start, otherwise undefined. */
|
|
8
|
+
probe(): LiteralArgvOptions | undefined
|
|
9
|
+
/** Identify the process listening on the user manager's private socket, or undefined when none listens. */
|
|
10
|
+
managerListener(): string | undefined
|
|
11
|
+
/** Confirm the user manager before a launch under a positive verdict. */
|
|
12
|
+
confirmManager(): boolean
|
|
13
|
+
/** Identify the systemd-run binary scope launches resolve, or undefined when none resolves. */
|
|
14
|
+
launcherIdentity(): string | undefined
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Event that made the selector probe: the first selection or one that invalidated the previous verdict. */
|
|
18
|
+
export type LinuxProbeTrigger = 'first' | 'scope-not-started' | 'new-listener' | 'launcher-changed'
|
|
19
|
+
|
|
20
|
+
/** One containment decision and the branch that produced it. */
|
|
21
|
+
export type LinuxScopeDecision =
|
|
22
|
+
| {
|
|
23
|
+
readonly kind: 'scope'
|
|
24
|
+
/** A probe found scope support, or a positive verdict confirmed the user manager. */
|
|
25
|
+
readonly reason: 'probe-available' | 'manager-confirmed'
|
|
26
|
+
readonly literalArgv: LiteralArgvOptions
|
|
27
|
+
/** Probe count when the verdict was made; pass it to scopeNotStarted for a failed launch. */
|
|
28
|
+
readonly generation: number
|
|
29
|
+
readonly probe: LinuxProbeTrigger | undefined
|
|
30
|
+
}
|
|
31
|
+
| {
|
|
32
|
+
readonly kind: 'fallback'
|
|
33
|
+
/**
|
|
34
|
+
* A probe found no scope support; a positive verdict failed to confirm the manager for this launch;
|
|
35
|
+
* or a negative verdict saw no listener or the listener present at the failed probe.
|
|
36
|
+
*/
|
|
37
|
+
readonly reason: 'probe-unavailable' | 'manager-unconfirmed' | 'no-listener' | 'same-listener'
|
|
38
|
+
readonly probe: LinuxProbeTrigger | undefined
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type LinuxScopeState =
|
|
42
|
+
| { readonly kind: 'unprobed'; readonly trigger: LinuxProbeTrigger }
|
|
43
|
+
| { readonly kind: 'available'; readonly literalArgv: LiteralArgvOptions; readonly launcher: string | undefined }
|
|
44
|
+
| { readonly kind: 'unavailable'; readonly listener: string | undefined }
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Provider-lifetime Linux scope selection. A probe runs on the first selection and again only after
|
|
48
|
+
* a scope launch never started its target, a different user-manager listener appears under a
|
|
49
|
+
* negative verdict, or the systemd-run binary changes under a positive one. A positive verdict
|
|
50
|
+
* confirms the user manager on every selection. Selection is synchronous, so a decision stays
|
|
51
|
+
* valid for the launch that follows it.
|
|
52
|
+
*/
|
|
53
|
+
export class LinuxScopeSelector {
|
|
54
|
+
private state: LinuxScopeState = { kind: 'unprobed', trigger: 'first' }
|
|
55
|
+
private generation = 0
|
|
56
|
+
|
|
57
|
+
/** @param observe - host checks consulted by each selection. */
|
|
58
|
+
constructor(private readonly observe: LinuxScopeObservations) {}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Choose containment for one eligible launch.
|
|
62
|
+
* @returns the decision and the branch that produced it.
|
|
63
|
+
*/
|
|
64
|
+
select(): LinuxScopeDecision {
|
|
65
|
+
const state = this.state
|
|
66
|
+
if (state.kind === 'unprobed') return this.probe(state.trigger)
|
|
67
|
+
if (state.kind === 'available') {
|
|
68
|
+
if (this.observe.launcherIdentity() !== state.launcher) return this.probe('launcher-changed')
|
|
69
|
+
return this.observe.confirmManager()
|
|
70
|
+
? { kind: 'scope', reason: 'manager-confirmed', literalArgv: state.literalArgv, generation: this.generation, probe: undefined }
|
|
71
|
+
: { kind: 'fallback', reason: 'manager-unconfirmed', probe: undefined }
|
|
72
|
+
}
|
|
73
|
+
const listener = this.observe.managerListener()
|
|
74
|
+
if (listener === undefined) return { kind: 'fallback', reason: 'no-listener', probe: undefined }
|
|
75
|
+
if (listener === state.listener) return { kind: 'fallback', reason: 'same-listener', probe: undefined }
|
|
76
|
+
return this.probe('new-listener')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Record that a scope launched under generation exited before its bootstrap started the target,
|
|
81
|
+
* so the next selection probes again. Launches from a superseded probe are ignored.
|
|
82
|
+
* @param generation - generation of the scope decision that launched it.
|
|
83
|
+
*/
|
|
84
|
+
scopeNotStarted(generation: number): void {
|
|
85
|
+
if (generation === this.generation) this.state = { kind: 'unprobed', trigger: 'scope-not-started' }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private probe(trigger: LinuxProbeTrigger): LinuxScopeDecision {
|
|
89
|
+
this.generation += 1
|
|
90
|
+
// Read before probing: a manager that starts during a failed probe then counts as a new listener.
|
|
91
|
+
const listener = this.observe.managerListener()
|
|
92
|
+
const launcher = this.observe.launcherIdentity()
|
|
93
|
+
const literalArgv = this.observe.probe()
|
|
94
|
+
if (literalArgv === undefined) {
|
|
95
|
+
this.state = { kind: 'unavailable', listener }
|
|
96
|
+
return { kind: 'fallback', reason: 'probe-unavailable', probe: trigger }
|
|
97
|
+
}
|
|
98
|
+
this.state = { kind: 'available', literalArgv, launcher }
|
|
99
|
+
return { kind: 'scope', reason: 'probe-available', literalArgv, generation: this.generation, probe: trigger }
|
|
100
|
+
}
|
|
101
|
+
}
|