@johannes.latzel/llm-chat-shell 0.1.0
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/LICENSE +7 -0
- package/README.md +43 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/bash-executor.d.ts +125 -0
- package/dist/lib/bash-executor.d.ts.map +1 -0
- package/dist/lib/bash-executor.js +314 -0
- package/dist/lib/bash-executor.js.map +1 -0
- package/dist/lib/config.d.ts +79 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +216 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/env.d.ts +34 -0
- package/dist/lib/env.d.ts.map +1 -0
- package/dist/lib/env.js +77 -0
- package/dist/lib/env.js.map +1 -0
- package/dist/lib/job-registry.d.ts +55 -0
- package/dist/lib/job-registry.d.ts.map +1 -0
- package/dist/lib/job-registry.js +116 -0
- package/dist/lib/job-registry.js.map +1 -0
- package/dist/lib/permission.d.ts +101 -0
- package/dist/lib/permission.d.ts.map +1 -0
- package/dist/lib/permission.js +361 -0
- package/dist/lib/permission.js.map +1 -0
- package/dist/lib/session-manager.d.ts +148 -0
- package/dist/lib/session-manager.d.ts.map +1 -0
- package/dist/lib/session-manager.js +264 -0
- package/dist/lib/session-manager.js.map +1 -0
- package/dist/lib/session-queue.d.ts +58 -0
- package/dist/lib/session-queue.d.ts.map +1 -0
- package/dist/lib/session-queue.js +123 -0
- package/dist/lib/session-queue.js.map +1 -0
- package/dist/lib/session-registry.d.ts +140 -0
- package/dist/lib/session-registry.d.ts.map +1 -0
- package/dist/lib/session-registry.js +267 -0
- package/dist/lib/session-registry.js.map +1 -0
- package/dist/lib/types.d.ts +155 -0
- package/dist/lib/types.d.ts.map +1 -0
- package/dist/lib/types.js +37 -0
- package/dist/lib/types.js.map +1 -0
- package/dist/tools/shell-command-tool.d.ts +30 -0
- package/dist/tools/shell-command-tool.d.ts.map +1 -0
- package/dist/tools/shell-command-tool.js +138 -0
- package/dist/tools/shell-command-tool.js.map +1 -0
- package/dist/tools/shell-create-tool.d.ts +12 -0
- package/dist/tools/shell-create-tool.d.ts.map +1 -0
- package/dist/tools/shell-create-tool.js +24 -0
- package/dist/tools/shell-create-tool.js.map +1 -0
- package/dist/tools/shell-job-status-tool.d.ts +13 -0
- package/dist/tools/shell-job-status-tool.d.ts.map +1 -0
- package/dist/tools/shell-job-status-tool.js +59 -0
- package/dist/tools/shell-job-status-tool.js.map +1 -0
- package/dist/tools/shell-jobs-tool.d.ts +12 -0
- package/dist/tools/shell-jobs-tool.d.ts.map +1 -0
- package/dist/tools/shell-jobs-tool.js +28 -0
- package/dist/tools/shell-jobs-tool.js.map +1 -0
- package/dist/tools/shell-package.d.ts +54 -0
- package/dist/tools/shell-package.d.ts.map +1 -0
- package/dist/tools/shell-package.js +77 -0
- package/dist/tools/shell-package.js.map +1 -0
- package/dist/tools/shell-permissions-tool.d.ts +15 -0
- package/dist/tools/shell-permissions-tool.d.ts.map +1 -0
- package/dist/tools/shell-permissions-tool.js +38 -0
- package/dist/tools/shell-permissions-tool.js.map +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { Mutex } from 'async-mutex';
|
|
2
|
+
import { ShellJobStatus } from './types.js';
|
|
3
|
+
import { JobRegistry } from './job-registry.js';
|
|
4
|
+
import { SessionRegistry } from './session-registry.js';
|
|
5
|
+
import { SessionQueue } from './session-queue.js';
|
|
6
|
+
/**
|
|
7
|
+
* Manages shell session lifecycle as a registry of {@link ShellExecutor} instances.
|
|
8
|
+
* Each session is its own executor. Tracks active sessions and enforces limits.
|
|
9
|
+
*
|
|
10
|
+
* The class composes a {@link JobRegistry} (bounded store of every job, live
|
|
11
|
+
* or finished), a {@link SessionRegistry} (live sessions plus tombstones), and
|
|
12
|
+
* a {@link SessionQueue} (the per-session FIFO worker loop), and coordinates
|
|
13
|
+
* them with the idle-expiry sweeper and the teardown of dead or closed
|
|
14
|
+
* sessions.
|
|
15
|
+
*
|
|
16
|
+
* Because a shell executes a single command at a time, every command submitted to
|
|
17
|
+
* a session (foreground or background) is queued in FIFO order and run by a single
|
|
18
|
+
* per-session worker loop. Foreground calls block until their job completes;
|
|
19
|
+
* background submissions return immediately with a {@link ShellJob} to poll.
|
|
20
|
+
* Finished jobs stay queryable by ID in a bounded registry, even after their
|
|
21
|
+
* session dies.
|
|
22
|
+
*
|
|
23
|
+
* Sessions idle for longer than `config.sessionTimeout` are expired by a background
|
|
24
|
+
* sweeper, and sessions whose underlying process died are pruned, so `maxSessions`
|
|
25
|
+
* slots are never permanently lost. Sessions with queued or running jobs are never
|
|
26
|
+
* expired. Dead sessions are recorded as tombstones so stale session IDs keep
|
|
27
|
+
* producing descriptive errors instead of a bare "not found".
|
|
28
|
+
*
|
|
29
|
+
* The manager owns the single mutex that gates the operations which span an
|
|
30
|
+
* `await`: session creation (its factory call is awaited while holding the
|
|
31
|
+
* lock, so concurrent creates cannot both pass the `maxSessions` check),
|
|
32
|
+
* teardown, and expiry are serialized against each other and against
|
|
33
|
+
* submissions. The components themselves are lock-free — their operations are
|
|
34
|
+
* synchronous and therefore atomic under the single-threaded event loop, so
|
|
35
|
+
* they interleave safely with the manager's mutex-protected blocks. The
|
|
36
|
+
* worker loop runs outside the mutex by design: its per-job bookkeeping is a
|
|
37
|
+
* single synchronous block, and the session's `processing` flag guarantees at
|
|
38
|
+
* most one worker. Executor close is single-owner: whoever removes a session
|
|
39
|
+
* from the registry closes its executor (a teardown caller, or the worker on
|
|
40
|
+
* a naturally dead session).
|
|
41
|
+
*/
|
|
42
|
+
export class ShellSessionManager {
|
|
43
|
+
config;
|
|
44
|
+
workspace;
|
|
45
|
+
sessions;
|
|
46
|
+
jobs = new JobRegistry();
|
|
47
|
+
queue;
|
|
48
|
+
mutex = new Mutex();
|
|
49
|
+
sweeper = null;
|
|
50
|
+
constructor(factory, config, workspace) {
|
|
51
|
+
this.config = config;
|
|
52
|
+
this.workspace = workspace;
|
|
53
|
+
this.sessions = new SessionRegistry(factory, config, workspace, this.jobs);
|
|
54
|
+
this.queue = new SessionQueue(this.sessions, this.jobs);
|
|
55
|
+
this.startSweeper();
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Create a new shell session.
|
|
59
|
+
* @param cwd - Optional working directory for this session. Must resolve to a subpath
|
|
60
|
+
* of the configured workspace access dirs. Symlinks are resolved when the
|
|
61
|
+
* workspace has `resolveSymlinks` enabled.
|
|
62
|
+
* @returns The session ID.
|
|
63
|
+
* @throws Error if max sessions reached or cwd is outside the accessible directories.
|
|
64
|
+
*/
|
|
65
|
+
async createSession(cwd) {
|
|
66
|
+
return this.mutex.runExclusive(() => this.sessions.create(cwd));
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Return the workspace root a session is currently bound to.
|
|
70
|
+
* @throws Error if session does not exist.
|
|
71
|
+
*/
|
|
72
|
+
async getSessionWorkspaceRoot(sessionId) {
|
|
73
|
+
return this.mutex.runExclusive(() => this.sessions.getWorkspaceRoot(sessionId));
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Return the working directory a session's jobs run in.
|
|
77
|
+
* @throws Error if session does not exist.
|
|
78
|
+
*/
|
|
79
|
+
async getSessionCwd(sessionId) {
|
|
80
|
+
return this.mutex.runExclusive(() => this.sessions.getCwd(sessionId));
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Permanently rebind a session to a different workspace root and working
|
|
84
|
+
* directory. Subsequent permission checks use the new root and jobs run in
|
|
85
|
+
* the new cwd.
|
|
86
|
+
* @throws Error if session does not exist.
|
|
87
|
+
*/
|
|
88
|
+
async rebindSession(sessionId, workspaceRoot, cwd) {
|
|
89
|
+
await this.mutex.runExclusive(() => this.sessions.rebind(sessionId, workspaceRoot, cwd));
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Run a command in the foreground: enqueue it and block until the shell gets
|
|
93
|
+
* to it and it completes (or fails). Commands already queued on the same
|
|
94
|
+
* session (including background jobs) run first.
|
|
95
|
+
*
|
|
96
|
+
* @param options - `cwd` is the working directory the command runs in
|
|
97
|
+
* (defaults to the session's cwd); `timeout` overrides the
|
|
98
|
+
* idle timeout (ms, capped at `config.maxTimeout`); omitted
|
|
99
|
+
* uses `ctrlCTimeout`.
|
|
100
|
+
* @throws Error if the session does not exist or the job failed before running.
|
|
101
|
+
*/
|
|
102
|
+
async executeCommand(sessionId, command, options) {
|
|
103
|
+
const cwd = options?.cwd ?? (await this.getSessionCwd(sessionId));
|
|
104
|
+
const record = await this.mutex.runExclusive(() => this.queue.submit(sessionId, command, this.config.resolveIdleTimeout(false, options?.timeout), cwd));
|
|
105
|
+
await record.done;
|
|
106
|
+
if (record.status === ShellJobStatus.Failed) {
|
|
107
|
+
throw new Error(record.error);
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
stdout: record.stdout,
|
|
111
|
+
stderr: record.stderr,
|
|
112
|
+
exitCode: record.exitCode,
|
|
113
|
+
timedOut: record.timedOut,
|
|
114
|
+
sessionAlive: record.sessionAlive,
|
|
115
|
+
...(record.timedOut === true ? { idleTimeoutMs: record.idleTimeoutMs } : {})
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Submit a command to run in the background and return immediately with a
|
|
120
|
+
* {@link ShellJob}. The job runs when the shell is free (FIFO queue per
|
|
121
|
+
* session); poll {@link getJobStatus} for progress and results.
|
|
122
|
+
*
|
|
123
|
+
* @param options - `cwd` is the working directory the job runs in
|
|
124
|
+
* (defaults to the session's cwd); `timeout` overrides the
|
|
125
|
+
* idle timeout (ms, capped at `config.maxTimeout`); omitted
|
|
126
|
+
* uses `backgroundTimeout`.
|
|
127
|
+
* @throws Error if the session does not exist.
|
|
128
|
+
*/
|
|
129
|
+
async submitCommand(sessionId, command, options) {
|
|
130
|
+
const cwd = options?.cwd ?? (await this.getSessionCwd(sessionId));
|
|
131
|
+
return this.mutex.runExclusive(() => this.queue.submit(sessionId, command, this.config.resolveIdleTimeout(true, options?.timeout), cwd));
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Return the current status and (once finished) results of a job.
|
|
135
|
+
* @throws Error if the job was evicted from the registry or never existed.
|
|
136
|
+
*/
|
|
137
|
+
async getJobStatus(jobId) {
|
|
138
|
+
return this.mutex.runExclusive(() => {
|
|
139
|
+
const job = this.jobs.require(jobId);
|
|
140
|
+
const snapshot = { ...job };
|
|
141
|
+
if (job.status === ShellJobStatus.Queued) {
|
|
142
|
+
const position = this.sessions.queuePosition(job.sessionId, job.id);
|
|
143
|
+
if (position !== undefined) {
|
|
144
|
+
snapshot.position = position;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return snapshot;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* List the retained jobs submitted to a session, oldest first. Works even
|
|
152
|
+
* after the session has died, as long as its jobs are still in the registry.
|
|
153
|
+
* @throws Error if the session is unknown and has no retained jobs.
|
|
154
|
+
*/
|
|
155
|
+
async listJobs(sessionId) {
|
|
156
|
+
return this.mutex.runExclusive(() => {
|
|
157
|
+
const jobs = this.jobs.listForSession(sessionId);
|
|
158
|
+
if (jobs.length === 0 && !this.sessions.has(sessionId)) {
|
|
159
|
+
throw new Error(this.sessions.notFoundMessage(sessionId));
|
|
160
|
+
}
|
|
161
|
+
return jobs;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Snapshot the active shell sessions with their current load. Pending
|
|
166
|
+
* (queued) jobs are counted; the running job (if any) is identified.
|
|
167
|
+
*/
|
|
168
|
+
async listSessions() {
|
|
169
|
+
return this.mutex.runExclusive(() => {
|
|
170
|
+
const runningBySession = new Map();
|
|
171
|
+
for (const job of this.jobs.listAll()) {
|
|
172
|
+
if (job.status === ShellJobStatus.Running) {
|
|
173
|
+
runningBySession.set(job.sessionId, job.id);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return this.sessions.entries().map(([id, entry]) => {
|
|
177
|
+
const runningJobId = runningBySession.get(id);
|
|
178
|
+
return {
|
|
179
|
+
id,
|
|
180
|
+
workspaceRoot: entry.workspaceRoot,
|
|
181
|
+
queued: entry.queue.length,
|
|
182
|
+
...(runningJobId !== undefined ? { runningJobId } : {})
|
|
183
|
+
};
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* List every retained job across all sessions, oldest first. Jobs that
|
|
189
|
+
* completed or failed remain in the registry until evicted.
|
|
190
|
+
*/
|
|
191
|
+
async listAllJobs() {
|
|
192
|
+
return this.mutex.runExclusive(() => this.jobs.listAll());
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Close a shell session and clean up its executor. Queued jobs fail with a
|
|
196
|
+
* descriptive reason; the session is tombstoned so later references produce
|
|
197
|
+
* a descriptive error.
|
|
198
|
+
*/
|
|
199
|
+
async closeSession(sessionId) {
|
|
200
|
+
const executor = await this.mutex.runExclusive(() => this.sessions.teardown(sessionId, 'closed', 'the session was closed before the job could run'));
|
|
201
|
+
if (executor !== undefined) {
|
|
202
|
+
await executor.close();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Close all active sessions and stop the idle-expiry sweeper.
|
|
207
|
+
*/
|
|
208
|
+
async close() {
|
|
209
|
+
this.stopSweeper();
|
|
210
|
+
const executors = await this.mutex.runExclusive(() => {
|
|
211
|
+
const execs = this.sessions.values().map((entry) => entry.executor);
|
|
212
|
+
for (const entry of this.sessions.values()) {
|
|
213
|
+
this.jobs.failAll(entry.queue, 'the session manager was disposed before the job could run');
|
|
214
|
+
}
|
|
215
|
+
this.sessions.clear();
|
|
216
|
+
return execs;
|
|
217
|
+
});
|
|
218
|
+
await Promise.all(executors.map((exec) => exec.close()));
|
|
219
|
+
}
|
|
220
|
+
/** Alias for {@link close}: closes all sessions and stops background timers. */
|
|
221
|
+
async dispose() {
|
|
222
|
+
await this.close();
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Expire sessions that have been idle (no queued or running jobs) for at least
|
|
226
|
+
* `config.sessionTimeout`. Sessions with pending jobs are never expired.
|
|
227
|
+
*/
|
|
228
|
+
async expireIdleSessions() {
|
|
229
|
+
const sessionTimeout = this.config.sessionTimeout;
|
|
230
|
+
if (!Number.isFinite(sessionTimeout) || sessionTimeout <= 0) {
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
const now = Date.now();
|
|
234
|
+
const expiredExecutors = await this.mutex.runExclusive(() => {
|
|
235
|
+
const executors = [];
|
|
236
|
+
for (const [id, entry] of this.sessions.expired(now, sessionTimeout)) {
|
|
237
|
+
executors.push(entry.executor);
|
|
238
|
+
this.sessions.teardown(id, 'expired', 'the session expired before the job could run');
|
|
239
|
+
}
|
|
240
|
+
return executors;
|
|
241
|
+
});
|
|
242
|
+
await Promise.all(expiredExecutors.map((exec) => exec.close()));
|
|
243
|
+
}
|
|
244
|
+
/** Start the idle-expiry sweeper, ticking every sessionTimeout/2 (min 1s). */
|
|
245
|
+
startSweeper() {
|
|
246
|
+
this.stopSweeper();
|
|
247
|
+
const sessionTimeout = this.config.sessionTimeout;
|
|
248
|
+
if (!Number.isFinite(sessionTimeout) || sessionTimeout <= 0) {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
const interval = Math.max(1000, Math.floor(sessionTimeout / 2));
|
|
252
|
+
this.sweeper = setInterval(() => {
|
|
253
|
+
void this.expireIdleSessions().catch(() => { });
|
|
254
|
+
}, interval);
|
|
255
|
+
this.sweeper.unref();
|
|
256
|
+
}
|
|
257
|
+
stopSweeper() {
|
|
258
|
+
if (this.sweeper !== null) {
|
|
259
|
+
clearInterval(this.sweeper);
|
|
260
|
+
this.sweeper = null;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
//# sourceMapping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,cAAc,GAAG,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC;QAClD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,cAAc,IAAI,CAAC,EAAE,CAAC;YAC1D,OAAO;QACX,CAAC;QACD,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,cAAc,GAAG,CAAC,CAAC,CAAC,CAAC;QAChE,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,GAAG,EAAE;YAC5B,KAAK,IAAI,CAAC,kBAAkB,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QACnD,CAAC,EAAE,QAAQ,CAAC,CAAC;QACb,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAEO,WAAW;QACf,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;YACxB,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAC5B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACxB,CAAC;IACL,CAAC;CACJ"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { JobRecord, JobRegistry } from './job-registry.js';
|
|
2
|
+
import type { SessionRegistry } from './session-registry.js';
|
|
3
|
+
/**
|
|
4
|
+
* Runs the per-session FIFO job queue of a {@link ShellSessionManager}.
|
|
5
|
+
*
|
|
6
|
+
* Because a shell executes a single command at a time, every command submitted
|
|
7
|
+
* to a session (foreground or background) is queued in FIFO order and executed
|
|
8
|
+
* by a single per-session worker loop. Submitting starts the loop only when
|
|
9
|
+
* the session is idle; while the loop drains, further submissions are picked
|
|
10
|
+
* up by the running loop rather than starting a second one.
|
|
11
|
+
*
|
|
12
|
+
* Finished and failed jobs are recorded in the {@link JobRegistry} and their
|
|
13
|
+
* completion promise is resolved, so foreground callers can await them.
|
|
14
|
+
*
|
|
15
|
+
* The queue holds no lock of its own: every transition it performs on the
|
|
16
|
+
* session and job registries is synchronous and therefore atomic under the
|
|
17
|
+
* single-threaded event loop. Submissions are serialized by the owning
|
|
18
|
+
* manager, which wraps its calls into this queue in its mutex, so at most one
|
|
19
|
+
* worker loop runs per session. The worker itself runs lock-free: its
|
|
20
|
+
* per-job bookkeeping (dequeue, status transitions, and the death path) is a
|
|
21
|
+
* single synchronous block and must never gain an `await` — an `await` there
|
|
22
|
+
* would let a submission interleave with a mid-transition state. Executor
|
|
23
|
+
* close is single-owner: the worker closes the executor only when it removed
|
|
24
|
+
* the session itself; a manager teardown that removed the session first owns
|
|
25
|
+
* the close. This class holds no session state of its own: sessions and jobs
|
|
26
|
+
* live in the registries passed to the constructor.
|
|
27
|
+
*/
|
|
28
|
+
export declare class SessionQueue {
|
|
29
|
+
private readonly sessions;
|
|
30
|
+
private readonly jobs;
|
|
31
|
+
constructor(sessions: SessionRegistry, jobs: JobRegistry);
|
|
32
|
+
/**
|
|
33
|
+
* Enqueue a job and, when the session is idle, start the worker loop.
|
|
34
|
+
* @param cwd - Working directory the job runs in; the executor re-anchors here before running.
|
|
35
|
+
* @returns The queued job record. Foreground callers await its `done`
|
|
36
|
+
* promise; background callers poll its status via the registries.
|
|
37
|
+
* @throws Error if the session does not exist.
|
|
38
|
+
*/
|
|
39
|
+
submit(sessionId: string, command: string, idleTimeoutMs: number, cwd: string): JobRecord;
|
|
40
|
+
/**
|
|
41
|
+
* Per-session worker loop: runs one queued job at a time until the queue
|
|
42
|
+
* drains. Fetching the next job and clearing the `processing` flag happen
|
|
43
|
+
* in one synchronous step, so a job enqueued while the queue is draining
|
|
44
|
+
* always either gets picked up by this worker or triggers a fresh one —
|
|
45
|
+
* never neither.
|
|
46
|
+
*/
|
|
47
|
+
private run;
|
|
48
|
+
/**
|
|
49
|
+
* Execute a single job, updating its status and results. When the command
|
|
50
|
+
* killed the shell (timeout) or the process exited, the session is removed,
|
|
51
|
+
* tombstoned, and every still-queued job on it is failed — but only when
|
|
52
|
+
* this worker still owns the session. If a manager teardown (close,
|
|
53
|
+
* closeSession, expiry) removed the session first, that owner has already
|
|
54
|
+
* tombstoned it and closed the executor; the worker leaves both alone.
|
|
55
|
+
*/
|
|
56
|
+
private execute;
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=session-queue.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-queue.d.ts","sourceRoot":"","sources":["../../src/lib/session-queue.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,KAAK,EAAgB,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE3E;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,qBAAa,YAAY;IAEjB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,IAAI;gBADJ,QAAQ,EAAE,eAAe,EACzB,IAAI,EAAE,WAAW;IAGtC;;;;;;OAMG;IACH,MAAM,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,SAAS;IAgBzF;;;;;;OAMG;YACW,GAAG;IAUjB;;;;;;;OAOG;YACW,OAAO;CAyCxB"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { ShellJobStatus } from './types.js';
|
|
3
|
+
import { createJobRecord } from './job-registry.js';
|
|
4
|
+
/**
|
|
5
|
+
* Runs the per-session FIFO job queue of a {@link ShellSessionManager}.
|
|
6
|
+
*
|
|
7
|
+
* Because a shell executes a single command at a time, every command submitted
|
|
8
|
+
* to a session (foreground or background) is queued in FIFO order and executed
|
|
9
|
+
* by a single per-session worker loop. Submitting starts the loop only when
|
|
10
|
+
* the session is idle; while the loop drains, further submissions are picked
|
|
11
|
+
* up by the running loop rather than starting a second one.
|
|
12
|
+
*
|
|
13
|
+
* Finished and failed jobs are recorded in the {@link JobRegistry} and their
|
|
14
|
+
* completion promise is resolved, so foreground callers can await them.
|
|
15
|
+
*
|
|
16
|
+
* The queue holds no lock of its own: every transition it performs on the
|
|
17
|
+
* session and job registries is synchronous and therefore atomic under the
|
|
18
|
+
* single-threaded event loop. Submissions are serialized by the owning
|
|
19
|
+
* manager, which wraps its calls into this queue in its mutex, so at most one
|
|
20
|
+
* worker loop runs per session. The worker itself runs lock-free: its
|
|
21
|
+
* per-job bookkeeping (dequeue, status transitions, and the death path) is a
|
|
22
|
+
* single synchronous block and must never gain an `await` — an `await` there
|
|
23
|
+
* would let a submission interleave with a mid-transition state. Executor
|
|
24
|
+
* close is single-owner: the worker closes the executor only when it removed
|
|
25
|
+
* the session itself; a manager teardown that removed the session first owns
|
|
26
|
+
* the close. This class holds no session state of its own: sessions and jobs
|
|
27
|
+
* live in the registries passed to the constructor.
|
|
28
|
+
*/
|
|
29
|
+
export class SessionQueue {
|
|
30
|
+
sessions;
|
|
31
|
+
jobs;
|
|
32
|
+
constructor(sessions, jobs) {
|
|
33
|
+
this.sessions = sessions;
|
|
34
|
+
this.jobs = jobs;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Enqueue a job and, when the session is idle, start the worker loop.
|
|
38
|
+
* @param cwd - Working directory the job runs in; the executor re-anchors here before running.
|
|
39
|
+
* @returns The queued job record. Foreground callers await its `done`
|
|
40
|
+
* promise; background callers poll its status via the registries.
|
|
41
|
+
* @throws Error if the session does not exist.
|
|
42
|
+
*/
|
|
43
|
+
submit(sessionId, command, idleTimeoutMs, cwd) {
|
|
44
|
+
const record = createJobRecord({
|
|
45
|
+
id: randomUUID(),
|
|
46
|
+
sessionId,
|
|
47
|
+
cwd,
|
|
48
|
+
command,
|
|
49
|
+
idleTimeoutMs
|
|
50
|
+
});
|
|
51
|
+
const shouldStart = this.sessions.enqueue(sessionId, record);
|
|
52
|
+
this.jobs.set(record);
|
|
53
|
+
if (shouldStart) {
|
|
54
|
+
void this.run(sessionId);
|
|
55
|
+
}
|
|
56
|
+
return record;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Per-session worker loop: runs one queued job at a time until the queue
|
|
60
|
+
* drains. Fetching the next job and clearing the `processing` flag happen
|
|
61
|
+
* in one synchronous step, so a job enqueued while the queue is draining
|
|
62
|
+
* always either gets picked up by this worker or triggers a fresh one —
|
|
63
|
+
* never neither.
|
|
64
|
+
*/
|
|
65
|
+
async run(sessionId) {
|
|
66
|
+
while (true) {
|
|
67
|
+
const next = this.sessions.dequeue(sessionId);
|
|
68
|
+
if (next === undefined) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
await this.execute(next.entry, next.job);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Execute a single job, updating its status and results. When the command
|
|
76
|
+
* killed the shell (timeout) or the process exited, the session is removed,
|
|
77
|
+
* tombstoned, and every still-queued job on it is failed — but only when
|
|
78
|
+
* this worker still owns the session. If a manager teardown (close,
|
|
79
|
+
* closeSession, expiry) removed the session first, that owner has already
|
|
80
|
+
* tombstoned it and closed the executor; the worker leaves both alone.
|
|
81
|
+
*/
|
|
82
|
+
async execute(entry, job) {
|
|
83
|
+
try {
|
|
84
|
+
job.status = ShellJobStatus.Running;
|
|
85
|
+
job.startedAt = Date.now();
|
|
86
|
+
entry.lastUsedMs = Date.now();
|
|
87
|
+
let result;
|
|
88
|
+
try {
|
|
89
|
+
result = await entry.executor.execute(job.command, {
|
|
90
|
+
cwd: job.cwd,
|
|
91
|
+
idleTimeoutMs: job.idleTimeoutMs
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
this.jobs.fail(job, error.message);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const died = result.timedOut || !result.sessionAlive || !entry.executor.isAlive();
|
|
99
|
+
if (died) {
|
|
100
|
+
const reason = result.timedOut
|
|
101
|
+
? 'timeout'
|
|
102
|
+
: 'process-exited';
|
|
103
|
+
const current = this.sessions.get(job.sessionId);
|
|
104
|
+
if (current !== undefined && current === entry) {
|
|
105
|
+
this.sessions.remove(job.sessionId);
|
|
106
|
+
const pending = this.sessions.takeQueue(current);
|
|
107
|
+
this.jobs.failAll(pending, 'the session died before the job could run');
|
|
108
|
+
this.sessions.recordDeath(job.sessionId, reason);
|
|
109
|
+
// The executor may already be dead; never let a close failure surface here.
|
|
110
|
+
void entry.executor.close().catch(() => { });
|
|
111
|
+
}
|
|
112
|
+
this.jobs.finish(job, result);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
this.jobs.finish(job, result);
|
|
116
|
+
this.sessions.touch(job.sessionId);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
this.jobs.fail(job, `unexpected failure: ${error.message}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
//# sourceMappingURL=session-queue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-queue.js","sourceRoot":"","sources":["../../src/lib/session-queue.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAE5C,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIpD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,OAAO,YAAY;IAEA;IACA;IAFrB,YACqB,QAAyB,EACzB,IAAiB;QADjB,aAAQ,GAAR,QAAQ,CAAiB;QACzB,SAAI,GAAJ,IAAI,CAAa;IACnC,CAAC;IAEJ;;;;;;OAMG;IACH,MAAM,CAAC,SAAiB,EAAE,OAAe,EAAE,aAAqB,EAAE,GAAW;QACzE,MAAM,MAAM,GAAG,eAAe,CAAC;YAC3B,EAAE,EAAE,UAAU,EAAE;YAChB,SAAS;YACT,GA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ACb,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,uBAAwB,KAAe,CAAC,OAAO,EAAE,CAAC,CAAC;QAC3E,CAAC;IACL,CAAC;CACJ"}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type { Workspace } from '@johannes.latzel/llm-chat-workspace';
|
|
2
|
+
import type { ShellExecutor, ShellExecutorFactory, ShellSessionDeathReason } from './types.js';
|
|
3
|
+
import type { ShellConfiguration } from './config.js';
|
|
4
|
+
import type { JobRecord, JobRegistry } from './job-registry.js';
|
|
5
|
+
/** Description of a dead session, kept so stale session IDs still produce descriptive errors. */
|
|
6
|
+
export interface ShellSessionTombstone {
|
|
7
|
+
reason: ShellSessionDeathReason;
|
|
8
|
+
message: string;
|
|
9
|
+
}
|
|
10
|
+
/** Internal session entry binding an executor to its workspace root. */
|
|
11
|
+
export interface SessionEntry {
|
|
12
|
+
executor: ShellExecutor;
|
|
13
|
+
workspaceRoot: string;
|
|
14
|
+
/** Working directory this session's jobs run in; the executor re-anchors here before each job. */
|
|
15
|
+
cwd: string;
|
|
16
|
+
/** Last time this session started or finished work; used by the idle-expiry sweeper. */
|
|
17
|
+
lastUsedMs: number;
|
|
18
|
+
/** Pending (queued) jobs in FIFO order — a shell runs a single command at a time. */
|
|
19
|
+
queue: JobRecord[];
|
|
20
|
+
/** True while the worker loop is draining this session's queue. */
|
|
21
|
+
processing: boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Registry of live shell sessions plus the tombstones of dead ones. Owns the
|
|
25
|
+
* session map, the FIFO job queue per session, and the bounded tombstone
|
|
26
|
+
* store. It is a lock-free store: every operation is synchronous and
|
|
27
|
+
* therefore atomic under the single-threaded event loop (`create` completes
|
|
28
|
+
* its asynchronous factory call before writing any shared state). The owning
|
|
29
|
+
* {@link ShellSessionManager} serializes access with its mutex, so this class
|
|
30
|
+
* holds no lock of its own.
|
|
31
|
+
*
|
|
32
|
+
* Sessions are bound to a workspace root at creation. The binding is used for
|
|
33
|
+
* permission checks; switching the active workspace never moves existing
|
|
34
|
+
* sessions. Executor close is single-owner: the registry only returns the
|
|
35
|
+
* executor (via {@link teardown}) or records a session as dead; it never
|
|
36
|
+
* closes executors itself.
|
|
37
|
+
*/
|
|
38
|
+
export declare class SessionRegistry {
|
|
39
|
+
private readonly factory;
|
|
40
|
+
private readonly config;
|
|
41
|
+
private readonly workspace;
|
|
42
|
+
private readonly jobs;
|
|
43
|
+
/** Tombstones are kept in insertion order and evicted FIFO once the cap is reached. */
|
|
44
|
+
private static readonly TOMBSTONE_CAP;
|
|
45
|
+
private static readonly DEATH_REASONS;
|
|
46
|
+
private sessions;
|
|
47
|
+
private tombstones;
|
|
48
|
+
constructor(factory: ShellExecutorFactory, config: ShellConfiguration, workspace: Workspace, jobs: JobRegistry);
|
|
49
|
+
/**
|
|
50
|
+
* Create a new shell session: prune dead sessions, enforce `maxSessions`,
|
|
51
|
+
* then build an executor bound to the resolved cwd.
|
|
52
|
+
* @param cwd - Optional working directory. Must resolve to a subpath of the
|
|
53
|
+
* configured workspace access dirs.
|
|
54
|
+
* @returns The session ID.
|
|
55
|
+
* @throws Error if max sessions reached or cwd is outside the accessible directories.
|
|
56
|
+
*/
|
|
57
|
+
create(cwd?: string): Promise<string>;
|
|
58
|
+
/** Validate and resolve a cwd path against the accessible directories. */
|
|
59
|
+
private validateCwd;
|
|
60
|
+
/** Resolve the workspace root (deepest containing access dir) for a cwd. */
|
|
61
|
+
private resolveWorkspaceRoot;
|
|
62
|
+
/** Get a session entry, or `undefined` when unknown or tombstoned. */
|
|
63
|
+
get(sessionId: string): SessionEntry | undefined;
|
|
64
|
+
/** Require a session entry, throwing a descriptive error when unknown. */
|
|
65
|
+
require(sessionId: string): SessionEntry;
|
|
66
|
+
has(sessionId: string): boolean;
|
|
67
|
+
/** Remove and return a session entry, or `undefined` when unknown. */
|
|
68
|
+
remove(sessionId: string): SessionEntry | undefined;
|
|
69
|
+
/** All live sessions as `[id, entry]` pairs. */
|
|
70
|
+
entries(): [string, SessionEntry][];
|
|
71
|
+
/** All live session entries. */
|
|
72
|
+
values(): SessionEntry[];
|
|
73
|
+
clear(): void;
|
|
74
|
+
/**
|
|
75
|
+
* Return the workspace root a session is currently bound to.
|
|
76
|
+
* @throws Error if session does not exist.
|
|
77
|
+
*/
|
|
78
|
+
getWorkspaceRoot(sessionId: string): string;
|
|
79
|
+
/**
|
|
80
|
+
* Return the working directory a session's jobs run in.
|
|
81
|
+
* @throws Error if session does not exist.
|
|
82
|
+
*/
|
|
83
|
+
getCwd(sessionId: string): string;
|
|
84
|
+
/**
|
|
85
|
+
* Permanently rebind a session to a different workspace root and working
|
|
86
|
+
* directory. Subsequent permission checks use the new root and jobs run in
|
|
87
|
+
* the new cwd.
|
|
88
|
+
* @throws Error if session does not exist.
|
|
89
|
+
*/
|
|
90
|
+
rebind(sessionId: string, workspaceRoot: string, cwd: string): void;
|
|
91
|
+
/**
|
|
92
|
+
* Enqueue a job and start the worker loop when the session is idle.
|
|
93
|
+
* Sets the job's queue position, records activity, and marks the session
|
|
94
|
+
* as processing. Synchronous and therefore atomic on its own.
|
|
95
|
+
* @returns True if the caller should start the worker loop.
|
|
96
|
+
*/
|
|
97
|
+
enqueue(sessionId: string, record: JobRecord): boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Shift the next job off a session's queue. Clearing the `processing` flag
|
|
100
|
+
* happens here too, so a job enqueued while the queue is draining always
|
|
101
|
+
* either gets picked up by the current worker or triggers a fresh one.
|
|
102
|
+
* @returns The entry and next job, or `undefined` when the session is gone
|
|
103
|
+
* or its queue has drained.
|
|
104
|
+
*/
|
|
105
|
+
dequeue(sessionId: string): {
|
|
106
|
+
entry: SessionEntry;
|
|
107
|
+
job: JobRecord;
|
|
108
|
+
} | undefined;
|
|
109
|
+
/** Current 1-based queue position of a queued job, or `undefined` if not queued. */
|
|
110
|
+
queuePosition(sessionId: string, jobId: string): number | undefined;
|
|
111
|
+
/** Record session activity; a no-op when the session is gone. */
|
|
112
|
+
touch(sessionId: string): void;
|
|
113
|
+
/** Remove a session's queue and return its still-queued jobs. */
|
|
114
|
+
takeQueue(entry: SessionEntry): JobRecord[];
|
|
115
|
+
/** Fail every still-queued job of a session with the given reason. */
|
|
116
|
+
failPending(entry: SessionEntry, reason: string): void;
|
|
117
|
+
/**
|
|
118
|
+
* Remove a session, tombstone it, and fail its pending jobs. When
|
|
119
|
+
* `expected` is given, only tears down if the live entry still is that one.
|
|
120
|
+
* @returns The session's executor for the caller to close, or `undefined`
|
|
121
|
+
* when the session was already gone (or no longer the expected entry).
|
|
122
|
+
*/
|
|
123
|
+
teardown(sessionId: string, reason: ShellSessionDeathReason, failReason: string, expected?: SessionEntry): ShellExecutor | undefined;
|
|
124
|
+
/** Live sessions idle for at least `sessionTimeout` with no pending work. */
|
|
125
|
+
expired(now: number, sessionTimeout: number): [string, SessionEntry][];
|
|
126
|
+
/**
|
|
127
|
+
* Record a dead session as a tombstone so stale IDs produce a descriptive
|
|
128
|
+
* error (with the relevant configured timeout value) instead of a bare
|
|
129
|
+
* "Session not found". Tombstones are bounded FIFO.
|
|
130
|
+
*/
|
|
131
|
+
recordDeath(sessionId: string, reason: ShellSessionDeathReason): void;
|
|
132
|
+
/** Descriptive "not found" error for a session ID, preferring a tombstone message. */
|
|
133
|
+
notFoundMessage(sessionId: string): string;
|
|
134
|
+
/**
|
|
135
|
+
* Remove sessions whose underlying process has exited, freeing their
|
|
136
|
+
* `maxSessions` slot. Queued jobs fail and the session is tombstoned.
|
|
137
|
+
*/
|
|
138
|
+
private pruneDead;
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=session-registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-registry.d.ts","sourceRoot":"","sources":["../../src/lib/session-registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,KAAK,EAAE,aAAa,EAAE,oBA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