@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.
Files changed (67) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +43 -0
  3. package/dist/index.d.ts +9 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +9 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/lib/bash-executor.d.ts +125 -0
  8. package/dist/lib/bash-executor.d.ts.map +1 -0
  9. package/dist/lib/bash-executor.js +314 -0
  10. package/dist/lib/bash-executor.js.map +1 -0
  11. package/dist/lib/config.d.ts +79 -0
  12. package/dist/lib/config.d.ts.map +1 -0
  13. package/dist/lib/config.js +216 -0
  14. package/dist/lib/config.js.map +1 -0
  15. package/dist/lib/env.d.ts +34 -0
  16. package/dist/lib/env.d.ts.map +1 -0
  17. package/dist/lib/env.js +77 -0
  18. package/dist/lib/env.js.map +1 -0
  19. package/dist/lib/job-registry.d.ts +55 -0
  20. package/dist/lib/job-registry.d.ts.map +1 -0
  21. package/dist/lib/job-registry.js +116 -0
  22. package/dist/lib/job-registry.js.map +1 -0
  23. package/dist/lib/permission.d.ts +101 -0
  24. package/dist/lib/permission.d.ts.map +1 -0
  25. package/dist/lib/permission.js +361 -0
  26. package/dist/lib/permission.js.map +1 -0
  27. package/dist/lib/session-manager.d.ts +148 -0
  28. package/dist/lib/session-manager.d.ts.map +1 -0
  29. package/dist/lib/session-manager.js +264 -0
  30. package/dist/lib/session-manager.js.map +1 -0
  31. package/dist/lib/session-queue.d.ts +58 -0
  32. package/dist/lib/session-queue.d.ts.map +1 -0
  33. package/dist/lib/session-queue.js +123 -0
  34. package/dist/lib/session-queue.js.map +1 -0
  35. package/dist/lib/session-registry.d.ts +140 -0
  36. package/dist/lib/session-registry.d.ts.map +1 -0
  37. package/dist/lib/session-registry.js +267 -0
  38. package/dist/lib/session-registry.js.map +1 -0
  39. package/dist/lib/types.d.ts +155 -0
  40. package/dist/lib/types.d.ts.map +1 -0
  41. package/dist/lib/types.js +37 -0
  42. package/dist/lib/types.js.map +1 -0
  43. package/dist/tools/shell-command-tool.d.ts +30 -0
  44. package/dist/tools/shell-command-tool.d.ts.map +1 -0
  45. package/dist/tools/shell-command-tool.js +138 -0
  46. package/dist/tools/shell-command-tool.js.map +1 -0
  47. package/dist/tools/shell-create-tool.d.ts +12 -0
  48. package/dist/tools/shell-create-tool.d.ts.map +1 -0
  49. package/dist/tools/shell-create-tool.js +24 -0
  50. package/dist/tools/shell-create-tool.js.map +1 -0
  51. package/dist/tools/shell-job-status-tool.d.ts +13 -0
  52. package/dist/tools/shell-job-status-tool.d.ts.map +1 -0
  53. package/dist/tools/shell-job-status-tool.js +59 -0
  54. package/dist/tools/shell-job-status-tool.js.map +1 -0
  55. package/dist/tools/shell-jobs-tool.d.ts +12 -0
  56. package/dist/tools/shell-jobs-tool.d.ts.map +1 -0
  57. package/dist/tools/shell-jobs-tool.js +28 -0
  58. package/dist/tools/shell-jobs-tool.js.map +1 -0
  59. package/dist/tools/shell-package.d.ts +54 -0
  60. package/dist/tools/shell-package.d.ts.map +1 -0
  61. package/dist/tools/shell-package.js +77 -0
  62. package/dist/tools/shell-package.js.map +1 -0
  63. package/dist/tools/shell-permissions-tool.d.ts +15 -0
  64. package/dist/tools/shell-permissions-tool.d.ts.map +1 -0
  65. package/dist/tools/shell-permissions-tool.js +38 -0
  66. package/dist/tools/shell-permissions-tool.js.map +1 -0
  67. package/package.json +87 -0
