opencode-fs-plugin 3.4.0 → 3.6.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/src/core/jobs.ts CHANGED
@@ -3,11 +3,11 @@
3
3
  * license-wizard managed-header v1 EPL-2.0 short 73897e75828f
4
4
  */
5
5
 
6
- import { randomUUID } from "node:crypto";
6
+ import { randomBytes, randomUUID } from "node:crypto";
7
7
  import * as fs from "node:fs/promises";
8
8
  import * as os from "node:os";
9
9
  import * as path from "node:path";
10
- import { FsError, errorMessage } from "./errors.js";
10
+ import { FsError, errorMessage, fromErrno, isMissing } from "./errors.js";
11
11
  import type { RenderedResult } from "./format.js";
12
12
 
13
13
  export type JobState = "running" | "completed" | "failed" | "cancelled";
@@ -33,6 +33,10 @@ export interface JobManagerOptions {
33
33
  readonly limit?: number;
34
34
  readonly ttlMs?: number;
35
35
  readonly now?: () => number;
36
+ /** Internal bound on retained finished jobs; not a plugin option. */
37
+ readonly retainedLimit?: number;
38
+ /** Internal bound on one rendered result's content; not a plugin option. */
39
+ readonly maxResultBytes?: number;
36
40
  }
37
41
 
