Repository navigation
Expand file tree
/
Copy pathlauncher.ts
More file actions
261 lines (249 loc) · 10.2 KB
/
Copy pathlauncher.ts
File metadata and controls
261 lines (249 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { execFile } from 'child_process';
import { createHash, randomUUID } from 'crypto';
import { promisify } from 'util';
import { AgentConfig, SessionManifest, identifier } from './protocol';
import { atomicJson } from './journal';
import { hostNodeRuntime, NodeRuntime } from './nodeExecutable';
import { prepareSupervisor } from './supervisor';
import { ensureStorageDirectory, prepareStorage, storageError } from './storage';
import { installSessRuntime } from './backends/sessPreparation';
export { prepareStorage } from './storage';
const run = promisify(execFile);
export function defaultStorage(
platform = process.platform,
home = os.homedir(),
environment = process.env,
): string {
const xdg = environment.XDG_STATE_HOME;
// XDG paths must be absolute; an empty value is equivalent to being unset.
if (xdg && path.isAbsolute(xdg)) {
return path.join(xdg, 'vscode-r', 'interactive');
}
const legacy = path.join(home, '.local', 'state', 'vscode-r', 'interactive');
// Keep existing agents and their on-disk paths discoverable without moving live storage.
if (platform !== 'darwin' || fs.existsSync(legacy)) {
return legacy;
}
return path.join(home, 'Library', 'Application Support', 'vscode-r', 'interactive');
}
export function discoverSessions(root: string): SessionManifest[] {
let names: string[];
try {
names = fs.readdirSync(root);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return [];
}
throw storageError(root, error);
}
const sessions: SessionManifest[] = [];
for (const name of names) {
if (name === 'runtimes') {
continue;
}
try {
identifier(name);
const file = path.join(root, name, 'manifest.json');
const stat = fs.lstatSync(file);
if (stat.isSymbolicLink() || (process.getuid && stat.uid !== process.getuid())) {
continue;
}
const manifest = JSON.parse(fs.readFileSync(file, 'utf8')) as SessionManifest;
if (manifest.id !== name || manifest.host !== os.hostname()) {
continue;
}
sessions.push(manifest);
} catch {
/* Ignore partial, foreign, and unrecognized registry entries. */
}
}
return sessions.sort((a, b) => b.created - a.created);
}
/** Cheap rejection of stale registry entries; a socket still needs an authenticated probe. */
export function hasSessionEndpoint(manifest: SessionManifest): boolean {
if (
!Number.isSafeInteger(manifest.agentPid) ||
manifest.agentPid <= 0 ||
typeof manifest.endpoint !== 'string' ||
!path.isAbsolute(manifest.endpoint)
) {
return false;
}
try {
process.kill(manifest.agentPid, 0);
return fs.statSync(manifest.endpoint).isSocket();
} catch {
return false;
}
}
/** Shell quoting is used only for tmux/system service launch commands, never for R code. */
export function shellQuote(value: string): string {
return `'${value.replace(/'/g, `'"'"'`)}'`;
}
/** Debugger auto-attach must not make the persistent agent part of the editor's debug session. */
export function agentEnvironment(environment = process.env): NodeJS.ProcessEnv {
const result = { ...environment };
delete result.ELECTRON_RUN_AS_NODE;
if (result.VSCODE_INSPECTOR_OPTIONS) {
delete result.NODE_OPTIONS;
delete result.VSCODE_INSPECTOR_OPTIONS;
}
return result;
}
/** Only the Electron launcher and agent need this flag, not their R children. */
export function nodeEnvironment(
runtime: NodeRuntime,
environment = process.env,
): NodeJS.ProcessEnv {
const result = agentEnvironment(environment);
if (runtime.electron) {
result.ELECTRON_RUN_AS_NODE = '1';
}
return result;
}
/** Agent bundles are cached independently of any R backend or package library. */
export function installAgentBundle(extensionPath: string, root: string): string {
prepareStorage(root);
const bytes = fs.readFileSync(path.join(extensionPath, 'dist', 'interactive-agent.js'));
const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 20);
const agent = path.join(root, 'runtimes', `agent-${hash}.cjs`);
if (!fs.existsSync(agent)) {
const temporary = `${agent}.${randomUUID()}.tmp`;
try {
fs.writeFileSync(temporary, bytes, { mode: 0o600 });
fs.renameSync(temporary, agent);
} finally {
fs.rmSync(temporary, { force: true });
}
}
return agent;
}
/** Convenience for existing callers preparing the shipped sess backend. */
export async function installRuntime(
extensionPath: string,
root: string,
rPath: string,
log: (text: string) => void,
): Promise<{ library: string; resources: string; agent: string }> {
const runtime = await installSessRuntime(extensionPath, root, rPath, log);
return { ...runtime, agent: installAgentBundle(extensionPath, root) };
}
/** Validate before building a runtime or stopping a session for restart. */
export async function prepareNodeRuntime(
directory: string,
runtime = hostNodeRuntime(),
): Promise<NodeRuntime> {
const node = runtime.executable;
const help =
"Set r.interactive.nodePath to a Node.js 18+ executable on the R host, or clear it to use VS Code's runtime. Reload VS Code to refresh the automatic runtime; repair or update VS Code (VS Code Server on a remote host) if needed.";
let version: string;
try {
version = (
await run(node, ['-p', 'process.versions.node'], {
env: nodeEnvironment(runtime),
cwd: directory,
timeout: 5000,
})
).stdout.trim();
} catch (error) {
throw new Error(`Cannot run the Node.js runtime “${node}”. ${help}`, { cause: error });
}
const major = /^(\d+)\.\d+\.\d+(?:[-+].*)?$/.exec(version)?.[1];
if (!major || Number(major) < 18) {
throw new Error(
`The session agent requires Node.js 18 or newer; “${node}” reported “${version}”. ${help}`,
);
}
return runtime;
}
export async function launchAgent(
config: AgentConfig,
agent: string,
runtime = hostNodeRuntime(),
log: (text: string) => void = () => undefined,
): Promise<SessionManifest> {
const supervisor = prepareSupervisor(config.supervision, config.directory);
runtime = await prepareNodeRuntime(config.directory, runtime);
const node = runtime.executable;
ensureStorageDirectory(config.storage, path.dirname(config.storage));
const file = path.join(config.storage, 'config.json');
const env = nodeEnvironment(runtime);
config.supervision = supervisor.kind;
atomicJson(file, config);
if (supervisor.kind !== 'detached') {
const args =
supervisor.kind === 'tmux'
? [
'new-session',
'-d',
'-s',
`vscode-r-${config.id.slice(0, 8)}-${config.generation.slice(0, 8)}`,
`${runtime.electron ? 'ELECTRON_RUN_AS_NODE=1 ' : ''}exec ${[node, agent, file].map(shellQuote).join(' ')} >>${shellQuote(path.join(config.storage, 'agent.log'))} 2>&1`,
]
: [
'--user',
'--collect',
'--unit',
`vscode-r-${config.id}-${config.generation}`,
...(runtime.electron ? ['--setenv=ELECTRON_RUN_AS_NODE=1'] : []),
'--',
node,
agent,
file,
];
try {
await run(supervisor.executable, args, { env, cwd: config.directory, timeout: 10000 });
} catch (error) {
// A failed command may already have started an agent. Falling back now
// could create two R processes using the same session registry.
throw new Error(
`Could not start the ${supervisor.kind} session supervisor. Check ${supervisor.kind === 'systemd' ? 'the systemd user service' : 'tmux'} on the R host, ` +
`or set r.interactive.supervision to "detached". ${String(error)}`,
{ cause: error },
);
}
} else {
if (supervisor.notice) {
log(supervisor.notice);
fs.appendFileSync(path.join(config.storage, 'agent.log'), `${supervisor.notice}\n`, {
mode: 0o600,
});
}
// setsid/unref alone leaves the agent in the extension host's process tree.
// Wait for a short-lived launcher to exit so tree-based editor/debugger cleanup
// cannot reach the agent. The agent owns its log and has no inherited IPC or stdio.
const bootstrap = `
const fs = require('fs');
const log = fs.openSync(${JSON.stringify(path.join(config.storage, 'agent.log'))}, 'a', 0o600);
const child = require('child_process').spawn(process.execPath, process.argv.slice(1),
{ detached: true, stdio: ['ignore', log, log] });
child.once('error', error => { console.error(error); process.exitCode = 1; });
child.unref();
fs.closeSync(log);
`;
await run(node, ['-e', bootstrap, agent, file], { env });
}
const deadline = Date.now() + 30000;
while (Date.now() < deadline) {
try {
const manifest = JSON.parse(
fs.readFileSync(path.join(config.storage, 'manifest.json'), 'utf8'),
) as SessionManifest;
if (manifest.generation === config.generation) {
return manifest;
}
} catch {
/* Atomic manifest is published after the endpoints are ready. */
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
throw new Error(
`Session agent did not become ready. See ${path.join(config.storage, 'agent.log')}`,
);
}
export function newIdentity(): { id: string; generation: string } {
return { id: randomUUID(), generation: randomUUID() };
}