@@ -0,0 +1,267 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { workspaceForPath } from './permission.js';
3
+ /**
4
+ * Registry of live shell sessions plus the tombstones of dead ones. Owns the
5
+ * session map, the FIFO job queue per session, and the bounded tombstone
6
+ * store. It is a lock-free store: every operation is synchronous and
7
+ * therefore atomic under the single-threaded event loop (`create` completes
8
+ * its asynchronous factory call before writing any shared state). The owning
9
+ * {@link ShellSessionManager} serializes access with its mutex, so this class
10
+ * holds no lock of its own.
11
+ *
12
+ * Sessions are bound to a workspace root at creation. The binding is used for
13
+ * permission checks; switching the active workspace never moves existing
14
+ * sessions. Executor close is single-owner: the registry only returns the
15
+ * executor (via {@link teardown}) or records a session as dead; it never
16
+ * closes executors itself.
17
+ */
18
+ export class SessionRegistry {
19
+ factory;
20
+ config;
21
+ workspace;
22
+ jobs;
23
+ /** Tombstones are kept in insertion order and evicted FIFO once the cap is reached. */
24
+ static TOMBSTONE_CAP = 100;
25
+ static DEATH_REASONS = {
26
+ timeout: 'was killed because a command produced no output for too long',
27
+ expired: 'expired after being idle for too long',
28
+ 'process-exited': 'is dead because the underlying shell process exited',
29
+ closed: 'was closed'
30
+ };
31
+ sessions = new Map();
32
+ tombstones = new Map();
33
+ constructor(factory, config, workspace, jobs) {
34
+ this.factory = factory;
35
+ this.config = config;
36
+ this.workspace = workspace;
37
+ this.jobs = jobs;
38
+ }
39
+ /**
40
+ * Create a new shell session: prune dead sessions, enforce `maxSessions`,
41
+ * then build an executor bound to the resolved cwd.
42
+ * @param cwd - Optional working directory. Must resolve to a subpath of the
43
+ * configured workspace access dirs.
44
+ * @returns The session ID.
45
+ * @throws Error if max sessions reached or cwd is outside the accessible directories.
46
+ */
47
+ async create(cwd) {
48
+ const resolvedCwd = cwd !== undefined ? this.validateCwd(cwd) : this.workspace.currentPath;
49
+ this.pruneDead();
50
+ if (this.sessions.size >= this.config.maxSessions) {
51
+ throw new Error(`Maximum sessions reached (${this.config.maxSessions}). Close a session before creating a new one.`);
52
+ }
53
+ const executor = await this.factory.create(resolvedCwd);
54
+ const id = randomUUID();
55
+ this.sessions.set(id, {
56
+ executor,
57
+ workspaceRoot: this.resolveWorkspaceRoot(resolvedCwd),
58
+ cwd: resolvedCwd,
59
+ lastUsedMs: Date.now(),
60
+ queue: [],
61
+ processing: false
62
+ });
63
+ return id;
64
+ }
65
+ /** Validate and resolve a cwd path against the accessible directories. */
66
+ validateCwd(inputCwd) {
67
+ const resolved = this.workspace.normalize(inputCwd);
68
+ if (!this.workspace.canRead(resolved)) {
69
+ throw new Error(`cwd must be within the configured working directory (${this.workspace.currentPath})`);
70
+ }
71
+ return resolved;
72
+ }
73
+ /** Resolve the workspace root (deepest containing access dir) for a cwd. */
74
+ resolveWorkspaceRoot(cwd) {
75
+ const roots = this.workspace.getAccesses().map((a) => a.path);
76
+ return workspaceForPath(cwd, roots);
77
+ }
78
+ /** Get a session entry, or `undefined` when unknown or tombstoned. */
79
+ get(sessionId) {
80
+ return this.sessions.get(sessionId);
81
+ }
82
+ /** Require a session entry, throwing a descriptive error when unknown. */
83
+ require(sessionId) {
84
+ const entry = this.sessions.get(sessionId);
85
+ if (entry === undefined) {
86
+ throw new Error(this.notFoundMessage(sessionId));
87
+ }
88
+ return entry;
89
+ }
90
+ has(sessionId) {
91
+ return this.sessions.has(sessionId);
92
+ }
93
+ /** Remove and return a session entry, or `undefined` when unknown. */
94
+ remove(sessionId) {
95
+ const entry = this.sessions.get(sessionId);
96
+ this.sessions.delete(sessionId);
97
+ return entry;
98
+ }
99
+ /** All live sessions as `[id, entry]` pairs. */
100
+ entries() {
101
+ return [...this.sessions.entries()];
102
+ }
103
+ /** All live session entries. */
104
+ values() {
105
+ return [...this.sessions.values()];
106
+ }
107
+ clear() {
108
+ this.sessions.clear();
109
+ }
110
+ /**
111
+ * Return the workspace root a session is currently bound to.
112
+ * @throws Error if session does not exist.
113
+ */
114
+ getWorkspaceRoot(sessionId) {
115
+ return this.require(sessionId).workspaceRoot;
116
+ }
117
+ /**
118
+ * Return the working directory a session's jobs run in.
119
+ * @throws Error if session does not exist.
120
+ */
121
+ getCwd(sessionId) {
122
+ return this.require(sessionId).cwd;
123
+ }
124
+ /**
125
+ * Permanently rebind a session to a different workspace root and working
126
+ * directory. Subsequent permission checks use the new root and jobs run in
127
+ * the new cwd.
128
+ * @throws Error if session does not exist.
129
+ */
130
+ rebind(sessionId, workspaceRoot, cwd) {
131
+ const entry = this.require(sessionId);
132
+ entry.workspaceRoot = workspaceRoot;
133
+ entry.cwd = cwd;
134
+ }
135
+ /**
136
+ * Enqueue a job and start the worker loop when the session is idle.
137
+ * Sets the job's queue position, records activity, and marks the session
138
+ * as processing. Synchronous and therefore atomic on its own.
139
+ * @returns True if the caller should start the worker loop.
140
+ */
141
+ enqueue(sessionId, record) {
142
+ const entry = this.sessions.get(sessionId);
143
+ if (entry === undefined) {
144
+ throw new Error(this.notFoundMessage(sessionId));
145
+ }
146
+ record.position = entry.queue.length + 1;
147
+ entry.queue.push(record);
148
+ entry.lastUsedMs = Date.now();
149
+ const shouldStart = !entry.processing;
150
+ entry.processing = true;
151
+ return shouldStart;
152
+ }
153
+ /**
154
+ * Shift the next job off a session's queue. Clearing the `processing` flag
155
+ * happens here too, so a job enqueued while the queue is draining always
156
+ * either gets picked up by the current worker or triggers a fresh one.
157
+ * @returns The entry and next job, or `undefined` when the session is gone
158
+ * or its queue has drained.
159
+ */
160
+ dequeue(sessionId) {
161
+ const entry = this.sessions.get(sessionId);
162
+ if (entry === undefined) {
163
+ return undefined;
164
+ }
165
+ const job = entry.queue.shift();
166
+ if (job === undefined) {
167
+ entry.processing = false;
168
+ entry.lastUsedMs = Date.now();
169
+ return undefined;
170
+ }
171
+ return { entry, job };
172
+ }
173
+ /** Current 1-based queue position of a queued job, or `undefined` if not queued. */
174
+ queuePosition(sessionId, jobId) {
175
+ const entry = this.sessions.get(sessionId);
176
+ if (entry === undefined) {
177
+ return undefined;
178
+ }
179
+ const index = entry.queue.findIndex((queued) => queued.id === jobId);
180
+ return index >= 0 ? index + 1 : undefined;
181
+ }
182
+ /** Record session activity; a no-op when the session is gone. */
183
+ touch(sessionId) {
184
+ const entry = this.sessions.get(sessionId);
185
+ if (entry !== undefined) {
186
+ entry.lastUsedMs = Date.now();
187
+ }
188
+ }
189
+ /** Remove a session's queue and return its still-queued jobs. */
190
+ takeQueue(entry) {
191
+ const rest = entry.queue;
192
+ entry.queue = [];
193
+ return rest;
194
+ }
195
+ /** Fail every still-queued job of a session with the given reason. */
196
+ failPending(entry, reason) {
197
+ this.jobs.failAll(entry.queue, reason);
198
+ entry.queue = [];
199
+ }
200
+ /**
201
+ * Remove a session, tombstone it, and fail its pending jobs. When
202
+ * `expected` is given, only tears down if the live entry still is that one.
203
+ * @returns The session's executor for the caller to close, or `undefined`
204
+ * when the session was already gone (or no longer the expected entry).
205
+ */
206
+ teardown(sessionId, reason, failReason, expected) {
207
+ const current = this.sessions.get(sessionId);
208
+ if (current === undefined || (expected !== undefined && current !== expected)) {
209
+ return undefined;
210
+ }
211
+ this.sessions.delete(sessionId);
212
+ this.recordDeath(sessionId, reason);
213
+ this.failPending(current, failReason);
214
+ return current.executor;
215
+ }
216
+ /** Live sessions idle for at least `sessionTimeout` with no pending work. */
217
+ expired(now, sessionTimeout) {
218
+ const expired = [];
219
+ for (const [id, entry] of this.sessions) {
220
+ if (!entry.processing &&
221
+ entry.queue.length === 0 &&
222
+ now - entry.lastUsedMs >= sessionTimeout) {
223
+ expired.push([id, entry]);
224
+ }
225
+ }
226
+ return expired;
227
+ }
228
+ /**
229
+ * Record a dead session as a tombstone so stale IDs produce a descriptive
230
+ * error (with the relevant configured timeout value) instead of a bare
231
+ * "Session not found". Tombstones are bounded FIFO.
232
+ */
233
+ recordDeath(sessionId, reason) {
234
+ let detail = '';
235
+ if (reason === 'timeout') {
236
+ detail = ` (idle limit: ${this.config.ctrlCTimeout}ms)`;
237
+ }
238
+ else if (reason === 'expired') {
239
+ detail = ` (idle limit: ${this.config.sessionTimeout}ms)`;
240
+ }
241
+ const message = `Session ${sessionId} ${SessionRegistry.DEATH_REASONS[reason]}${detail}. Create a new session to continue.`;
242
+ this.tombstones.set(sessionId, { reason, message });
243
+ while (this.tombstones.size > SessionRegistry.TOMBSTONE_CAP) {
244
+ this.tombstones.delete(this.tombstones.keys().next().value);
245
+ }
246
+ }
247
+ /** Descriptive "not found" error for a session ID, preferring a tombstone message. */
248
+ notFoundMessage(sessionId) {
249
+ const tombstone = this.tombstones.get(sessionId);
250
+ if (tombstone !== undefined) {
251
+ return tombstone.message;
252
+ }
253
+ return `Session not found: ${sessionId}`;
254
+ }
255
+ /**
256
+ * Remove sessions whose underlying process has exited, freeing their
257
+ * `maxSessions` slot. Queued jobs fail and the session is tombstoned.
258
+ */
259
+ pruneDead() {
260
+ for (const [id, entry] of this.sessions) {
261
+ if (!entry.executor.isAlive()) {
262
+ this.teardown(id, 'process-exited', 'the shell process exited before the job could run');
263
+ }
264
+ }
265
+ }
266
+ }
267
+ //# sourceMappingURL=session-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-registry.js","sourceRoot":"","sources":["../../src/lib/session-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAKzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAsBnD;;;;;;;;;;;;;;GAcG;AACH,MAAM,OAAO,eAAe;IAcH;IACA;IACA;IACA;IAhBrB,uFAAuF;IAC/E,MAAM,CAAU,aAAa,GAAG,GAAG,CAAC;IACpC,MAAM,CAAU,aAAa,GAA4C;QAC7E,OAAO,EAAE,8DAA8D;QACvE,OAAO,EAAE,uCAAuC;QAChD,gBAAgB,EAAE,qDAAqD;QACvE,MAAM,EAAE,YAAY;KACvB,CAAC;IAEM,QAAQ,GAAG,IAAI,GAAG,EAAwB,CAAC;IAC3C,UAAU,GAAG,IAAI,GAAG,EAAiC,CAAC;IAE9D,YACqB,OAA6B,EAC7B,MAA0B,EAC1B,SAAoB,EACpB,IAAiB;QAHjB,YAAO,GAAP,OAAO,CAAsB;QAC7B,WAAM,GAAN,MAAM,CAAoB;QAC1B,cAAS,GAAT,SAAS,CAAW;QACpB,SAAI,GAAJ,IAAI,CAAa;IACnC,CAAC;IAEJ;;;;;;;OAOG;IACH,KAAK,CAAC,MAAM,CAAC,GAAY;QACrB,MAAM,WAAW,GAAG,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,C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AAE,CAAC;YAC9B,MAAM,GAAG,iBAAiB,IAAI,CAAC,MAAM,CAAC,cAAc,KAAK,CAAC;QAC9D,CAAC;QACD,MAAM,OAAO,GAAG,WAAW,SAAS,IAAI,eAAe,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,MAAM,qCAAqC,CAAC;QAC5H,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;QACpD,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,GAAG,eAAe,CAAC,aAAa,EAAE,CAAC;YAC1D,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAM,CAAC,CAAC;QACjE,CAAC;IACL,CAAC;IAED,sFAAsF;IACtF,eAAe,CAAC,SAAiB;QAC7B,MAAM,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC1B,OAAO,SAAS,CAAC,OAAO,CAAC;QAC7B,CAAC;QACD,OAAO,sBAAsB,SAAS,EAAE,CAAC;IAC7C,CAAC;IAED;;;OAGG;IACK,SAAS;QACb,KAAK,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACtC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;gBAC5B,IAAI,CAAC,QAAQ,CACT,EAAE,EACF,gBAAgB,EAChB,mDAAmD,CACtD,CAAC;YACN,CAAC;QACL,CAAC;IACL,CAAC"}
@@ -0,0 +1,155 @@
1
+ /** Permission action for shell commands. */
2
+ export declare enum PermissionAction {
3
+ /** Allow the command to execute. */
4
+ Allow = "allow",
5
+ /** Deny the command execution. */
6
+ Deny = "deny"
7
+ }
8
+ /** Access level a permission rule requires from its workspace. */
9
+ export declare enum PermissionAccess {
10
+ /** The rule applies in any accessible workspace (default). */
11
+ Read = "read",
12
+ /** The rule only applies in a workspace with write access. */
13
+ Write = "write"
14
+ }
15
+ /** Why a shell command was denied. */
16
+ export declare enum PermissionDenyReason {
17
+ /** A rule pattern or the default permission denied the command. */
18
+ Pattern = "pattern",
19
+ /** A write-classified rule matched but the workspace root is not writable. */
20
+ WriteAccess = "write-access"
21
+ }
22
+ /** A single permission rule matching a glob pattern to an action. */
23
+ export interface PermissionRule {
24
+ /** Glob pattern to match against subcommands (e.g. "git *"). */
25
+ pattern: string;
26
+ /** Action to take when the pattern matches. */
27
+ action: PermissionAction;
28
+ /** Access level required from the workspace. Defaults to {@link PermissionAccess.Read}. */
29
+ access?: PermissionAccess;
30
+ }
31
+ /** Permission settings for a single workspace, keyed by its resolved root path. */
32
+ export interface WorkspacePermissions {
33
+ /** Default action for commands not matching any rule in this workspace. */
34
+ defaultPermission: PermissionAction;
35
+ /** Permission rules applied in this workspace. */
36
+ permissionRules: PermissionRule[];
37
+ }
38
+ /** Contents of the shell permission config file (strict JSON). */
39
+ export interface ShellConfigFile {
40
+ /** Global permission settings (default: deny, no rules). */
41
+ globalPermissions?: WorkspacePermissions;
42
+ /** Per-workspace permission settings keyed by resolved workspace root path. */
43
+ workspacePermissions?: Record<string, WorkspacePermissions>;
44
+ }
45
+ /** Result of executing a shell command. */
46
+ export interface ShellCommandResult {
47
+ /** Standard output from the command. */
48
+ stdout: string;
49
+ /** Standard error from the command. */
50
+ stderr: string;
51
+ /** Exit code of the command (0 = success). */
52
+ exitCode: number;
53
+ /** True if the command was killed due to timeout. */
54
+ timedOut: boolean;
55
+ /** False if the bash process was killed (session is dead). */
56
+ sessionAlive: boolean;
57
+ /** Ms of inactivity (idle limit) after which the command was timed out; present when timedOut is true. */
58
+ idleTimeoutMs?: number;
59
+ }
60
+ /** Execution state of a background job. */
61
+ export declare enum ShellJobStatus {
62
+ /** Submitted and waiting for the shell to become free. */
63
+ Queued = "queued",
64
+ /** Currently running in the shell. */
65
+ Running = "running",
66
+ /** Finished and produced a result. */
67
+ Completed = "completed",
68
+ /** Failed before producing a result (e.g. the session died). */
69
+ Failed = "failed"
70
+ }
71
+ /**
72
+ * A background job submitted to a shell session. Jobs run one at a time per
73
+ * session (the shell executes a single command at a time); submitted jobs are
74
+ * queued in FIFO order. Completed and failed jobs remain queryable by ID until
75
+ * they are evicted from the bounded job registry.
76
+ */
77
+ export interface ShellJob {
78
+ /** Globally unique job ID. */
79
+ id: string;
80
+ /** Session the job was submitted to. */
81
+ sessionId: string;
82
+ /** Working directory the job runs in (the shell re-anchors here before running). */
83
+ cwd: string;
84
+ /** The command the job runs. */
85
+ command: string;
86
+ /** Current execution state. */
87
+ status: ShellJobStatus;
88
+ /** Effective idle timeout (ms) the job runs under. */
89
+ idleTimeoutMs: number;
90
+ /** Epoch ms when the job was submitted. */
91
+ submittedAt: number;
92
+ /** Epoch ms when the job started running; present once started. */
93
+ startedAt?: number;
94
+ /** Epoch ms when the job finished; present once completed or failed. */
95
+ finishedAt?: number;
96
+ /** Standard output; present when the job completed. */
97
+ stdout?: string;
98
+ /** Standard error; present when the job completed. */
99
+ stderr?: string;
100
+ /** Exit code; present when the job completed. */
101
+ exitCode?: number;
102
+ /** True when the job was killed due to timeout; present when the job completed. */
103
+ timedOut?: boolean;
104
+ /** False when the shell process died as a result of this job; present when the job completed. */
105
+ sessionAlive?: boolean;
106
+ /** Queue position (1-based) at submission; recomputed on read while queued. */
107
+ position: number;
108
+ /** Human-readable failure reason; present when the job failed. */
109
+ error?: string;
110
+ }
111
+ /** Snapshot of an active shell session for administrative listing. */
112
+ export interface ShellSessionInfo {
113
+ /** Globally unique session ID. */
114
+ id: string;
115
+ /** Workspace root the session is bound to for permission checks. */
116
+ workspaceRoot: string;
117
+ /** Number of jobs still queued (not yet started). */
118
+ queued: number;
119
+ /** ID of the currently running job, if one is executing. */
120
+ runningJobId?: string;
121
+ }
122
+ /** Options for {@link ShellExecutor.execute}. */
123
+ export interface ShellExecuteOptions {
124
+ /**
125
+ * Working directory the command runs in. When provided, the executor
126
+ * re-anchors the shell into this directory before running the command.
127
+ */
128
+ cwd?: string;
129
+ /**
130
+ * Idle timeout in ms (resets on stdout/stderr activity). When omitted or 0,
131
+ * the executor's configured `ctrlCTimeout` applies.
132
+ */
133
+ idleTimeoutMs?: number;
134
+ }
135
+ /** Interface for a single persistent shell session. */
136
+ export interface ShellExecutor {
137
+ /** Execute a command in this session. */
138
+ execute(command: string, options?: ShellExecuteOptions): Promise<ShellCommandResult>;
139
+ /**
140
+ * Close this session and clean up resources. Idempotent: subsequent calls
141
+ * are no-ops. Safe to call while {@link execute} is in flight — the running
142
+ * command is terminated and its result reports `sessionAlive: false`.
143
+ */
144
+ close(): Promise<void>;
145
+ /** True while the underlying shell process is still running. */
146
+ isAlive(): boolean;
147
+ }
148
+ /** Factory interface for creating new {@link ShellExecutor} instances. */
149
+ export interface ShellExecutorFactory {
150
+ /** Create a new shell executor (one session). */
151
+ create(cwd?: string): Promise<ShellExecutor>;
152
+ }
153
+ /** Why a shell session is no longer usable. */
154
+ export type ShellSessionDeathReason = 'timeout' | 'expired' | 'process-exited' | 'closed';
155
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,oBAAY,gBAAgB;IACxB,oCAAoC;IACpC,KAAK,UAAU;IACf,kCAAkC;IAClC,IAAI,SAAS;CAChB;AAED,kEAAkE;AAClE,oBAAY,gBAAgB;IACxB,8DAA8D;IAC9D,IAAI,SAAS;IACb,8DAA8D;IAC9D,KAAK,UAAU;CAClB;AAED,sCAAsC;AACtC,oBAAY,oBAAoB;IAC5B,mEAAmE;IACnE,OAAO,YAAY;IACnB,8EAA8E;IAC9E,WAAW,iBAAiB;CAC/B;AAED,qEAAqE;AACrE,MAAM,WAAW,cAAc;IAC3B,gEA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WAAW,oBAAoB;IACjC,iDAAiD;IACjD,MAAM,CAAC,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CAChD;AAED,+CAA+C;AAC/C,MAAM,MAAM,uBAAuB,GAAG,SAAS,GAAG,SAAS,GAAG,gBAAgB,GAAG,QAAQ,CAAC"}
@@ -0,0 +1,37 @@
1
+ /** Permission action for shell commands. */
2
+ export var PermissionAction;
3
+ (function (PermissionAction) {
4
+ /** Allow the command to execute. */
5
+ PermissionAction["Allow"] = "allow";
6
+ /** Deny the command execution. */
7
+ PermissionAction["Deny"] = "deny";
8
+ })(PermissionAction || (PermissionAction = {}));
9
+ /** Access level a permission rule requires from its workspace. */
10
+ export var PermissionAccess;
11
+ (function (PermissionAccess) {
12
+ /** The rule applies in any accessible workspace (default). */
13
+ PermissionAccess["Read"] = "read";
14
+ /** The rule only applies in a workspace with write access. */
15
+ PermissionAccess["Write"] = "write";
16
+ })(PermissionAccess || (PermissionAccess = {}));
17
+ /** Why a shell command was denied. */
18
+ export var PermissionDenyReason;
19
+ (function (PermissionDenyReason) {
20
+ /** A rule pattern or the default permission denied the command. */
21
+ PermissionDenyReason["Pattern"] = "pattern";
22
+ /** A write-classified rule matched but the workspace root is not writable. */
23
+ PermissionDenyReason["WriteAccess"] = "write-access";
24
+ })(PermissionDenyReason || (PermissionDenyReason = {}));
25
+ /** Execution state of a background job. */
26
+ export var ShellJobStatus;
27
+ (function (ShellJobStatus) {
28
+ /** Submitted and waiting for the shell to become free. */
29
+ ShellJobStatus["Queued"] = "queued";
30
+ /** Currently running in the shell. */
31
+ ShellJobStatus["Running"] = "running";
32
+ /** Finished and produced a result. */
33
+ ShellJobStatus["Completed"] = "completed";
34
+ /** Failed before producing a result (e.g. the session died). */
35
+ ShellJobStatus["Failed"] = "failed";
36
+ })(ShellJobStatus || (ShellJobStatus = {}));
37
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,MAAM,CAAN,IAAY,gBAKX;AALD,WAAY,gBAAgB;IACxB,oCAAoC;IACpC,mCAAe,CAAA;IACf,kCAAkC;IAClC,iCAAa,CAAA;AACjB,CAAC,EALW,gBAAgB,KAAhB,gBAAgB,QAK3B;AAED,kEAAkE;AAClE,MAAM,CAAN,IAAY,gBAKX;AALD,WAAY,gBAAgB;IACxB,8DAA8D;IAC9D,iCAAa,CAAA;IACb,8DAA8D;IAC9D,mCAAe,CAAA;AACnB,CAAC,EALW,gBAAgB,KAAhB,gBAAgB,QAK3B;AAED,sCAAsC;AACtC,MAAM,CAAN,IAAY,oBAKX;AALD,WAAY,oBAAoB;IAC5B,mEAAmE;IACnE,2CAAmB,CAAA;IACnB,8EAA8E;IAC9E,oDAA4B,CAAA;AAChC,CAAC,EALW,oBAAoB,KAApB,oBAAoB,QAK/B;AA4CD,2CAA2C;AAC3C,MAAM,CAAN,IAAY,cASX;AATD,WAAY,cAAc;IACtB,0DAA0D;IAC1D,mCAAiB,CAAA;IACjB,sCAAsC;IACtC,qCAAmB,CAAA;IACnB,sCAAsC;IACtC,yCAAuB,CAAA;IACvB,gEAAgE;IAChE,mCAAiB,CAAA;AACrB,CAAC,EATW,cAAc,KAAd,cAAc,QASzB"}
@@ -0,0 +1,30 @@
1
+ import { Tool, type PartialToolResult } from '@johannes.latzel/llm-chat';
2
+ import type { Workspace } from '@johannes.latzel/llm-chat-workspace';
3
+ import type { ShellSessionManager } from '../lib/session-manager.js';
4
+ import { PermissionSystem } from '../lib/permission.js';
5
+ /**
6
+ * Tool that executes a shell command in a persistent session.
7
+ * Checks command permissions before execution. With `background=true` the
8
+ * command is submitted as a queued job and the tool returns a job ID
9
+ * immediately; poll `shell_job_status` for its progress and results.
10
+ */
11
+ export declare class ShellCommandTool extends Tool {
12
+ private sessionManager;
13
+ private permissionSystem;
14
+ private workspace;
15
+ constructor(sessionManager: ShellSessionManager, permissionSystem: PermissionSystem, workspace: Workspace);
16
+ protected onExecute(args: Record<string, unknown>): Promise<PartialToolResult>;
17
+ /** Only finite, positive numbers are honored; anything else falls back to the default. */
18
+ private parseTimeout;
19
+ /**
20
+ * Build the command to execute, its working directory, and the workspace
21
+ * root its permissions are checked against. When `useCurrentWorkspace` is
22
+ * true, the command runs in the current workspace and the workspace root is
23
+ * derived from that path; otherwise the session's bound root and cwd are used.
24
+ */
25
+ private buildEffectiveCommand;
26
+ private getDeniedSubcommands;
27
+ private formatJobSubmitted;
28
+ private formatOutput;
29
+ }
30
+ //# sourceMappingURL=shell-command-tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shell-command-tool.d.ts","sourceRoot":"","sources":["../../src/tools/shell-command-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,IAAI,EAIJ,KAAK,iBAAiB,EACzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qCAAqC,CAAC;AACrE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AACrE,OAAO,EACH,gBAAgB,EAGnB,MAAM,sBAAsB,CAAC;AAc9B;;;;;GAKG;AACH,qBAAa,gBAAiB,SAAQ,IAAI;IAElC,OAAO,CAAC,cAAc;IACtB,OAAO,CAAC,gBAAgB;IACxB,OAAO,CAAC,SAAS;gBAFT,cAAc,EAAE,mBAAmB,EACnC,gBAAgB,EAAE,gBAAgB,EAClC,SAAS,EAAE,SAAS;cA2BhB,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAwDpF,0FAA0F;IAC1F,OAAO,CAAC,YAAY;IAOpB;;;;;OAKG;YACW,qBAAqB;IAqBnC,OAAO,CAAC,oBAAoB;IAe5B,OAAO,CAAC,kBAAkB;IAI1B,OAAO,CAAC,YAAY;CAmCvB"}
@@ -0,0 +1,138 @@
1
+ import { Tool, ToolParameters, ToolParameterProperty, ResultStatus } from '@johannes.latzel/llm-chat';
2
+ import { workspaceForPath } from '../lib/permission.js';
3
+ import { PermissionAction, PermissionDenyReason } from '../lib/types.js';
4
+ /**
5
+ * Tool that executes a shell command in a persistent session.
6
+ * Checks command permissions before execution. With `background=true` the
7
+ * command is submitted as a queued job and the tool returns a job ID
8
+ * immediately; poll `shell_job_status` for its progress and results.
9
+ */
10
+ export class ShellCommandTool extends Tool {
11
+ sessionManager;
12
+ permissionSystem;
13
+ workspace;
14
+ constructor(sessionManager, permissionSystem, workspace) {
15
+ super('shell_command', 'Executes a shell command in a persistent session. Supports pipes (|), logical operators (&&, ||), and redirects. Requires a session ID from shell_create. ' +
16
+ 'Set background=true to submit the command as a queued job and return immediately with a job ID; poll shell_job_status / shell_jobs for results. ' +
17
+ 'Set timeout to override the max idle time (no output) in ms; larger values are capped by the server config. ' +
18
+ 'Set useCurrentWorkspace=true to run the command in the current workspace and permanently rebind the session to it.', new ToolParameters({
19
+ command: ToolParameterProperty.string('The shell command to execute.'),
20
+ sessionId: ToolParameterProperty.string('The session ID from shell_create.'),
21
+ useCurrentWorkspace: ToolParameterProperty.boolean('When true, run the command in the current workspace and permanently bind this session to that workspace.'),
22
+ background: ToolParameterProperty.boolean('When true, submit the command as a background job, return immediately with a jobId, and continue with other work. Poll shell_job_status for the result.'),
23
+ timeout: ToolParameterProperty.integer('Max idle time in ms (no stdout/stderr output) before the command is killed. Defaults to the configured foreground or background timeout; larger values are capped by the server config.')
24
+ }, ['command', 'sessionId']));
25
+ this.sessionManager = sessionManager;
26
+ this.permissionSystem = permissionSystem;
27
+ this.workspace = workspace;
28
+ }
29
+ async onExecute(args) {
30
+ this.validateRequiredParams(args, ['command', 'sessionId']);
31
+ const command = args['command'];
32
+ const sessionId = args['sessionId'];
33
+ const useCurrentWorkspace = args['useCurrentWorkspace'] === true;
34
+ const background = args['background'] === true;
35
+ const timeout = this.parseTimeout(args['timeout']);
36
+ const effective = await this.buildEffectiveCommand(sessionId, command, useCurrentWorkspace);
37
+ // Check permissions against the effective workspace root
38
+ const permission = this.permissionSystem.check(effective.command, effective.workspaceRoot);
39
+ if (permission.action === PermissionAction.Deny) {
40
+ const deniedSubs = this.getDeniedSubcommands(permission, effective.workspaceRoot);
41
+ const message = deniedSubs.length > 0
42
+ ? `Permission denied for: ${deniedSubs.join(', ')}`
43
+ : 'Permission denied';
44
+ const reason = permission.denyReason === PermissionDenyReason.WriteAccess
45
+ ? ` (requires write access to ${effective.workspaceRoot})`
46
+ : '';
47
+ return { result: message + reason, status: ResultStatus.Error };
48
+ }
49
+ // Permanently rebind the session once the command is allowed
50
+ if (useCurrentWorkspace) {
51
+ await this.sessionManager.rebindSession(sessionId, effective.workspaceRoot, effective.cwd);
52
+ }
53
+ if (background) {
54
+ const job = await this.sessionManager.submitCommand(sessionId, effective.command, {
55
+ cwd: effective.cwd,
56
+ ...(timeout !== undefined ? { timeout } : {})
57
+ });
58
+ return { result: this.formatJobSubmitted(job), status: ResultStatus.Success };
59
+ }
60
+ // Execute command (blocks until the shell gets to it, running queued jobs first)
61
+ const result = await this.sessionManager.executeCommand(sessionId, effective.command, {
62
+ cwd: effective.cwd,
63
+ ...(timeout !== undefined ? { timeout } : {})
64
+ });
65
+ // Format output
66
+ const output = this.formatOutput(result);
67
+ const status = result.exitCode === 0 ? ResultStatus.Success : ResultStatus.Error;
68
+ return { result: output, status };
69
+ }
70
+ /** Only finite, positive numbers are honored; anything else falls back to the default. */
71
+ parseTimeout(value) {
72
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
73
+ return undefined;
74
+ }
75
+ return value;
76
+ }
77
+ /**
78
+ * Build the command to execute, its working directory, and the workspace
79
+ * root its permissions are checked against. When `useCurrentWorkspace` is
80
+ * true, the command runs in the current workspace and the workspace root is
81
+ * derived from that path; otherwise the session's bound root and cwd are used.
82
+ */
83
+ async buildEffectiveCommand(sessionId, command, useCurrentWorkspace) {
84
+ if (!useCurrentWorkspace) {
85
+ return {
86
+ command,
87
+ cwd: await this.sessionManager.getSessionCwd(sessionId),
88
+ workspaceRoot: await this.sessionManager.getSessionWorkspaceRoot(sessionId)
89
+ };
90
+ }
91
+ const roots = this.workspace.getAccesses().map((a) => a.path);
92
+ const workspaceRoot = workspaceForPath(this.workspace.currentPath, roots);
93
+ return {
94
+ command,
95
+ cwd: this.workspace.currentPath,
96
+ workspaceRoot
97
+ };
98
+ }
99
+ getDeniedSubcommands(permission, workspaceRoot) {
100
+ // Re-check each subcommand to find which ones are denied
101
+ const denied = [];
102
+ for (const sub of permission.subcommands) {
103
+ const check = this.permissionSystem.check(sub, workspaceRoot);
104
+ if (check.action === PermissionAction.Deny) {
105
+ denied.push(sub);
106
+ }
107
+ }
108
+ return denied;
109
+ }
110
+ formatJobSubmitted(job) {
111
+ return `Background job ${job.id} submitted (status: ${job.status}, queue position ${job.position}). Poll shell_job_status with this jobId for results.`;
112
+ }
113
+ formatOutput(result) {
114
+ const parts = [];
115
+ // Add timeout/session death messages first
116
+ const idleLimit = result.idleTimeoutMs !== undefined ? ` (idle limit: ${result.idleTimeoutMs}ms)` : '';
117
+ if (result.timedOut && !result.sessionAlive) {
118
+ parts.push(`Command timed out and session was killed${idleLimit}.`);
119
+ }
120
+ else if (result.timedOut) {
121
+ parts.push(`Command timed out${idleLimit}.`);
122
+ }
123
+ if (!result.sessionAlive) {
124
+ parts.push('Session is no longer alive. Create a new session to continue.');
125
+ }
126
+ if (result.stdout.length > 0) {
127
+ parts.push(result.stdout);
128
+ }
129
+ if (result.stderr.length > 0) {
130
+ parts.push(`[stderr] ${result.stderr}`);
131
+ }
132
+ if (result.exitCode !== 0) {
133
+ parts.push(`[exit code: ${result.exitCode}]`);
134
+ }
135
+ return parts.length > 0 ? parts.join('\n') : '(no output)';
136
+ }
137
+ }
138
+ //# sourceMappingURL=shell-command-tool.js.map