38
42
  interface JobRecord {
@@ -44,6 +48,8 @@ interface JobRecord {
44
48
  error?: string;
45
49
  readonly statusPath: string;
46
50
  readonly controller: AbortController;
51
+ /** Session that created the job; never exposed in snapshots. */
52
+ readonly owner: string;
47
53
  result?: RenderedResult;
48
54
  done: Promise<void>;
49
55
  timer?: NodeJS.Timeout;
@@ -51,6 +57,23 @@ interface JobRecord {
51
57
 
52
58
  const DEFAULT_LIMIT = 8;
53
59
  const DEFAULT_TTL_MS = 60 * 60 * 1000;
60
+ /**
61
+ * Finished jobs are kept so `fs.job wait` can return their results. The TTL
62
+ * alone bounds time, not count, so a burst of quick jobs would retain an
63
+ * unbounded number of results and status files. Keep a finite window and evict
64
+ * the oldest finished job before admitting a new one.
65
+ */
66
+ const DEFAULT_MAX_RETAINED_JOBS = 64;
67
+ /** One retained rendered result; larger text is truncated and binary is dropped. */
68
+ const DEFAULT_MAX_RESULT_BYTES = 1024 * 1024;
69
+ const TRUNCATION_MARKER = "\n[truncated]";
70
+ /**
71
+ * Owner used by direct `JobManager` callers (unit tests and internal helpers).
72
+ * The plugin always passes the originating host session id, so this namespace
73
+ * cannot collide with a real `ses_…` session and never widens another caller's
74
+ * view.
75
+ */
76
+ const LOCAL_OWNER = "local";
54
77
 
55
78
  function snapshot(job: JobRecord): JobStatus {
56
79
  return {
@@ -71,36 +94,31 @@ export class JobManager {
71
94
  private readonly dir: string;
72
95
  private readonly limit: number;
73
96
  private readonly ttlMs: number;
97
+ private readonly retainedLimit: number;
98
+ private readonly maxResultBytes: number;
74
99
  private readonly now: () => number;
100
+ /** Serializes admission so concurrent starts cannot overrun either cap. */
101
+ private admission: Promise<void> = Promise.resolve();
75
102
 
76
103
  constructor(options: JobManagerOptions = {}) {
77
104
  this.dir = options.dir ?? path.join(os.tmpdir(), "opencode", "fs-jobs", String(process.pid));
78
105
  this.limit = options.limit ?? DEFAULT_LIMIT;
79
106
  this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
107
+ this.retainedLimit = options.retainedLimit ?? DEFAULT_MAX_RETAINED_JOBS;
108
+ this.maxResultBytes = options.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES;
80
109
  this.now = options.now ?? Date.now;
81
110
  }
82
111
 
83
- async start(tool: string, run: (signal: AbortSignal) => Promise<RenderedResult>): Promise<JobStatus> {
84
- if (this.runningCount() >= this.limit) {
85
- throw new FsError(`background job limit reached (${this.limit} running).`, "busy");
86
- }
87
-
88
- const id = `job_${randomUUID()}`;
89
- const job: JobRecord = {
90
- id,
91
- tool,
92
- state: "running",
93
- startedAt: this.now(),
94
- statusPath: path.join(this.dir, `${id}.json`),
95
- controller: new AbortController(),
96
- done: Promise.resolve(),
97
- };
98
- this.jobs.set(id, job);
99
-
112
+ async start(
113
+ tool: string,
114
+ run: (signal: AbortSignal) => Promise<RenderedResult>,
115
+ owner: string = LOCAL_OWNER,
116
+ ): Promise<JobStatus> {
117
+ const job = await this.admit(tool, owner);
100
118
  try {
101
119
  await this.write(job);
102
120
  } catch (error) {
103
- this.jobs.delete(id);
121
+ this.jobs.delete(job.id);
104
122
  throw error;
105
123
  }
106
124
 
@@ -109,19 +127,23 @@ export class JobManager {
109
127
  return snapshot(job);
110
128
  }
111
129
 
112
- status(id: string): JobStatus {
113
- return snapshot(this.require(id));
130
+ status(id: string, owner: string = LOCAL_OWNER): JobStatus {
131
+ return snapshot(this.require(id, owner));
114
132
  }
115
133
 
116
- list(): JobStatus[] {
134
+ list(owner: string = LOCAL_OWNER): JobStatus[] {
117
135
  return [...this.jobs.values()]
136
+ .filter((job) => job.owner === owner)
118
137
  .sort((a, b) => b.startedAt - a.startedAt)
119
138
  .map((job) => snapshot(job));
120
139
  }
121
140
 
122
- async wait(id: string, timeoutMs: number): Promise<JobWait> {
123
- const job = this.require(id);
141
+ async wait(id: string, timeoutMs: number, owner: string = LOCAL_OWNER): Promise<JobWait> {
142
+ const job = this.require(id, owner);
124
143
  if (job.state !== "running") {
144
+ // State flips before the final status write in `execute`; await the
145
+ // completion promise so a caller never observes a stale "running" file.
146
+ await job.done;
125
147
  return { status: snapshot(job), timedOut: false, ...(job.result ? { result: job.result } : {}) };
126
148
  }
127
149
  await new Promise<void>((resolve) => {
@@ -138,8 +160,8 @@ export class JobManager {
138
160
  };
139
161
  }
140
162
 
141
- cancel(id: string): JobStatus {
142
- const job = this.require(id);
163
+ cancel(id: string, owner: string = LOCAL_OWNER): JobStatus {
164
+ const job = this.require(id, owner);
143
165
  if (job.state === "running") job.controller.abort();
144
166
  return snapshot(job);
145
167
  }
@@ -152,6 +174,85 @@ export class JobManager {
152
174
  this.jobs.clear();
153
175
  }
154
176
 
177
+ /**
178
+ * Reserve both a running slot and a retained slot. The check, eviction and
179
+ * insertion run under one admission lock, so two concurrent starts cannot
180
+ * both observe free capacity and then both insert.
181
+ */
182
+ private async admit(tool: string, owner: string): Promise<JobRecord> {
183
+ if (owner.length === 0) throw new FsError("job owner is required.", "invalid");
184
+ return this.withAdmission(async () => {
185
+ if (this.runningCount() >= this.limit) {
186
+ throw new FsError(`background job limit reached (${this.limit} running).`, "busy");
187
+ }
188
+ await this.ensureCapacity();
189
+
190
+ const id = `job_${randomUUID()}`;
191
+ const job: JobRecord = {
192
+ id,
193
+ tool,
194
+ owner,
195
+ state: "running",
196
+ startedAt: this.now(),
197
+ statusPath: path.join(this.dir, `${id}.json`),
198
+ controller: new AbortController(),
199
+ done: Promise.resolve(),
200
+ };
201
+ this.jobs.set(id, job);
202
+ return job;
203
+ });
204
+ }
205
+
206
+ private async withAdmission<T>(task: () => Promise<T>): Promise<T> {
207
+ const previous = this.admission;
208
+ let release!: () => void;
209
+ this.admission = new Promise<void>((resolve) => {
210
+ release = resolve;
211
+ });
212
+ await previous;
213
+ try {
214
+ return await task();
215
+ } finally {
216
+ release();
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Evict the oldest finished jobs until one slot remains for a new job.
222
+ * Running jobs are never evicted; if only running jobs remain, the caller
223
+ * fails with `busy` rather than growing the retained window.
224
+ */
225
+ private async ensureCapacity(): Promise<void> {
226
+ while (this.jobs.size >= this.retainedLimit) {
227
+ const victim = this.oldestFinished();
228
+ if (victim === undefined) {
229
+ throw new FsError(
230
+ `background job retention limit reached (${this.retainedLimit} jobs).`,
231
+ "busy",
232
+ );
233
+ }
234
+ // Remove it from the map first so concurrent starts cannot pick the same
235
+ // victim; then wait for its final status write before deleting the file.
236
+ this.jobs.delete(victim.id);
237
+ clearTimeout(victim.timer);
238
+ await victim.done;
239
+ clearTimeout(victim.timer);
240
+ /* v8 ignore next -- retained status-file cleanup is best-effort */
241
+ await fs.rm(victim.statusPath, { force: true }).catch(() => {});
242
+ }
243
+ }
244
+
245
+ private oldestFinished(): JobRecord | undefined {
246
+ let oldest: JobRecord | undefined;
247
+ for (const job of this.jobs.values()) {
248
+ if (job.state === "running") continue;
249
+ if (oldest === undefined || (job.finishedAt as number) < (oldest.finishedAt as number)) {
250
+ oldest = job;
251
+ }
252
+ }
253
+ return oldest;
254
+ }
255
+
155
256
  private async execute(
156
257
  job: JobRecord,
157
258
  run: (signal: AbortSignal) => Promise<RenderedResult>,
@@ -162,7 +263,7 @@ export class JobManager {
162
263
  job.state = "cancelled";
163
264
  } else {
164
265
  job.state = "completed";
165
- job.result = result;
266
+ job.result = this.boundResult(result);
166
267
  }
167
268
  } catch (error) {
168
269
  job.state = job.controller.signal.aborted ? "cancelled" : "failed";
@@ -193,19 +294,87 @@ export class JobManager {
193
294
  }
194
295
 
195
296
  private async write(job: JobRecord): Promise<void> {
196
- await fs.mkdir(this.dir, { recursive: true });
197
- const temp = `${job.statusPath}.${process.pid}.tmp`;
297
+ await this.ensureDir();
298
+ // A random, exclusive-create temp name prevents a pre-planted symlink from
299
+ // redirecting the status write (the job id and pid alone are predictable).
300
+ const temp = `${job.statusPath}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
301
+ // Keep sensitive runtime data (raw errors, absolute status path) out of the
302
+ // on-disk file; the owner still gets the rich snapshot from fs.job.
198
303
  const payload = {
199
- ...snapshot(job),
304
+ id: job.id,
305
+ tool: job.tool,
306
+ state: job.state,
307
+ startedAt: job.startedAt,
308
+ ...(job.finishedAt === undefined ? {} : { finishedAt: job.finishedAt }),
200
309
  ...(job.result ? { hasResult: true } : {}),
201
310
  };
202
- await fs.writeFile(temp, `${JSON.stringify(payload)}\n`, "utf8");
311
+ await fs.writeFile(temp, `${JSON.stringify(payload)}\n`, {
312
+ encoding: "utf8",
313
+ mode: 0o600,
314
+ flag: "wx",
315
+ });
316
+ await fs.chmod(temp, 0o600);
203
317
  await fs.rename(temp, job.statusPath);
204
318
  }
205
319
 
206
- private require(id: string): JobRecord {
320
+ /**
321
+ * Create or validate the status directory without following a pre-existing
322
+ * symlink anywhere in the configured path. A caller-supplied ordinary nested
323
+ * directory keeps working; any symlink, non-directory, root, or inaccessible
324
+ * component fails before a chmod or write. A resolve/check-to-syscall race
325
+ * remains possible, so this is a guardrail, not a kernel boundary.
326
+ */
327
+ private async ensureDir(): Promise<void> {
328
+ const absolute = path.resolve(this.dir);
329
+ const root = path.parse(absolute).root;
330
+ if (absolute === root) {
331
+ throw new FsError(`job directory must not be the filesystem root: ${absolute}`, "invalid");
332
+ }
333
+
334
+ let current = root;
335
+ let missing = false;
336
+ for (const part of path.relative(root, absolute).split(path.sep)) {
337
+ current = path.join(current, part);
338
+ if (missing) continue;
339
+ let stats: Awaited<ReturnType<typeof fs.lstat>>;
340
+ try {
341
+ stats = await fs.lstat(current);
342
+ } catch (error) {
343
+ /* v8 ignore next -- a non-missing lstat error is an OS access failure */
344
+ if (!isMissing(error)) throw fromErrno(error, "access");
345
+ missing = true;
346
+ continue;
347
+ }
348
+ if (stats.isSymbolicLink()) {
349
+ throw new FsError(`job directory must not contain a symbolic link: ${current}`, "invalid");
350
+ }
351
+ if (!stats.isDirectory()) {
352
+ throw new FsError(`job directory component is not a directory: ${current}`, "not-directory");
353
+ }
354
+ }
355
+
356
+ if (missing) await fs.mkdir(absolute, { recursive: true, mode: 0o700 });
357
+ await fs.chmod(absolute, 0o700);
358
+ }
359
+
360
+ private boundResult(result: RenderedResult): RenderedResult {
361
+ const bytes = Buffer.byteLength(result.content, "utf8");
362
+ if (bytes <= this.maxResultBytes) return result;
363
+ const metadata = { ...result.metadata, truncated: true, originalBytes: bytes };
364
+ if (result.metadata.encoding === "base64") {
365
+ return { content: "", metadata };
366
+ }
367
+ const limit = Math.max(0, this.maxResultBytes - Buffer.byteLength(TRUNCATION_MARKER, "utf8"));
368
+ return { content: `${truncateUtf8(result.content, limit)}${TRUNCATION_MARKER}`, metadata };
369
+ }
370
+
371
+ private require(id: string, owner: string = LOCAL_OWNER): JobRecord {
207
372
  const job = this.jobs.get(id);
208
- if (!job) throw new FsError(`job not found: ${id}`, "not-found");
373
+ if (job === undefined || job.owner !== owner) {
374
+ // Deliberately identical for missing and foreign jobs: a caller without
375
+ // the owner token must not learn that another session's id exists.
376
+ throw new FsError(`job not found: ${id}`, "not-found");
377
+ }
209
378
  return job;
210
379
  }
211
380
 
@@ -215,3 +384,10 @@ export class JobManager {
215
384
  return count;
216
385
  }
217
386
  }
387
+
388
+ function truncateUtf8(text: string, maxBytes: number): string {
389
+ const bytes = Buffer.from(text, "utf8");
390
+ let end = Math.min(bytes.length, maxBytes);
391
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
392
+ return bytes.subarray(0, end).toString("utf8");
393
+ }
@@ -46,17 +46,39 @@ export class PermissionGate {
46
46
  private readonly assertPermission: PermissionAssert,
47
47
  ) {}
48
48
 
49
- /** Assert an action on trusted tool-owned paths without an external gate. */
49
+ /**
50
+ * Assert an action on trusted tool-owned paths without an external gate.
51
+ * An empty list is a deliberate wildcard request; any other list saves its
52
+ * exact resources, so "allow always" never widens a specific host or path to
53
+ * every resource of the action.
54
+ */
50
55
  async assertTrusted(resources: readonly string[]): Promise<void> {
51
- await this.assertAction(resources.length === 0 ? ["*"] : [...resources], ["*"]);
56
+ await this.assertAction(resources.length === 0 ? ["*"] : [...resources]);
52
57
  }
53
58
 
54
59
  async assert(entries: readonly PermissionEntry[]): Promise<void> {
55
60
  if (entries.length === 0) {
56
- await this.assertAction(["*"], ["*"]);
61
+ await this.assertAction(["*"]);
57
62
  return;
58
63
  }
59
64
 
65
+ await this.assertExternal(entries);
66
+
67
+ const resources = unique(
68
+ entries.map((entry) =>
69
+ entry.target.outside
70
+ ? slash(entry.target.full)
71
+ : (entry.resource ?? this.sandboxResource(entry.target.full)),
72
+ ),
73
+ );
74
+ await this.assertAction(resources);
75
+ }
76
+
77
+ /**
78
+ * Assert only the external_directory boundary for targets outside the
79
+ * project, without asserting this gate's action on their paths.
80
+ */
81
+ async assertExternal(entries: readonly PermissionEntry[]): Promise<void> {
60
82
  const external = entries.filter((entry) => entry.target.outside);
61
83
  const boundaries = new Map<string, string[]>();
62
84
  for (const entry of external) {
@@ -75,23 +97,19 @@ export class PermissionGate {
75
97
  save: repoRoots.map((root) => `${slash(root)}/*`),
76
98
  });
77
99
  }
78
-
79
- const resources = unique(
80
- entries.map((entry) =>
81
- entry.target.outside
82
- ? slash(entry.target.full)
83
- : (entry.resource ?? this.sandboxResource(entry.target.full)),
84
- ),
85
- );
86
- await this.assertAction(resources, ["*"]);
87
100
  }
88
101
 
89
- private async assertAction(resources: string[], save: string[]): Promise<void> {
102
+ /**
103
+ * `save` mirrors the asserted resources so a persisted "allow always" rule
104
+ * stays as narrow as the request. The only wildcard is the explicit `*` the
105
+ * caller asked for (an empty-call default or a supplied wildcard).
106
+ */
107
+ private async assertAction(resources: string[]): Promise<void> {
90
108
  await this.assertPermission({
91
109
  ...this.base(),
92
110
  action: this.action,
93
111
  resources,
94
- save,
112
+ save: [...resources],
95
113
  });
96
114
  }
97
115