@eum-agent/file-explorer 1.1.0 → 1.2.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/dist/index.js CHANGED
@@ -1,18 +1,15 @@
1
- import { AccessErrorSchema, FileBytesParamsSchema, FileEntrySchema, FileTargetSchema, FilesChangedSchema, ListParamsSchema, ListResultSchema, MkdirParamsSchema, MoveFilesParamsSchema, MoveFilesResultSchema, OperationResultSchema, OperationStatusesParamsSchema, OperationStatusesResultSchema, PathSchema, RemoveFilesParamsSchema, RemoveFilesResultSchema, RenameParamsSchema, RootsParamsSchema, RootsResultSchema, SegmentSchema, StatsParamsSchema, StatsResultSchema } from "./schema.js";
1
+ import { AccessErrorSchema, FileBytesParamsSchema, FileEntrySchema, FileTargetSchema, FilesChangedSchema, ListParamsSchema, ListResultSchema, MkdirParamsSchema, MoveFilesParamsSchema, MoveFilesResultSchema, OperationResultSchema, OperationStatusesParamsSchema, OperationStatusesResultSchema, PathSchema, RemoveFilesParamsSchema, RemoveFilesResultSchema, RenameParamsSchema, RootsParamsSchema, RootsResultSchema, SegmentSchema as SegmentSchema$1, StatsParamsSchema, StatsResultSchema } from "./schema.js";
2
+ import nodePath, { dirname, join } from "node:path";
2
3
  import { existsSync } from "node:fs";
3
4
  import { fileURLToPath } from "node:url";
4
- import { randomUUID } from "node:crypto";
5
- import nodePath, { join } from "node:path";
5
+ import { z } from "zod";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import ignore from "ignore";
6
8
  //#region src/errors.ts
7
- /** Bounded extension errors safe for transport and operation records. */
8
- var FileAccessError = class extends Error {
9
- /** Stable business code, never raw host exception text. */
9
+ var FileAccessError$1 = class extends Error {
10
10
  code;
11
- /** HTTP status used by the generic resource boundary. */
12
11
  status;
13
- /** Context validated by the provider's ErrorDetailsSchema before publication. */
14
12
  details;
15
- /** Carries a business code and JSON context without raw host exceptions or content. */
16
13
  constructor(code, status, details) {
17
14
  super(`File access failed: ${code}`);
18
15
  this.name = "FileAccessError";
@@ -21,10 +18,9 @@ var FileAccessError = class extends Error {
21
18
  this.details = details;
22
19
  }
23
20
  };
24
- /** Preserves known business errors and maps host failures without exposing paths or file bytes. */
25
- function accessError(error) {
26
- if (error instanceof FileAccessError) return error;
27
- if (error instanceof Error && error.name === "AbortError") return new FileAccessError("unavailable", 503);
21
+ function accessError$1(error) {
22
+ if (error instanceof FileAccessError$1) return error;
23
+ if (error instanceof Error && error.name === "AbortError") return new FileAccessError$1("unavailable", 503);
28
24
  const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
29
25
  const business = {
30
26
  ENOENT: "missing",
@@ -47,12 +43,11 @@ function accessError(error) {
47
43
  "unsupported-type": 415,
48
44
  "unsupported-platform": 503
49
45
  };
50
- return new FileAccessError(business in status ? business : "io-failed", status[business] ?? 500);
46
+ return new FileAccessError$1(business in status ? business : "io-failed", status[business] ?? 500);
51
47
  }
52
48
  //#endregion
53
49
  //#region src/batches.ts
54
50
  const encoded = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
55
- /** Runs independent members with owner cancellation and complete serialized-member limits. */
56
51
  async function fileCollection(items, signal, work, maxItemBytes = Math.floor(8380416 / items.length)) {
57
52
  const results = [];
58
53
  for (const [index, target] of items.entries()) {
@@ -66,11 +61,11 @@ async function fileCollection(items, signal, work, maxItemBytes = Math.floor(838
66
61
  ok: true,
67
62
  value
68
63
  };
69
- if (encoded(member) > maxItemBytes) throw new FileAccessError("read-limit", 413);
64
+ if (encoded(member) > maxItemBytes) throw new FileAccessError$1("read-limit", 413);
70
65
  results.push(member);
71
66
  } catch (error) {
72
67
  signal.throwIfAborted();
73
- const failure = accessError(error);
68
+ const failure = accessError$1(error);
74
69
  results.push({
75
70
  index,
76
71
  target,
@@ -85,111 +80,251 @@ async function fileCollection(items, signal, work, maxItemBytes = Math.floor(838
85
80
  return { results };
86
81
  }
87
82
  //#endregion
88
- //#region src/listings.ts
89
- /** Owner-local bounded immutable directory snapshots and opaque page cursors. */
90
- /** Keeps at most eight sixty-second snapshots; every page still revalidates current scope. */
91
- var Listings = class {
92
- scope;
93
- now;
94
- snapshots = /* @__PURE__ */ new Map();
95
- /** Shares the provider's scope and clock without retaining host descriptors. */
96
- constructor(scope, now) {
97
- this.scope = scope;
98
- this.now = now;
83
+ //#region src/references/errors.ts
84
+ var FileAccessError = class extends Error {
85
+ code;
86
+ status;
87
+ details;
88
+ constructor(code, status, details) {
89
+ super(`File access failed: ${code}`);
90
+ this.name = "FileAccessError";
91
+ this.code = code;
92
+ this.status = status;
93
+ this.details = details;
99
94
  }
100
- /** Returns a 200-entry page of one immutable generation or refuses an expired/cross-target cursor. */
101
- async list(params, signal) {
102
- const selection = await this.scope.select(params.target, signal);
103
- try {
104
- const directory = selection.name ? await selection.parent.openDirectory([selection.name]) : selection.parent;
105
- const current = this.scope.fingerprint(await directory.stat());
106
- const now = this.now();
107
- for (const [id, snapshot] of this.snapshots) if (now - snapshot.snapshotAt >= 6e4) this.snapshots.delete(id);
108
- let snapshot;
109
- let offset = 0;
110
- if (params.cursor !== void 0) {
111
- for (const candidate of this.snapshots.values()) for (const [position, cursor] of candidate.cursors) if (cursor === params.cursor) {
112
- snapshot = candidate;
113
- offset = position;
114
- }
115
- if (!snapshot || snapshot.target !== JSON.stringify(params.target)) throw new FileAccessError("stale-cursor", 409);
116
- } else {
117
- const observed = await directory.list(1e4);
118
- const entries = [];
119
- for (const item of observed) {
120
- const path = [params.target.path, item.name].filter(Boolean).join("/");
121
- if (item.observation.kind === "symlink") {
122
- const linked = await this.scope.select({
123
- ...params.target,
124
- path
125
- }, signal);
126
- try {
127
- entries.push(this.scope.entry(linked));
128
- } finally {
129
- await linked.close();
130
- }
131
- } else entries.push(this.scope.entry({
132
- ...selection,
133
- parent: directory,
134
- name: item.name,
135
- path: join(directory.path, item.name),
136
- effectivePath: join(directory.path, item.name),
137
- target: {
138
- ...params.target,
139
- path
140
- },
141
- observation: item.observation
142
- }));
95
+ };
96
+ function accessError(error) {
97
+ if (error instanceof FileAccessError) return error;
98
+ if (error instanceof Error && error.name === "AbortError") return new FileAccessError("unavailable", 503);
99
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
100
+ const business = {
101
+ ENOENT: "missing",
102
+ EEXIST: "exists",
103
+ EACCES: "io-failed",
104
+ EPERM: "io-failed",
105
+ EXDEV: "cross-device",
106
+ "too-large": "too-large-directory"
107
+ }[code] ?? code;
108
+ const status = {
109
+ "not-found": 404,
110
+ "not-regular-file": 415,
111
+ "os-permission-denied": 403,
112
+ "deadline-exceeded": 503,
113
+ cancelled: 503,
114
+ "invalid-range": 416,
115
+ missing: 404,
116
+ exists: 409,
117
+ stale: 409,
118
+ sealed: 403,
119
+ "outside-root": 403,
120
+ "cross-device": 409,
121
+ unavailable: 503,
122
+ "too-large-directory": 413,
123
+ "unsupported-name": 415,
124
+ "unsupported-type": 415,
125
+ "unsupported-platform": 503
126
+ };
127
+ return new FileAccessError(business in status ? business : "io-failed", status[business] ?? 500);
128
+ }
129
+ //#endregion
130
+ //#region src/references/native-path.ts
131
+ function checkPathText(value) {
132
+ if (!value || /[\uD800-\uDFFF]/u.test(value) || /[\x00-\x1f\x7f]/.test(value)) throw new FileAccessError("invalid-path", 400);
133
+ if (new TextEncoder().encode(value).length > 131072) throw new FileAccessError("too-large", 413);
134
+ }
135
+ function windowsRoot(path) {
136
+ return /^(?:\\\\\?\\)?[a-z]:[\\/]/i.exec(path)?.[0] ?? /^(?:\\\\\?\\UNC\\|\\\\)[^\\/:<>"|?*]+[\\/][^\\/:<>"|?*]+(?:[\\/]|$)/i.exec(path)?.[0];
137
+ }
138
+ function nativeAbsolute(path, style, base) {
139
+ checkPathText(path);
140
+ if (/^[a-z]:($|[^\\/])/i.test(path)) throw new FileAccessError("ambiguous-path", 400);
141
+ if (style === "posix") {
142
+ if (/^[a-z]:[\\/]/i.test(path) || path.startsWith("\\\\")) throw new FileAccessError("platform-mismatch", 400);
143
+ if (path.startsWith("/")) return path;
144
+ if (!base?.startsWith("/")) throw new FileAccessError("origin-unavailable", 409);
145
+ const absolute = `${base}${base.endsWith("/") ? "" : "/"}${path}`;
146
+ checkPathText(absolute);
147
+ return absolute;
148
+ }
149
+ if (path.startsWith("\\\\?\\") && !/^\\\\\?\\(?:[a-z]:\\|UNC\\[^\\]+\\[^\\]+)/i.test(path)) throw new FileAccessError("unsupported-path", 400);
150
+ const root = windowsRoot(path);
151
+ if (path.startsWith("\\\\") && (!root || path.startsWith("\\\\.\\"))) throw new FileAccessError("unsupported-path", 400);
152
+ if (/[<>:"|?*]/.test(root ? path.slice(root.length) : path)) throw new FileAccessError("unsupported-path", 400);
153
+ if (root) return path;
154
+ const baseRoot = base && windowsRoot(base);
155
+ if (!base || !baseRoot) throw new FileAccessError("origin-unavailable", 409);
156
+ const absolute = /^[\\/]/.test(path) ? `${baseRoot.replace(/[\\/]$/, "")}\\${path.slice(1)}` : `${base}${/[\\/]$/.test(base) ? "" : "\\"}${path}`;
157
+ checkPathText(absolute);
158
+ return absolute;
159
+ }
160
+ function assertAbsolute(path, style) {
161
+ return nativeAbsolute(path, style);
162
+ }
163
+ function nativeParent(path, style) {
164
+ assertAbsolute(path, style);
165
+ const end = style === "posix" ? path.lastIndexOf("/") : Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
166
+ const rootLength = style === "posix" ? 1 : windowsRoot(path).length;
167
+ return path.slice(0, Math.max(end, rootLength));
168
+ }
169
+ const IdentitySchema = z.string().min(1).max(1024).refine((value) => value !== "." && value !== ".." && [...value].every((character) => character !== "/" && character !== "\\" && character.charCodeAt(0) > 31 && character.charCodeAt(0) !== 127), "Invalid segment");
170
+ const GatewayIdSchema = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
171
+ const DigestSchema = z.string().regex(/^[0-9a-f]{64}$/);
172
+ const AttachmentParamsSchema = z.object({
173
+ workspaceId: IdentitySchema,
174
+ sessionId: IdentitySchema,
175
+ fileId: DigestSchema
176
+ }).strict();
177
+ const AttachmentMetadataSchema = z.object({
178
+ referenceKind: z.literal("attachment"),
179
+ uri: z.string(),
180
+ fileId: DigestSchema,
181
+ name: z.string().min(1).max(200),
182
+ mediaType: z.string().min(1).max(256),
183
+ size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
184
+ width: z.number().int().positive().optional(),
185
+ height: z.number().int().positive().optional()
186
+ }).strict();
187
+ z.discriminatedUnion("kind", [z.object({
188
+ kind: z.literal("current"),
189
+ gatewayId: GatewayIdSchema,
190
+ target: z.strictObject({
191
+ pathStyle: z.enum(["posix", "windows"]),
192
+ absolutePath: z.string()
193
+ })
194
+ }).strict(), z.object({
195
+ kind: z.literal("attachment"),
196
+ gatewayId: GatewayIdSchema,
197
+ reference: AttachmentParamsSchema
198
+ }).strict()]);
199
+ const GatewayFileMetadataSchema = z.strictObject({
200
+ referenceKind: z.literal("current"),
201
+ uri: z.string(),
202
+ gatewayId: GatewayIdSchema,
203
+ pathStyle: z.enum(["posix", "windows"]),
204
+ absolutePath: z.string(),
205
+ resolvedPath: z.string().optional(),
206
+ name: z.string(),
207
+ mediaType: z.string(),
208
+ size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
209
+ fingerprint: DigestSchema
210
+ });
211
+ //#endregion
212
+ //#region src/references/uri.ts
213
+ function parseReference(uri, gatewayId) {
214
+ try {
215
+ const identity = uri.split("#", 1)[0];
216
+ const match = /^gfs:\/\/([^/]+)\/([^?#]*)$/.exec(identity);
217
+ if (!match || !GatewayIdSchema.safeParse(match[1]).success) throw new Error("invalid");
218
+ if (match[1] !== gatewayId) throw new FileAccessError("gateway-mismatch", 403);
219
+ const parts = match[2].split("/").map((value) => {
220
+ const decoded = decodeURIComponent(value);
221
+ if (encodeURIComponent(decoded) !== value) throw new Error("noncanonical reference");
222
+ return decoded;
223
+ });
224
+ if (parts[0] === "file" && parts.length === 3 && (parts[1] === "posix" || parts[1] === "windows")) {
225
+ const pathStyle = parts[1];
226
+ return {
227
+ kind: "current",
228
+ gatewayId,
229
+ target: {
230
+ pathStyle,
231
+ absolutePath: assertAbsolute(parts[2], pathStyle)
143
232
  }
144
- if (this.scope.fingerprint(await directory.stat()) !== current) throw new FileAccessError("stale", 409);
145
- const order = {
146
- directory: 0,
147
- file: 1,
148
- symlink: 2,
149
- other: 3
150
- };
151
- entries.sort((a, b) => order[a.kind] - order[b.kind] || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
152
- if (this.snapshots.size === 8) this.snapshots.delete(this.snapshots.keys().next().value);
153
- snapshot = {
154
- target: JSON.stringify(params.target),
155
- entries,
156
- listingId: randomUUID(),
157
- snapshotAt: now,
158
- fingerprint: current,
159
- cursors: /* @__PURE__ */ new Map()
160
- };
161
- this.snapshots.set(snapshot.listingId, snapshot);
233
+ };
234
+ }
235
+ if (parts[0] === "attachment" && parts.length === 4) return {
236
+ kind: "attachment",
237
+ gatewayId,
238
+ reference: AttachmentParamsSchema.parse({
239
+ workspaceId: parts[1],
240
+ sessionId: parts[2],
241
+ fileId: parts[3]
242
+ })
243
+ };
244
+ throw new Error("invalid branch");
245
+ } catch (error) {
246
+ if (error instanceof FileAccessError) throw error;
247
+ throw new FileAccessError("invalid-reference", 400);
248
+ }
249
+ }
250
+ function currentReference(gatewayId, pathStyle, absolutePath) {
251
+ GatewayIdSchema.parse(gatewayId);
252
+ assertAbsolute(absolutePath, pathStyle);
253
+ return `gfs://${gatewayId}/file/${pathStyle}/${encodeURIComponent(absolutePath)}`;
254
+ }
255
+ function attachmentReference(gatewayId, reference) {
256
+ GatewayIdSchema.parse(gatewayId);
257
+ AttachmentParamsSchema.parse(reference);
258
+ return `gfs://${gatewayId}/attachment/${[
259
+ reference.workspaceId,
260
+ reference.sessionId,
261
+ reference.fileId
262
+ ].map(encodeURIComponent).join("/")}`;
263
+ }
264
+ //#endregion
265
+ //#region src/observe.ts
266
+ const ObserveParamsSchema = z.strictObject({ items: z.array(z.strictObject({
267
+ uri: z.string().max(393400),
268
+ fingerprint: z.string().regex(/^[0-9a-f]{64}$/)
269
+ })).min(1).max(64) });
270
+ const ObserveResultSchema = z.strictObject({ items: z.array(z.discriminatedUnion("status", [
271
+ z.strictObject({ status: z.literal("same") }),
272
+ z.strictObject({
273
+ status: z.literal("changed"),
274
+ fingerprint: z.string().regex(/^[0-9a-f]{64}$/)
275
+ }),
276
+ z.strictObject({ status: z.literal("missing") }),
277
+ z.strictObject({
278
+ status: z.literal("error"),
279
+ code: z.string()
280
+ })
281
+ ])).min(1).max(64) });
282
+ async function observeReferences(reader, formatter, gatewayId, input, signal) {
283
+ const deadline = new AbortController();
284
+ const timer = setTimeout(() => deadline.abort(), 5e3);
285
+ const combined = AbortSignal.any([signal, deadline.signal]);
286
+ const items = [];
287
+ try {
288
+ for (const item of input.items) try {
289
+ const reference = parseReference(item.uri, gatewayId);
290
+ if (reference.kind === "attachment") {
291
+ items.push({ status: "same" });
292
+ continue;
162
293
  }
163
- await selection.current();
164
- const next = offset + 200;
165
- let nextCursor;
166
- if (next < snapshot.entries.length) {
167
- nextCursor = snapshot.cursors.get(next) ?? randomUUID();
168
- snapshot.cursors.set(next, nextCursor);
294
+ if (reference.target.pathStyle !== reader.pathStyle) {
295
+ items.push({
296
+ status: "error",
297
+ code: "platform-mismatch"
298
+ });
299
+ continue;
169
300
  }
170
- return {
171
- entries: snapshot.entries.slice(offset, next),
172
- nextCursor,
173
- fingerprint: snapshot.fingerprint,
174
- listingId: snapshot.listingId,
175
- snapshotAt: snapshot.snapshotAt,
176
- stale: snapshot.fingerprint !== current
177
- };
301
+ combined.throwIfAborted();
302
+ let cancel = () => {};
303
+ const cancelled = new Promise((_resolve, reject) => {
304
+ cancel = () => reject(combined.reason);
305
+ combined.addEventListener("abort", cancel, { once: true });
306
+ });
307
+ const observation = await Promise.race([Promise.resolve().then(() => reader.observe(reference.target.absolutePath, combined)), cancelled]).finally(() => combined.removeEventListener("abort", cancel));
308
+ combined.throwIfAborted();
309
+ const fingerprint = formatter.fingerprint(observation);
310
+ items.push(fingerprint === item.fingerprint ? { status: "same" } : {
311
+ status: "changed",
312
+ fingerprint
313
+ });
178
314
  } catch (error) {
179
- throw accessError(error);
180
- } finally {
181
- await selection.close();
315
+ const code = deadline.signal.aborted ? "deadline-exceeded" : accessError(error).code;
316
+ items.push(code === "not-found" || code === "missing" ? { status: "missing" } : {
317
+ status: "error",
318
+ code
319
+ });
182
320
  }
321
+ return { items };
322
+ } finally {
323
+ clearTimeout(timer);
183
324
  }
184
- /** Releases in-memory generations on owner shutdown. */
185
- close() {
186
- this.snapshots.clear();
187
- }
188
- };
325
+ }
189
326
  //#endregion
190
327
  //#region src/path-semantics.ts
191
- /** Host path syntax only; resolved object identity remains the platform's responsibility. */
192
- /** Requires an independent absolute root, excluding Windows drive-relative and root-relative forms. */
193
328
  function isFullAbsolute(value, paths = nodePath) {
194
329
  if (value.includes("\0") || !paths.isAbsolute(value)) return false;
195
330
  if (paths.sep !== "\\") return true;
@@ -203,7 +338,6 @@ function isFullAbsolute(value, paths = nodePath) {
203
338
  "?"
204
339
  ].includes(server) && ![".", ".."].includes(share);
205
340
  }
206
- /** Compares canonical ancestor segments exactly; drive-letter syntax alone is case-insensitive. */
207
341
  function containsHostPath(root, value, paths = nodePath) {
208
342
  if (!isFullAbsolute(root, paths) || !isFullAbsolute(value, paths)) return false;
209
343
  const parts = (path) => {
@@ -218,32 +352,25 @@ function containsHostPath(root, value, paths = nodePath) {
218
352
  const child = parts(value);
219
353
  return parent.root === child.root && parent.segments.length <= child.segments.length && parent.segments.every((segment, index) => segment === child.segments[index]);
220
354
  }
221
- /** Converts a contained host path to validated wire segments without changing filename content. */
222
355
  function toWirePath(root, value, paths = nodePath) {
223
- if (!containsHostPath(root, value, paths)) throw new FileAccessError("outside-root", 403);
356
+ if (!containsHostPath(root, value, paths)) throw new FileAccessError$1("outside-root", 403);
224
357
  const relative = paths.relative(root, value);
225
358
  const wire = relative === "" ? "" : relative.split(paths.sep).join("/");
226
- if (!PathSchema.safeParse(wire).success) throw new FileAccessError("outside-root", 403);
359
+ if (!PathSchema.safeParse(wire).success) throw new FileAccessError$1("outside-root", 403);
227
360
  return wire;
228
361
  }
229
362
  //#endregion
230
363
  //#region src/scope.ts
231
- /** Revalidates explicit workspace scope while all data/namespace operations remain anchored. */
232
- /** Tests lexical containment of canonical host paths, retaining exact object segment case. */
233
364
  function contains(parent, child, paths = nodePath) {
234
365
  return containsHostPath(parent, child, paths);
235
366
  }
236
- /** Current root and managed-media policy, deliberately independent of Agent approvals. */
237
367
  var FileScope = class {
238
368
  roots;
239
369
  files;
240
370
  signal;
241
371
  instanceId;
242
- /** Consistent host path operations throughout selection, links and mutations. */
243
372
  referenceFormatter;
244
- /** Host path operations retain exact observed segment spelling. */
245
373
  paths;
246
- /** Binds this policy to one owner and Gateway startup. */
247
374
  constructor(roots, files, signal, instanceId, paths = nodePath, referenceFormatter) {
248
375
  this.roots = roots;
249
376
  this.files = files;
@@ -252,37 +379,34 @@ var FileScope = class {
252
379
  this.paths = paths;
253
380
  this.referenceFormatter = referenceFormatter;
254
381
  }
255
- /** Uses the reader owner's sole reference revision semantics for ordinary files and links. */
256
382
  fingerprint(observation, referent) {
257
- if (!this.referenceFormatter) throw new FileAccessError("unavailable", 503);
383
+ if (!this.referenceFormatter) throw new FileAccessError$1("unavailable", 503);
258
384
  return this.referenceFormatter.fingerprint(observation, referent);
259
385
  }
260
- /** Returns a current explicit snapshot, refusing unavailable/mismatched startup identity. */
261
386
  async snapshot(workspaceId, request) {
262
387
  try {
263
388
  this.signal.throwIfAborted();
264
389
  request?.throwIfAborted();
265
- if (!this.roots.availability().available || !this.files.availability().available) throw new FileAccessError("unavailable", 503);
390
+ if (!this.roots.availability().available || !this.files.availability().available) throw new FileAccessError$1("unavailable", 503);
266
391
  const snapshot = await this.roots.read(workspaceId);
267
392
  this.signal.throwIfAborted();
268
393
  request?.throwIfAborted();
269
394
  snapshot.signal.throwIfAborted();
270
- if (snapshot.instanceId !== this.instanceId) throw new FileAccessError("instance-mismatch", 409);
395
+ if (snapshot.instanceId !== this.instanceId) throw new FileAccessError$1("instance-mismatch", 409);
271
396
  await snapshot.assertCurrent();
272
397
  this.signal.throwIfAborted();
273
398
  request?.throwIfAborted();
274
399
  snapshot.signal.throwIfAborted();
275
400
  return snapshot;
276
401
  } catch (error) {
277
- throw accessError(error);
402
+ throw accessError$1(error);
278
403
  }
279
404
  }
280
- /** Pins a parent and observes the literal final entry; missing final entries may be admitted for writes. */
281
405
  async select(target, request, missing = false) {
282
406
  FileTargetSchema.parse(target);
283
407
  const snapshot = await this.snapshot(target.workspaceId, request);
284
408
  const selected = snapshot.roots.find((root) => root.id === target.rootId);
285
- if (!selected) throw new FileAccessError("missing", 404);
409
+ if (!selected) throw new FileAccessError$1("missing", 404);
286
410
  const signal = AbortSignal.any([
287
411
  this.signal,
288
412
  snapshot.signal,
@@ -306,13 +430,13 @@ var FileScope = class {
306
430
  referent = entry.referent;
307
431
  } else observation = await parent.stat();
308
432
  } catch (error) {
309
- if (!missing || accessError(error).code !== "missing") throw error;
433
+ if (!missing || accessError$1(error).code !== "missing") throw error;
310
434
  }
311
435
  const path = name ? this.paths.join(parent.path, name) : parent.path;
312
436
  let effectivePath = path;
313
437
  let referentObservation;
314
438
  if (observation?.kind === "symlink") {
315
- if (!referent) throw new FileAccessError("outside-root", 403);
439
+ if (!referent) throw new FileAccessError$1("outside-root", 403);
316
440
  effectivePath = referent.path;
317
441
  referentObservation = referent.observation;
318
442
  }
@@ -338,21 +462,19 @@ var FileScope = class {
338
462
  };
339
463
  } catch (error) {
340
464
  await root.close();
341
- throw accessError(error);
465
+ throw accessError$1(error);
342
466
  }
343
467
  }
344
- /** Protects managed media itself, descendants, aliases and ancestors affected by mutation. */
345
468
  mutation(selection) {
346
- if (!selection.name) throw new FileAccessError("outside-root", 403);
347
- for (const sealed of selection.snapshot.sealedDirectories) for (const path of [selection.path, selection.effectivePath]) if (contains(path, sealed, this.paths) || contains(sealed, path, this.paths)) throw new FileAccessError("sealed", 403);
348
- for (const protectedPath of selection.snapshot.protectedDirectories) for (const path of [selection.path, selection.effectivePath]) if (contains(protectedPath, path, this.paths) || contains(path, protectedPath, this.paths)) throw new FileAccessError("managed-storage", 403);
469
+ if (!selection.name) throw new FileAccessError$1("outside-root", 403);
470
+ for (const sealed of selection.snapshot.sealedDirectories) for (const path of [selection.path, selection.effectivePath]) if (contains(path, sealed, this.paths) || contains(sealed, path, this.paths)) throw new FileAccessError$1("sealed", 403);
471
+ for (const protectedPath of selection.snapshot.protectedDirectories) for (const path of [selection.path, selection.effectivePath]) if (contains(protectedPath, path, this.paths) || contains(path, protectedPath, this.paths)) throw new FileAccessError$1("managed-storage", 403);
349
472
  }
350
- /** Keeps literal link kind/size while fingerprinting both its revision and selected referent. */
351
473
  entry(selection, observation = selection.observation) {
352
- if (!observation) throw new FileAccessError("missing", 404);
353
- if (selection.name && !SegmentSchema.safeParse(selection.name).success) throw new FileAccessError("unsupported-name", 415);
474
+ if (!observation) throw new FileAccessError$1("missing", 404);
475
+ if (selection.name && !SegmentSchema$1.safeParse(selection.name).success) throw new FileAccessError$1("unsupported-name", 415);
354
476
  const size = Number(observation.size);
355
- if (!Number.isSafeInteger(size)) throw new FileAccessError("too-large", 413);
477
+ if (!Number.isSafeInteger(size)) throw new FileAccessError$1("too-large", 413);
356
478
  let mutable = true;
357
479
  try {
358
480
  this.mutation(selection);
@@ -361,7 +483,7 @@ var FileScope = class {
361
483
  }
362
484
  const revision = this.fingerprint(observation, selection.referentObservation);
363
485
  const name = selection.name || selection.snapshot.roots.find((root) => root.id === selection.target.rootId)?.name;
364
- if (name === void 0) throw new FileAccessError("missing", 404);
486
+ if (name === void 0) throw new FileAccessError$1("missing", 404);
365
487
  return {
366
488
  name,
367
489
  path: selection.target.path,
@@ -380,10 +502,9 @@ var FileScope = class {
380
502
  pathStyle: this.paths.sep === "\\" ? "windows" : "posix",
381
503
  absolutePath: selection.path
382
504
  });
383
- if (!formatted) throw new FileAccessError("unavailable", 503);
505
+ if (!formatted) throw new FileAccessError$1("unavailable", 503);
384
506
  return formatted.uri;
385
507
  }
386
- /** Reobserves a published destination, resolving links at their new location. */
387
508
  async freshEntry(target, signal) {
388
509
  const selection = await this.select(target, signal);
389
510
  try {
@@ -394,18 +515,310 @@ var FileScope = class {
394
515
  }
395
516
  };
396
517
  //#endregion
518
+ //#region src/ignore.ts
519
+ var IgnoreRules = class {
520
+ cache = /* @__PURE__ */ new Map();
521
+ loading = Promise.resolve();
522
+ scope;
523
+ now;
524
+ constructor(scope, now = Date.now) {
525
+ this.scope = scope;
526
+ this.now = now;
527
+ }
528
+ load(selection, directoryPath) {
529
+ const cleanup = [];
530
+ const work = this.loading.then(() => this.loadRules(selection, directoryPath, cleanup));
531
+ this.loading = work.catch(() => {}).then(() => Promise.all(cleanup));
532
+ return work;
533
+ }
534
+ async loadRules(selection, directoryPath, cleanup) {
535
+ await selection.current();
536
+ const paths = this.scope.paths;
537
+ const rootPath = selection.root.path;
538
+ const directories = [];
539
+ for (let current = directoryPath; contains(rootPath, current, paths); current = paths.dirname(current)) {
540
+ directories.unshift(current);
541
+ if (current === rootPath) break;
542
+ }
543
+ const selectedRules = /* @__PURE__ */ new Map();
544
+ let degraded = false;
545
+ let missed = false;
546
+ const loadDirectory = async (directory) => {
547
+ const filename = paths.join(directory, ".gitignore");
548
+ const key = `${filename}\0${JSON.stringify(selection.snapshot.sealedDirectories)}`;
549
+ try {
550
+ const cached = this.cache.get(key);
551
+ if (cached && cached.expiresAt > this.now()) {
552
+ if (cached.fingerprint) selectedRules.set(directory, cached.matcher);
553
+ return;
554
+ }
555
+ missed = true;
556
+ let matcher;
557
+ const relative = paths.relative(rootPath, filename).split(paths.sep);
558
+ let file;
559
+ try {
560
+ const parentParts = relative.slice(0, -1);
561
+ const observation = await (parentParts.length ? await selection.root.openDirectory(parentParts) : selection.root).stat(".gitignore");
562
+ const fingerprint = this.scope.fingerprint(observation);
563
+ matcher = this.cache.get(key)?.fingerprint === fingerprint ? this.cache.get(key)?.matcher : void 0;
564
+ if (!matcher) {
565
+ if (observation.kind !== "file" || BigInt(observation.size) > 1048576n) throw new Error("Invalid ignore file");
566
+ file = await selection.root.openRead(relative);
567
+ const opened = await file.stat();
568
+ if (this.scope.fingerprint(opened) !== fingerprint) throw new Error("Ignore file changed");
569
+ const bytes = new Uint8Array(Number(opened.size));
570
+ let offset = 0;
571
+ while (offset < bytes.length) {
572
+ const chunk = await file.read(offset, bytes.length - offset);
573
+ if (!chunk.length) throw new Error("Ignore file changed");
574
+ bytes.set(chunk, offset);
575
+ offset += chunk.length;
576
+ }
577
+ if (this.scope.fingerprint(await file.stat()) !== fingerprint) throw new Error("Ignore file changed");
578
+ matcher = this.remember(key, fingerprint, new TextDecoder().decode(bytes));
579
+ }
580
+ } finally {
581
+ await file?.close();
582
+ }
583
+ if (matcher) {
584
+ const previous = this.cache.get(key);
585
+ if (previous) this.cache.set(key, {
586
+ ...previous,
587
+ expiresAt: this.now() + 2e3
588
+ });
589
+ selectedRules.set(directory, matcher);
590
+ }
591
+ } catch (error) {
592
+ if (error instanceof Error && "finished" in error && error.finished instanceof Promise) cleanup.push(error.finished);
593
+ const code = accessError(error).code;
594
+ if (code !== "missing" && code !== "not-found") degraded = true;
595
+ else this.remember(key, "", "");
596
+ }
597
+ };
598
+ let next = 0;
599
+ const workers = await Promise.allSettled(Array.from({ length: Math.min(4, directories.length) }, async () => {
600
+ while (next < directories.length) {
601
+ selection.signal.throwIfAborted();
602
+ await loadDirectory(directories[next++]);
603
+ }
604
+ }));
605
+ for (const worker of workers) if (worker.status === "rejected") throw worker.reason;
606
+ await selection.current();
607
+ const rules = directories.flatMap((directory) => {
608
+ const matcher = selectedRules.get(directory);
609
+ return matcher ? [{
610
+ directory,
611
+ matcher
612
+ }] : [];
613
+ });
614
+ const excluded = (candidate, isDirectory) => {
615
+ let excluded = false;
616
+ for (const rule of rules) {
617
+ const relative = paths.relative(rule.directory, candidate);
618
+ if (!relative || relative === ".." || relative.startsWith(`..${paths.sep}`) || paths.isAbsolute(relative)) continue;
619
+ const logical = relative.split(paths.sep).join("/") + (isDirectory ? "/" : "");
620
+ const verdict = rule.matcher.test(logical);
621
+ if (verdict.ignored) excluded = true;
622
+ else if (verdict.unignored) excluded = false;
623
+ }
624
+ return excluded;
625
+ };
626
+ const parentExcluded = directories.slice(1).some((directory) => excluded(directory, true));
627
+ const insideGit = directories.some((directory) => paths.basename(directory) === ".git");
628
+ return {
629
+ degraded,
630
+ cacheState: missed ? "miss" : "hit",
631
+ ignored: (name, isDirectory) => {
632
+ if (name === ".git" && isDirectory || insideGit || parentExcluded) return true;
633
+ if (!rules.length) return false;
634
+ return excluded(paths.join(directoryPath, name), isDirectory);
635
+ }
636
+ };
637
+ }
638
+ remember(path, fingerprint, content) {
639
+ const matcher = ignore({ ignorecase: false }).add(content);
640
+ const oldest = this.cache.keys().next().value;
641
+ if (this.cache.size >= 256 && oldest !== void 0) this.cache.delete(oldest);
642
+ this.cache.set(path, {
643
+ fingerprint,
644
+ matcher,
645
+ expiresAt: this.now() + 2e3
646
+ });
647
+ return matcher;
648
+ }
649
+ close() {
650
+ this.cache.clear();
651
+ }
652
+ };
653
+ //#endregion
654
+ //#region src/performance.ts
655
+ function startFileStage(observer, stage) {
656
+ try {
657
+ if (!observer || observer.enabled?.() === false) return () => {};
658
+ const started = observer.now();
659
+ return (outcome, facts) => {
660
+ try {
661
+ observer.observe({
662
+ stage,
663
+ monotonicStartMs: started,
664
+ durationMs: Math.max(0, observer.now() - started),
665
+ outcome,
666
+ ...facts
667
+ });
668
+ } catch {}
669
+ };
670
+ } catch {
671
+ return () => {};
672
+ }
673
+ }
674
+ function fileOutcome(error) {
675
+ const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
676
+ return code === "deadline-exceeded" ? "timeout" : code === "cancelled" || error instanceof Error && error.name === "AbortError" ? "cancelled" : "error";
677
+ }
678
+ async function observeFileStage(observer, stage, work, facts) {
679
+ const end = startFileStage(observer, stage);
680
+ try {
681
+ const value = await work();
682
+ end("ok", facts?.(value));
683
+ return value;
684
+ } catch (error) {
685
+ end(fileOutcome(error));
686
+ throw error;
687
+ }
688
+ }
689
+ //#endregion
690
+ //#region src/listings.ts
691
+ var Listings = class {
692
+ scope;
693
+ now;
694
+ rules;
695
+ performance;
696
+ snapshots = /* @__PURE__ */ new Map();
697
+ constructor(scope, now, performance) {
698
+ this.scope = scope;
699
+ this.now = now;
700
+ this.rules = new IgnoreRules(scope, now);
701
+ this.performance = performance;
702
+ }
703
+ async list(params, signal) {
704
+ const selection = await this.scope.select(params.target, signal);
705
+ try {
706
+ const directory = selection.name ? await selection.parent.openDirectory([selection.name]) : selection.parent;
707
+ const ignoredMode = params.ignored ?? "hide";
708
+ const current = this.scope.fingerprint(await directory.stat());
709
+ const now = this.now();
710
+ for (const [id, snapshot] of this.snapshots) if (now - snapshot.snapshotAt >= 6e4) this.snapshots.delete(id);
711
+ let snapshot;
712
+ let offset = 0;
713
+ if (params.cursor !== void 0) {
714
+ for (const candidate of this.snapshots.values()) for (const [position, cursor] of candidate.cursors) if (cursor === params.cursor) {
715
+ snapshot = candidate;
716
+ offset = position;
717
+ }
718
+ if (!snapshot || snapshot.target !== JSON.stringify(params.target) || snapshot.ignored !== ignoredMode) throw new FileAccessError$1("stale-cursor", 409);
719
+ } else {
720
+ const observed = await observeFileStage(this.performance, "file.enumerate", () => directory.list(1e4), (entries) => ({ count: entries.length }));
721
+ const rules = await observeFileStage(this.performance, "file.ignore", () => this.rules.load(selection, directory.path), (rules) => ({ cacheState: rules.cacheState }));
722
+ const entries = [];
723
+ const filtered = startFileStage(this.performance, "file.filter");
724
+ try {
725
+ for (const item of observed) {
726
+ const path = [params.target.path, item.name].filter(Boolean).join("/");
727
+ const ignored = rules.ignored(item.name, item.observation.kind === "directory");
728
+ if (ignored && ignoredMode === "hide") continue;
729
+ if (item.observation.kind === "symlink") {
730
+ const linked = await this.scope.select({
731
+ ...params.target,
732
+ path
733
+ }, signal);
734
+ try {
735
+ entries.push({
736
+ ...this.scope.entry(linked),
737
+ ignored
738
+ });
739
+ } finally {
740
+ await linked.close();
741
+ }
742
+ } else entries.push({
743
+ ...this.scope.entry({
744
+ ...selection,
745
+ parent: directory,
746
+ name: item.name,
747
+ path: join(directory.path, item.name),
748
+ effectivePath: join(directory.path, item.name),
749
+ target: {
750
+ ...params.target,
751
+ path
752
+ },
753
+ observation: item.observation
754
+ }),
755
+ ignored
756
+ });
757
+ }
758
+ filtered("ok", { count: entries.length });
759
+ } catch (error) {
760
+ filtered(fileOutcome(error));
761
+ throw error;
762
+ }
763
+ if (this.scope.fingerprint(await directory.stat()) !== current) throw new FileAccessError$1("stale", 409);
764
+ const order = {
765
+ directory: 0,
766
+ file: 1,
767
+ symlink: 2,
768
+ other: 3
769
+ };
770
+ const sorted = startFileStage(this.performance, "file.sort");
771
+ entries.sort((a, b) => order[a.kind] - order[b.kind] || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
772
+ sorted("ok", { count: entries.length });
773
+ if (this.snapshots.size === 8) this.snapshots.delete(this.snapshots.keys().next().value);
774
+ snapshot = {
775
+ target: JSON.stringify(params.target),
776
+ ignored: ignoredMode,
777
+ ignoreDegraded: rules.degraded,
778
+ entries,
779
+ listingId: randomUUID(),
780
+ snapshotAt: now,
781
+ fingerprint: current,
782
+ cursors: /* @__PURE__ */ new Map()
783
+ };
784
+ this.snapshots.set(snapshot.listingId, snapshot);
785
+ }
786
+ await selection.current();
787
+ const next = offset + 200;
788
+ let nextCursor;
789
+ if (next < snapshot.entries.length) {
790
+ nextCursor = snapshot.cursors.get(next) ?? randomUUID();
791
+ snapshot.cursors.set(next, nextCursor);
792
+ }
793
+ return {
794
+ entries: snapshot.entries.slice(offset, next),
795
+ nextCursor,
796
+ fingerprint: snapshot.fingerprint,
797
+ listingId: snapshot.listingId,
798
+ snapshotAt: snapshot.snapshotAt,
799
+ stale: snapshot.fingerprint !== current,
800
+ ignoreDegraded: snapshot.ignoreDegraded
801
+ };
802
+ } catch (error) {
803
+ throw accessError$1(error);
804
+ } finally {
805
+ await selection.close();
806
+ }
807
+ }
808
+ close() {
809
+ this.snapshots.clear();
810
+ this.rules.close();
811
+ }
812
+ };
813
+ //#endregion
397
814
  //#region src/locks.ts
398
- /** Atomic acquisition of ordered canonical path sets prevents opposing moves from deadlocking. */
399
- /** Serializes overlapping selected paths, including recursive ancestors. */
400
815
  var PathLocks = class {
401
- /** Binds lock overlap to the same host syntax as its selections. */
402
816
  constructor(paths = nodePath) {
403
817
  this.paths = paths;
404
818
  }
405
819
  paths;
406
820
  active = /* @__PURE__ */ new Set();
407
821
  waiting = [];
408
- /** Acquires all deduplicated paths in fixed order, refusing cancelled queued work. */
409
822
  acquire(paths, signal) {
410
823
  signal.throwIfAborted();
411
824
  return new Promise((resolve, reject) => {
@@ -418,7 +831,7 @@ var PathLocks = class {
418
831
  const aborted = () => {
419
832
  const index = this.waiting.indexOf(item);
420
833
  if (index >= 0) this.waiting.splice(index, 1);
421
- reject(new FileAccessError("unavailable", 503));
834
+ reject(new FileAccessError$1("unavailable", 503));
422
835
  this.wake();
423
836
  };
424
837
  signal.addEventListener("abort", aborted, { once: true });
@@ -450,12 +863,9 @@ var PathLocks = class {
450
863
  };
451
864
  //#endregion
452
865
  //#region src/mutations.ts
453
- /** Observed namespace operations serialized across canonical physical selections. */
454
- /** Compares object identity without treating an observation as permanent permission. */
455
866
  function sameObject(a, b) {
456
867
  return a.device === b.device && a.inode === b.inode;
457
868
  }
458
- /** Acquires all canonical targets atomically and rejects alias changes while waiting. */
459
869
  async function withSelections(scope, locks, targets, signal, work) {
460
870
  const preliminary = [];
461
871
  const selections = [];
@@ -474,7 +884,7 @@ async function withSelections(scope, locks, targets, signal, work) {
474
884
  for (const [index, target] of targets.entries()) {
475
885
  const selected = await scope.select(target, signal, true);
476
886
  selections.push(selected);
477
- if (selected.path !== preliminary[index]?.path || selected.effectivePath !== preliminary[index]?.effectivePath) throw new FileAccessError("stale", 409);
887
+ if (selected.path !== preliminary[index]?.path || selected.effectivePath !== preliminary[index]?.effectivePath) throw new FileAccessError$1("stale", 409);
478
888
  scope.mutation(selected);
479
889
  }
480
890
  return await work(selections);
@@ -486,11 +896,10 @@ async function withSelections(scope, locks, targets, signal, work) {
486
896
  }
487
897
  }
488
898
  }
489
- /** Rejects lexical containment and physical aliases/mount-root ancestry before any staging. */
490
899
  async function rejectOverlap(source, destination, paths = nodePath) {
491
900
  const observed = source.observation;
492
- if (!observed) throw new FileAccessError("missing", 404);
493
- if (source.path === destination.path || source.effectivePath === destination.effectivePath || destination.observation && sameObject(observed, destination.observation) || observed.kind === "directory" && contains(source.effectivePath, destination.effectivePath, paths) || destination.observation?.kind === "directory" && contains(destination.effectivePath, source.effectivePath, paths)) throw new FileAccessError("path-overlap", 409);
901
+ if (!observed) throw new FileAccessError$1("missing", 404);
902
+ if (source.path === destination.path || source.effectivePath === destination.effectivePath || destination.observation && sameObject(observed, destination.observation) || observed.kind === "directory" && contains(source.effectivePath, destination.effectivePath, paths) || destination.observation?.kind === "directory" && contains(destination.effectivePath, source.effectivePath, paths)) throw new FileAccessError$1("path-overlap", 409);
494
903
  const ancestorIncludes = async (selection, observation) => {
495
904
  const parts = paths.relative(selection.root.path, selection.parent.path).split(paths.sep).filter(Boolean);
496
905
  for (let length = 0; length <= parts.length; length++) {
@@ -503,40 +912,36 @@ async function rejectOverlap(source, destination, paths = nodePath) {
503
912
  }
504
913
  return false;
505
914
  };
506
- if (observed.kind === "directory" && await ancestorIncludes(destination, observed) || destination.observation?.kind === "directory" && await ancestorIncludes(source, destination.observation)) throw new FileAccessError("path-overlap", 409);
915
+ if (observed.kind === "directory" && await ancestorIncludes(destination, observed) || destination.observation?.kind === "directory" && await ancestorIncludes(source, destination.observation)) throw new FileAccessError$1("path-overlap", 409);
507
916
  }
508
- /** Requires the source revision and explicit, current replacement observation. */
509
917
  function observations(scope, source, expected, destination, replace = false, targetFingerprint) {
510
- if (!source.observation) throw new FileAccessError("missing", 404);
511
- if (scope.entry(source).fingerprint !== expected) throw new FileAccessError("stale", 409);
918
+ if (!source.observation) throw new FileAccessError$1("missing", 404);
919
+ if (scope.entry(source).fingerprint !== expected) throw new FileAccessError$1("stale", 409);
512
920
  if (!destination) return void 0;
513
921
  if (replace) {
514
- if (!targetFingerprint || !destination.observation || scope.entry(destination).fingerprint !== targetFingerprint) throw new FileAccessError("stale", 409, destination.observation ? { existing: scope.entry(destination) } : void 0);
922
+ if (!targetFingerprint || !destination.observation || scope.entry(destination).fingerprint !== targetFingerprint) throw new FileAccessError$1("stale", 409, destination.observation ? { existing: scope.entry(destination) } : void 0);
515
923
  return destination.observation;
516
924
  }
517
- if (destination.observation) throw new FileAccessError("exists", 409, { existing: scope.entry(destination) });
925
+ if (destination.observation) throw new FileAccessError$1("exists", 409, { existing: scope.entry(destination) });
518
926
  }
519
- /** Basic observed mutations; recursive and cross-device behavior compose through the same lock set. */
520
927
  var Mutations = class {
521
928
  scope;
522
929
  records;
523
930
  locks;
524
931
  trees;
525
- /** Shares owner-local records and fixed-order locks with uploads. */
526
932
  constructor(scope, records, locks, trees) {
527
933
  this.scope = scope;
528
934
  this.records = records;
529
935
  this.locks = locks;
530
936
  this.trees = trees;
531
937
  }
532
- /** Creates one exclusive directory and records the actual commit before cleanup. */
533
938
  mkdir(params, signal) {
534
939
  return this.records.run(params.operationId, {
535
940
  method: "mkdir",
536
941
  ...params
537
942
  }, (commit) => withSelections(this.scope, this.locks, [params.target], signal, async ([target]) => {
538
943
  const selected = target;
539
- if (selected.observation) throw new FileAccessError("exists", 409, { existing: this.scope.entry(selected) });
944
+ if (selected.observation) throw new FileAccessError$1("exists", 409, { existing: this.scope.entry(selected) });
540
945
  await selected.current();
541
946
  this.scope.mutation(selected);
542
947
  const observed = await selected.parent.mkdir(selected.name);
@@ -545,7 +950,6 @@ var Mutations = class {
545
950
  return entry;
546
951
  }));
547
952
  }
548
- /** Renames within one root, refusing stale source/target or physical containment. */
549
953
  rename(params, signal) {
550
954
  const segments = params.source.path.split("/");
551
955
  segments.pop();
@@ -573,7 +977,6 @@ var Mutations = class {
573
977
  return entry;
574
978
  }));
575
979
  }
576
- /** Removes exactly one selected object unless explicit recursive behavior is requested. */
577
980
  remove(params, signal) {
578
981
  return this.records.run(params.operationId, {
579
982
  method: "remove",
@@ -596,27 +999,24 @@ var Mutations = class {
596
999
  };
597
1000
  //#endregion
598
1001
  //#region src/moves.ts
599
- /** Moves within one workspace, preferring anchored rename and explicitly handling EXDEV. */
600
1002
  var Moves = class {
601
1003
  scope;
602
1004
  records;
603
1005
  locks;
604
1006
  trees;
605
- /** Shares operation records and ordered locks with all other writes. */
606
1007
  constructor(scope, records, locks, trees) {
607
1008
  this.scope = scope;
608
1009
  this.records = records;
609
1010
  this.locks = locks;
610
1011
  this.trees = trees;
611
1012
  }
612
- /** Rejects overlap and stale selections before changing either namespace. */
613
1013
  move(params, signal) {
614
1014
  return this.records.run(params.operationId, {
615
1015
  method: "move",
616
1016
  ...params,
617
1017
  replace: params.replace ?? false
618
1018
  }, (commit) => withSelections(this.scope, this.locks, [params.source, params.destination], signal, async ([source, destination]) => {
619
- if (params.source.workspaceId !== params.destination.workspaceId) throw new FileAccessError("outside-root", 403);
1019
+ if (params.source.workspaceId !== params.destination.workspaceId) throw new FileAccessError$1("outside-root", 403);
620
1020
  const from = source, to = destination;
621
1021
  await rejectOverlap(from, to, this.scope.paths);
622
1022
  const replacement = observations(this.scope, from, params.sourceFingerprint, to, params.replace, params.targetFingerprint);
@@ -629,7 +1029,7 @@ var Moves = class {
629
1029
  try {
630
1030
  await from.parent.rename(from.name, from.observation, to.parent, to.name, replacement);
631
1031
  } catch (error) {
632
- if (accessError(error).code !== "cross-device") throw error;
1032
+ if (accessError$1(error).code !== "cross-device") throw error;
633
1033
  let destinationCommitted = false;
634
1034
  let entry;
635
1035
  try {
@@ -646,9 +1046,9 @@ var Moves = class {
646
1046
  try {
647
1047
  await from.parent.stat(from.name);
648
1048
  } catch (failure) {
649
- if (accessError(failure).code === "missing") retained = false;
1049
+ if (accessError$1(failure).code === "missing") retained = false;
650
1050
  }
651
- throw new FileAccessError("move-incomplete", 500, {
1051
+ throw new FileAccessError$1("move-incomplete", 500, {
652
1052
  destinationCommitted: true,
653
1053
  sourceRetained: retained,
654
1054
  retainedPaths: retained ? [from.target.path] : []
@@ -666,17 +1066,17 @@ var Moves = class {
666
1066
  async copyFile(from, parts, observation, stage) {
667
1067
  const reader = await from.root.openRead([...from.target.path.split("/"), ...parts]);
668
1068
  try {
669
- if (this.scope.fingerprint(await reader.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError("stale", 409);
1069
+ if (this.scope.fingerprint(await reader.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError$1("stale", 409);
670
1070
  const size = Number(observation.size);
671
- if (!Number.isSafeInteger(size)) throw new FileAccessError("too-large", 413);
1071
+ if (!Number.isSafeInteger(size)) throw new FileAccessError$1("too-large", 413);
672
1072
  for (let position = 0; position < size;) {
673
1073
  await from.current();
674
1074
  const bytes = await reader.read(position, Math.min(65536, size - position));
675
- if (!bytes.byteLength) throw new FileAccessError("stale", 409);
1075
+ if (!bytes.byteLength) throw new FileAccessError$1("stale", 409);
676
1076
  await stage.write(bytes);
677
1077
  position += bytes.byteLength;
678
1078
  }
679
- if (this.scope.fingerprint(await reader.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError("stale", 409);
1079
+ if (this.scope.fingerprint(await reader.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError$1("stale", 409);
680
1080
  if (observation.mode !== void 0) await stage.setMode(observation.mode);
681
1081
  await stage.sync();
682
1082
  } finally {
@@ -695,7 +1095,7 @@ var Moves = class {
695
1095
  }
696
1096
  async copy(from, to, records, replacement, onPublished) {
697
1097
  const kind = from.observation?.kind;
698
- if (kind === "other") throw new FileAccessError("unsupported-type", 415);
1098
+ if (kind === "other") throw new FileAccessError$1("unsupported-type", 415);
699
1099
  if (kind === "file") {
700
1100
  const stage = await to.parent.stage();
701
1101
  try {
@@ -764,7 +1164,7 @@ var Moves = class {
764
1164
  } finally {
765
1165
  await file.close();
766
1166
  }
767
- } else throw new FileAccessError("unsupported-type", 415);
1167
+ } else throw new FileAccessError$1("unsupported-type", 415);
768
1168
  } finally {
769
1169
  await parent.close();
770
1170
  }
@@ -801,19 +1201,15 @@ var Moves = class {
801
1201
  };
802
1202
  //#endregion
803
1203
  //#region src/operation-records.ts
804
- /** Short-lived facts and in-flight deduplication; eviction never implies replay safety. */
805
- /** Canonical JSON makes equivalent property ordering share one operation key. */
806
1204
  function canonicalRequest(value) {
807
1205
  if (Array.isArray(value)) return `[${value.map(canonicalRequest).join(",")}]`;
808
1206
  if (value !== null && typeof value === "object") return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonicalRequest(item)}`).join(",")}}`;
809
1207
  return JSON.stringify(value);
810
1208
  }
811
- /** Retains at most 1000 records, with ten-minute settled facts and no eviction of active work. */
812
1209
  var OperationRecords = class {
813
1210
  instanceId;
814
1211
  now;
815
1212
  records = /* @__PURE__ */ new Map();
816
- /** Uses actual Gateway startup identity and a clock shared with snapshots. */
817
1213
  constructor(instanceId, now) {
818
1214
  this.instanceId = instanceId;
819
1215
  this.now = now;
@@ -821,7 +1217,6 @@ var OperationRecords = class {
821
1217
  expire() {
822
1218
  for (const [id, record] of this.records) if (!record.pending && record.settledAt !== void 0 && this.now() - record.settledAt >= 6e5) this.records.delete(id);
823
1219
  }
824
- /** Queries an existing fact only; cross-startup, expired and evicted records return unknown. */
825
1220
  status(instanceId, operationId) {
826
1221
  this.expire();
827
1222
  return instanceId === this.instanceId ? this.records.get(operationId)?.result ?? {
@@ -834,18 +1229,17 @@ var OperationRecords = class {
834
1229
  status: "unknown"
835
1230
  };
836
1231
  }
837
- /** Executes once while retained; an explicit commit records a fact before asynchronous release. */
838
1232
  run(operationId, request, work) {
839
1233
  this.expire();
840
1234
  const key = canonicalRequest(request);
841
1235
  const existing = this.records.get(operationId);
842
1236
  if (existing) {
843
- if (existing.key !== key) throw new FileAccessError("operation-conflict", 409);
1237
+ if (existing.key !== key) throw new FileAccessError$1("operation-conflict", 409);
844
1238
  return existing.promise;
845
1239
  }
846
1240
  if (this.records.size >= 1e3) {
847
1241
  const settled = [...this.records.entries()].filter(([, record]) => !record.pending).sort(([, a], [, b]) => (a.settledAt ?? 0) - (b.settledAt ?? 0))[0];
848
- if (!settled) throw new FileAccessError("capacity", 429);
1242
+ if (!settled) throw new FileAccessError$1("capacity", 429);
849
1243
  this.records.delete(settled[0]);
850
1244
  }
851
1245
  const record = {
@@ -877,7 +1271,7 @@ var OperationRecords = class {
877
1271
  if (record.result.status === "pending") commit(entry);
878
1272
  } catch (error) {
879
1273
  if (record.result.status !== "succeeded") {
880
- const failure = accessError(error);
1274
+ const failure = accessError$1(error);
881
1275
  const wire = AccessErrorSchema.parse({
882
1276
  code: failure.code,
883
1277
  message: failure.message,
@@ -898,7 +1292,6 @@ var OperationRecords = class {
898
1292
  });
899
1293
  return record.promise;
900
1294
  }
901
- /** Waits for active work; cancellation is supplied by the owning provider. */
902
1295
  async drain() {
903
1296
  await Promise.allSettled([...this.records.values()].filter((record) => record.pending).map((record) => record.promise));
904
1297
  }
@@ -906,40 +1299,38 @@ var OperationRecords = class {
906
1299
  //#endregion
907
1300
  //#region src/transfers.ts
908
1301
  async function nextChunk(iterator, signal) {
909
- if (signal.aborted) throw new FileAccessError("unavailable", 503);
1302
+ if (signal.aborted) throw new FileAccessError$1("unavailable", 503);
910
1303
  return new Promise((resolve, reject) => {
911
1304
  const aborted = () => {
912
1305
  signal.removeEventListener("abort", aborted);
913
- reject(new FileAccessError("unavailable", 503));
1306
+ reject(new FileAccessError$1("unavailable", 503));
914
1307
  };
915
1308
  signal.addEventListener("abort", aborted, { once: true });
916
1309
  Promise.resolve().then(() => iterator.next()).then(resolve, reject).finally(() => signal.removeEventListener("abort", aborted)).catch(() => {});
917
1310
  });
918
1311
  }
919
- /** Resolves one inclusive range from the opened object's actual safe-integer length. */
920
- function byteRange(total, request) {
1312
+ function byteRange$1(total, request) {
921
1313
  if (!request) return void 0;
922
1314
  const start = request.kind === "suffix" ? Math.max(0, total - request.length) : request.start;
923
1315
  const end = request.kind === "suffix" ? total - 1 : Math.min(request.end ?? total - 1, total - 1);
924
- if (total === 0 || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || start >= total || end < start || request.kind === "suffix" && (!Number.isSafeInteger(request.length) || request.length <= 0)) throw new FileAccessError("invalid-range", 416, { contentLength: total });
1316
+ if (total === 0 || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || start >= total || end < start || request.kind === "suffix" && (!Number.isSafeInteger(request.length) || request.length <= 0)) throw new FileAccessError$1("invalid-range", 416, { contentLength: total });
925
1317
  return {
926
1318
  start,
927
1319
  end,
928
1320
  total
929
1321
  };
930
1322
  }
931
- /** Reads the current selected regular file without buffering the full response. */
932
- async function readFileResource(scope, params, call) {
1323
+ async function readFileResource$1(scope, params, call) {
933
1324
  const selection = await scope.select(params.target, call.signal);
934
1325
  try {
935
1326
  const entry = scope.entry(selection);
936
- if (params.expectedFingerprint && params.expectedFingerprint !== entry.fingerprint) throw new FileAccessError("stale", 409);
1327
+ if (params.expectedFingerprint && params.expectedFingerprint !== entry.fingerprint) throw new FileAccessError$1("stale", 409);
937
1328
  const reader = await selection.root.openRead(params.target.path.split("/").filter(Boolean));
938
1329
  const observation = await reader.stat();
939
- if (scope.fingerprint(observation) !== scope.fingerprint(selection.referentObservation ?? selection.observation) || scope.fingerprint(await selection.parent.stat(selection.name)) !== scope.fingerprint(selection.observation)) throw new FileAccessError("stale", 409);
1330
+ if (scope.fingerprint(observation) !== scope.fingerprint(selection.referentObservation ?? selection.observation) || scope.fingerprint(await selection.parent.stat(selection.name)) !== scope.fingerprint(selection.observation)) throw new FileAccessError$1("stale", 409);
940
1331
  const total = Number(observation.size);
941
- if (!Number.isSafeInteger(total)) throw new FileAccessError("too-large", 413);
942
- const range = call.method === "GET" ? byteRange(total, call.range) : void 0;
1332
+ if (!Number.isSafeInteger(total)) throw new FileAccessError$1("too-large", 413);
1333
+ const range = call.method === "GET" ? byteRange$1(total, call.range) : void 0;
943
1334
  const bytes = {
944
1335
  contentType: "application/octet-stream",
945
1336
  contentLength: range ? range.end - range.start + 1 : total,
@@ -973,16 +1364,16 @@ async function readFileResource(scope, params, call) {
973
1364
  let position = range?.start ?? 0;
974
1365
  const end = range ? range.end + 1 : total;
975
1366
  while (position < end) {
976
- if (closed) throw new FileAccessError("unavailable", 503);
1367
+ if (closed) throw new FileAccessError$1("unavailable", 503);
977
1368
  await selection.current();
978
1369
  const chunk = await reader.read(position, Math.min(65536, end - position));
979
1370
  await selection.current();
980
- if (chunk.byteLength === 0) throw new FileAccessError("stale", 409);
1371
+ if (chunk.byteLength === 0) throw new FileAccessError$1("stale", 409);
981
1372
  position += chunk.byteLength;
982
1373
  yield chunk;
983
1374
  }
984
1375
  } catch (error) {
985
- throw accessError(error);
1376
+ throw accessError$1(error);
986
1377
  } finally {
987
1378
  await close();
988
1379
  }
@@ -991,19 +1382,18 @@ async function readFileResource(scope, params, call) {
991
1382
  };
992
1383
  } catch (error) {
993
1384
  await selection.close();
994
- throw accessError(error);
1385
+ throw accessError$1(error);
995
1386
  }
996
1387
  }
997
- /** Streams a bounded upload into same-directory staging, recording publication before release. */
998
1388
  async function uploadResource(scope, records, locks, params, call) {
999
- if (!params.operationId || !params.source) throw new FileAccessError("invalid-params", 400);
1389
+ if (!params.operationId || !params.source) throw new FileAccessError$1("invalid-params", 400);
1000
1390
  const source = params.source;
1001
1391
  const result = await records.run(params.operationId, {
1002
1392
  method: "upload",
1003
1393
  ...params,
1004
1394
  replace: params.replace ?? false
1005
1395
  }, async (commit) => {
1006
- if (source.size > 268435456) throw new FileAccessError("too-large", 413);
1396
+ if (source.size > 268435456) throw new FileAccessError$1("too-large", 413);
1007
1397
  const preliminary = await scope.select(params.target, call.signal, true);
1008
1398
  const selectedPath = preliminary.path;
1009
1399
  let release;
@@ -1016,12 +1406,12 @@ async function uploadResource(scope, records, locks, params, call) {
1016
1406
  }
1017
1407
  const selection = await scope.select(params.target, call.signal, true);
1018
1408
  try {
1019
- if (selection.path !== selectedPath) throw new FileAccessError("stale", 409);
1409
+ if (selection.path !== selectedPath) throw new FileAccessError$1("stale", 409);
1020
1410
  scope.mutation(selection);
1021
1411
  const existing = selection.observation;
1022
1412
  if (params.replace) {
1023
- if (!params.targetFingerprint || !existing || scope.entry(selection).fingerprint !== params.targetFingerprint) throw new FileAccessError("stale", 409, existing ? { existing: scope.entry(selection) } : void 0);
1024
- } else if (existing) throw new FileAccessError("exists", 409, { existing: scope.entry(selection) });
1413
+ if (!params.targetFingerprint || !existing || scope.entry(selection).fingerprint !== params.targetFingerprint) throw new FileAccessError$1("stale", 409, existing ? { existing: scope.entry(selection) } : void 0);
1414
+ } else if (existing) throw new FileAccessError$1("exists", 409, { existing: scope.entry(selection) });
1025
1415
  const stage = await selection.parent.stage();
1026
1416
  let publishedEntry;
1027
1417
  const iterator = call.body[Symbol.asyncIterator]();
@@ -1033,14 +1423,14 @@ async function uploadResource(scope, records, locks, params, call) {
1033
1423
  const chunk = next.value;
1034
1424
  await selection.current();
1035
1425
  total += chunk.byteLength;
1036
- if (total > 268435456) throw new FileAccessError("too-large", 413);
1037
- if (total > source.size) throw new FileAccessError("size-mismatch", 400);
1426
+ if (total > 268435456) throw new FileAccessError$1("too-large", 413);
1427
+ if (total > source.size) throw new FileAccessError$1("size-mismatch", 400);
1038
1428
  for (let offset = 0; offset < chunk.byteLength; offset += 65536) {
1039
1429
  await stage.write(chunk.subarray(offset, offset + 65536));
1040
1430
  await selection.current();
1041
1431
  }
1042
1432
  }
1043
- if (total !== source.size) throw new FileAccessError("size-mismatch", 400);
1433
+ if (total !== source.size) throw new FileAccessError$1("size-mismatch", 400);
1044
1434
  if (existing?.mode !== void 0) await stage.setMode(existing.mode);
1045
1435
  await stage.sync();
1046
1436
  await selection.current();
@@ -1075,11 +1465,9 @@ async function uploadResource(scope, records, locks, params, call) {
1075
1465
  }
1076
1466
  //#endregion
1077
1467
  //#region src/trees.ts
1078
- /** Records all selected objects before side effects, then checks each pending deletion separately. */
1079
1468
  var Trees = class {
1080
1469
  scope;
1081
1470
  budget;
1082
- /** Test budgets may be smaller; production cannot exceed the declared maximum. */
1083
1471
  constructor(scope, budget = {
1084
1472
  maxObjects: 1e4,
1085
1473
  maxDepth: 256
@@ -1088,12 +1476,11 @@ var Trees = class {
1088
1476
  this.scope = scope;
1089
1477
  this.budget = budget;
1090
1478
  }
1091
- /** Scans an entire tree before staging/deletion, refusing excess, protected entries or changes. */
1092
1479
  async scan(selection) {
1093
1480
  const result = [];
1094
1481
  const visit = async (parent, name, observation, parts) => {
1095
- if (!SegmentSchema.safeParse(name).success) throw new FileAccessError("unsupported-name", 415);
1096
- if (parts.length > this.budget.maxDepth || result.length >= this.budget.maxObjects) throw new FileAccessError("too-large-directory", 413);
1482
+ if (!SegmentSchema$1.safeParse(name).success) throw new FileAccessError$1("unsupported-name", 415);
1483
+ if (parts.length > this.budget.maxDepth || result.length >= this.budget.maxObjects) throw new FileAccessError$1("too-large-directory", 413);
1097
1484
  await selection.current();
1098
1485
  const path = [selection.target.path, ...parts].filter(Boolean).join("/");
1099
1486
  if (observation.kind === "symlink") {
@@ -1125,7 +1512,7 @@ var Trees = class {
1125
1512
  }
1126
1513
  const directory = await parent.openDirectory([name]);
1127
1514
  try {
1128
- if (this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError("stale", 409);
1515
+ if (this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError$1("stale", 409);
1129
1516
  const entries = [...await directory.list(1e4, { strict: true })].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1130
1517
  result.push({
1131
1518
  parts,
@@ -1133,28 +1520,26 @@ var Trees = class {
1133
1520
  children: entries.map((entry) => entry.name)
1134
1521
  });
1135
1522
  for (const entry of entries) await visit(directory, entry.name, entry.observation, [...parts, entry.name]);
1136
- if (this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError("stale", 409);
1523
+ if (this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(observation)) throw new FileAccessError$1("stale", 409);
1137
1524
  } finally {
1138
1525
  await directory.close();
1139
1526
  }
1140
1527
  };
1141
- if (!selection.observation) throw new FileAccessError("missing", 404);
1528
+ if (!selection.observation) throw new FileAccessError$1("missing", 404);
1142
1529
  await visit(selection.parent, selection.name, selection.observation, []);
1143
1530
  return result;
1144
1531
  }
1145
- /** Rechecks every selected object and directory child set before publication or source cleanup. */
1146
1532
  async verify(selection, records) {
1147
1533
  const current = await this.scan(selection);
1148
- if (current.length !== records.length || current.some((item, index) => item.parts.join("/") !== records[index]?.parts.join("/") || this.scope.fingerprint(item.observation) !== this.scope.fingerprint(records[index]?.observation))) throw new FileAccessError("stale", 409);
1534
+ if (current.length !== records.length || current.some((item, index) => item.parts.join("/") !== records[index]?.parts.join("/") || this.scope.fingerprint(item.observation) !== this.scope.fingerprint(records[index]?.observation))) throw new FileAccessError$1("stale", 409);
1149
1535
  }
1150
- /** Deletes copied versions in postorder, stopping immediately on new or changed pending content. */
1151
1536
  async remove(selection, records) {
1152
1537
  await this.verify(selection, records);
1153
1538
  const byPath = new Map(records.map((record) => [record.parts.join("/"), record]));
1154
1539
  const visit = async (parent, name, record) => {
1155
1540
  await selection.current();
1156
1541
  this.scope.mutation(selection);
1157
- if (this.scope.fingerprint(await parent.stat(name)) !== this.scope.fingerprint(record.observation)) throw new FileAccessError("stale", 409);
1542
+ if (this.scope.fingerprint(await parent.stat(name)) !== this.scope.fingerprint(record.observation)) throw new FileAccessError$1("stale", 409);
1158
1543
  if (record.observation.kind !== "directory") {
1159
1544
  await parent.remove(name, record.observation);
1160
1545
  return;
@@ -1164,14 +1549,14 @@ var Trees = class {
1164
1549
  let expected = record.observation;
1165
1550
  const remaining = [...record.children];
1166
1551
  for (const child of record.children) {
1167
- if (this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(expected)) throw new FileAccessError("stale", 409);
1552
+ if (this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(expected)) throw new FileAccessError$1("stale", 409);
1168
1553
  const actual = (await directory.list(1e4, { strict: true })).map((entry) => entry.name).sort();
1169
- if (JSON.stringify(actual) !== JSON.stringify(remaining)) throw new FileAccessError("stale", 409);
1554
+ if (JSON.stringify(actual) !== JSON.stringify(remaining)) throw new FileAccessError$1("stale", 409);
1170
1555
  await visit(directory, child, byPath.get([...record.parts, child].join("/")));
1171
1556
  remaining.splice(remaining.indexOf(child), 1);
1172
1557
  expected = await directory.stat();
1173
1558
  }
1174
- if ((await directory.list(1e4, { strict: true })).length !== 0 || this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(expected)) throw new FileAccessError("stale", 409);
1559
+ if ((await directory.list(1e4, { strict: true })).length !== 0 || this.scope.fingerprint(await directory.stat()) !== this.scope.fingerprint(expected)) throw new FileAccessError$1("stale", 409);
1175
1560
  await selection.current();
1176
1561
  this.scope.mutation(selection);
1177
1562
  await parent.remove(name, expected);
@@ -1184,19 +1569,18 @@ var Trees = class {
1184
1569
  };
1185
1570
  //#endregion
1186
1571
  //#region src/provider.ts
1187
- /** Creates an owner-local provider with bounded transient state. */
1188
1572
  function createFileExplorer(dependencies) {
1189
1573
  const abort = new AbortController();
1190
1574
  const signal = AbortSignal.any([abort.signal, dependencies.signal]);
1191
1575
  const scope = new FileScope(dependencies.roots, dependencies.files, signal, dependencies.instanceId, void 0, dependencies.referenceFormatter);
1192
- const listings = new Listings(scope, dependencies.now ?? Date.now);
1576
+ const listings = new Listings(scope, dependencies.now ?? Date.now, dependencies.performance);
1193
1577
  const records = new OperationRecords(dependencies.instanceId, dependencies.now ?? Date.now);
1194
1578
  const locks = new PathLocks();
1195
1579
  const trees = new Trees(scope, dependencies.treeBudget);
1196
1580
  const mutations = new Mutations(scope, records, locks, trees);
1197
1581
  const moves = new Moves(scope, records, locks, trees);
1198
1582
  const current = () => {
1199
- if (signal.aborted) throw new FileAccessError("unavailable", 503);
1583
+ if (signal.aborted) throw new FileAccessError$1("unavailable", 503);
1200
1584
  };
1201
1585
  const active = /* @__PURE__ */ new Set();
1202
1586
  let closing;
@@ -1215,11 +1599,9 @@ function createFileExplorer(dependencies) {
1215
1599
  return promise;
1216
1600
  };
1217
1601
  return {
1218
- /** Returns explicit root display metadata for the named workspace. */
1219
1602
  roots: (workspaceId, request) => track(async () => {
1220
1603
  return { roots: (await scope.snapshot(workspaceId, request)).roots };
1221
1604
  }),
1222
- /** Observes one current object and its resolved host display path. */
1223
1605
  stat: (target, request) => track(async () => {
1224
1606
  const selection = await scope.select(target, request);
1225
1607
  try {
@@ -1231,24 +1613,19 @@ function createFileExplorer(dependencies) {
1231
1613
  await selection.close();
1232
1614
  }
1233
1615
  }),
1234
- /** Pages immutable bounded snapshots while rechecking current scope. */
1235
- list: (params, request) => track(() => listings.list(params, request)),
1236
- /** Streams current GET/HEAD bytes or a staged bounded PUT upload. */
1237
- fileBytes: (params, call) => track(() => call.method === "PUT" ? uploadResource(scope, records, locks, params, call) : readFileResource(scope, params, call)),
1238
- /** Queries retained execution facts without replaying any work. */
1616
+ list: (params, request) => track(() => observeFileStage(dependencies.performance, "file.list", () => listings.list(params, request), (result) => ({
1617
+ count: result.entries.length,
1618
+ cacheState: params.cursor ? "hit" : "miss"
1619
+ }))),
1620
+ fileBytes: (params, call) => track(() => call.method === "PUT" ? uploadResource(scope, records, locks, params, call) : readFileResource$1(scope, params, call)),
1239
1621
  operationStatus: (params) => {
1240
1622
  current();
1241
1623
  return records.status(params.instanceId, params.operationId);
1242
1624
  },
1243
- /** Creates one directory exclusively with operation deduplication. */
1244
1625
  mkdir: (params, request) => track(() => mutations.mkdir(params, request)),
1245
- /** Renames an observed object within its current root. */
1246
1626
  rename: (params, request) => track(() => mutations.rename(params, request)),
1247
- /** Removes only the selected revision; recursive removal scans every descendant. */
1248
1627
  remove: (params, request) => track(() => mutations.remove(params, request)),
1249
- /** Moves within one workspace, preserving committed-destination facts on cleanup failure. */
1250
1628
  move: (params, request) => track(() => moves.move(params, request)),
1251
- /** Rejects new work and joins cleanup; failed physical cleanup remains retryable. */
1252
1629
  close() {
1253
1630
  closing ??= (async () => {
1254
1631
  abort.abort();
@@ -1265,16 +1642,761 @@ function createFileExplorer(dependencies) {
1265
1642
  };
1266
1643
  }
1267
1644
  //#endregion
1645
+ //#region src/reader.ts
1646
+ function failure(code) {
1647
+ return Object.assign(new Error(code), { code });
1648
+ }
1649
+ function hasCompletion(error) {
1650
+ return error instanceof Error && "finished" in error && error.finished instanceof Promise;
1651
+ }
1652
+ function createScheduledReader(reader, ownerSignal, performance) {
1653
+ let active = 0;
1654
+ const queue = [];
1655
+ const pump = () => {
1656
+ while (active < 4 && queue.length) queue.shift()();
1657
+ };
1658
+ function admit(caller, budget, work, finished, cancelValue) {
1659
+ const queued = startFileStage(performance, "file.queue");
1660
+ if (caller.aborted || ownerSignal.aborted) {
1661
+ queued("cancelled");
1662
+ return Promise.reject(failure("cancelled"));
1663
+ }
1664
+ if (queue.length >= 64) {
1665
+ queued("error");
1666
+ return Promise.reject(failure("unavailable"));
1667
+ }
1668
+ return new Promise((resolve, reject) => {
1669
+ const controller = new AbortController();
1670
+ const lifetime = AbortSignal.any([caller, ownerSignal]);
1671
+ let complete;
1672
+ const completion = new Promise((resolve) => {
1673
+ complete = resolve;
1674
+ });
1675
+ let started = false;
1676
+ let done = false;
1677
+ let value;
1678
+ const cleanup = () => {
1679
+ clearTimeout(timer);
1680
+ lifetime.removeEventListener("abort", abort);
1681
+ };
1682
+ const release = () => {
1683
+ if (done) return;
1684
+ done = true;
1685
+ cleanup();
1686
+ complete();
1687
+ active--;
1688
+ pump();
1689
+ };
1690
+ const cancel = (code) => {
1691
+ if (controller.signal.aborted || done) return;
1692
+ clearTimeout(timer);
1693
+ controller.abort(failure(code));
1694
+ if (!started) {
1695
+ queued(code === "cancelled" ? "cancelled" : "timeout");
1696
+ const index = queue.indexOf(start);
1697
+ if (index >= 0) queue.splice(index, 1);
1698
+ done = true;
1699
+ cleanup();
1700
+ complete();
1701
+ }
1702
+ if (value !== void 0) cancelValue?.(value);
1703
+ reject(started ? Object.assign(failure(code), { finished: completion }) : failure(code));
1704
+ };
1705
+ const abort = () => cancel("cancelled");
1706
+ const timer = setTimeout(() => cancel("deadline-exceeded"), budget);
1707
+ let admitted;
1708
+ const admission = new Promise((resolve) => {
1709
+ admitted = resolve;
1710
+ });
1711
+ const start = () => {
1712
+ started = true;
1713
+ active++;
1714
+ admitted();
1715
+ };
1716
+ admission.then(() => {
1717
+ queued("ok", { count: queue.length });
1718
+ return work(controller.signal);
1719
+ }).then((result) => {
1720
+ clearTimeout(timer);
1721
+ value = result;
1722
+ if (controller.signal.aborted) cancelValue?.(result);
1723
+ if (finished) finished(result).then(release, () => {});
1724
+ else release();
1725
+ resolve(result);
1726
+ }, (error) => {
1727
+ clearTimeout(timer);
1728
+ if (hasCompletion(error)) error.finished.then(release, () => {});
1729
+ else release();
1730
+ reject(error);
1731
+ });
1732
+ lifetime.addEventListener("abort", abort, { once: true });
1733
+ queue.push(start);
1734
+ pump();
1735
+ });
1736
+ }
1737
+ return {
1738
+ pathStyle: reader.pathStyle,
1739
+ open: (path, signal) => admit(signal, 3e4, (signal) => observeFileStage(performance, "file.open", async () => {
1740
+ const handle = await reader.open(path, signal);
1741
+ return {
1742
+ ...handle,
1743
+ readRange: (offset, length, signal) => observeFileStage(performance, "file.read", () => handle.readRange(offset, length, signal), (bytes) => ({ bytes: bytes.byteLength })),
1744
+ async close() {
1745
+ const end = startFileStage(performance, "file.close");
1746
+ try {
1747
+ const result = await handle.close();
1748
+ end(result.status === "closed" ? "ok" : "unknown");
1749
+ return result;
1750
+ } catch (error) {
1751
+ end(fileOutcome(error));
1752
+ throw error;
1753
+ }
1754
+ }
1755
+ };
1756
+ }), (handle) => handle.finished, (handle) => {
1757
+ handle.close().catch(() => {});
1758
+ }),
1759
+ observe: (path, signal) => admit(signal, 5e3, (signal) => observeFileStage(performance, "file.observe", () => reader.observe(path, signal)))
1760
+ };
1761
+ }
1762
+ //#endregion
1763
+ //#region src/references/formatter.ts
1764
+ function createReferenceFormatter(gatewayId, signal, active) {
1765
+ return {
1766
+ fingerprint(observation, referent) {
1767
+ signal.throwIfAborted();
1768
+ if (!active()) throw new Error("File reference formatter withdrawn");
1769
+ const one = (item) => createHash("sha256").update(JSON.stringify([
1770
+ item.device,
1771
+ item.inode,
1772
+ item.kind,
1773
+ item.size,
1774
+ item.modifiedNs,
1775
+ item.changedNs
1776
+ ])).digest("hex");
1777
+ return observation.kind === "symlink" && referent ? createHash("sha256").update(JSON.stringify([one(observation), one(referent)])).digest("hex") : one(observation);
1778
+ },
1779
+ formatCurrent(input) {
1780
+ if (signal.aborted || !active() || input.gatewayId !== gatewayId) return void 0;
1781
+ try {
1782
+ return { uri: currentReference(gatewayId, input.pathStyle, input.absolutePath) };
1783
+ } catch {
1784
+ return;
1785
+ }
1786
+ },
1787
+ format(input) {
1788
+ if (signal.aborted || !active() || input.gatewayId !== gatewayId) return void 0;
1789
+ try {
1790
+ return { uri: attachmentReference(gatewayId, {
1791
+ workspaceId: input.workspaceId,
1792
+ sessionId: input.sessionId,
1793
+ fileId: input.file.id
1794
+ }) };
1795
+ } catch {
1796
+ return;
1797
+ }
1798
+ }
1799
+ };
1800
+ }
1801
+ //#endregion
1802
+ //#region src/references/transfers.ts
1803
+ function byteRange(total, request) {
1804
+ if (!request) return void 0;
1805
+ const start = request.kind === "suffix" ? Math.max(0, total - request.length) : request.start;
1806
+ const end = request.kind === "suffix" ? total - 1 : Math.min(request.end ?? total - 1, total - 1);
1807
+ if (total === 0 || !Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || start >= total || end < start || request.kind === "suffix" && (!Number.isSafeInteger(request.length) || request.length <= 0)) throw new FileAccessError("invalid-range", 416, { contentLength: total });
1808
+ return {
1809
+ start,
1810
+ end,
1811
+ total
1812
+ };
1813
+ }
1814
+ async function readFileResource(reader, formatter, reference, expectedFingerprint, call) {
1815
+ if (reference.target.pathStyle !== reader.pathStyle) throw new FileAccessError("platform-mismatch", 400);
1816
+ let handle;
1817
+ try {
1818
+ handle = await reader.open(reference.target.absolutePath, call.signal);
1819
+ } catch (error) {
1820
+ throw accessError(error);
1821
+ }
1822
+ let closed = false;
1823
+ const close = async () => {
1824
+ if (closed) return;
1825
+ const result = await handle.close();
1826
+ if (result.status !== "closed") throw new FileAccessError(result.code, 503, { cleanupId: result.cleanupId });
1827
+ closed = true;
1828
+ };
1829
+ try {
1830
+ const fingerprint = formatter.fingerprint(handle.observation);
1831
+ if (expectedFingerprint && expectedFingerprint !== fingerprint) throw new FileAccessError("stale", 409);
1832
+ const path = reference.target.absolutePath;
1833
+ const name = (reference.target.pathStyle === "windows" ? path.split(/[\\/]/) : path.split("/")).at(-1) || "file";
1834
+ const metadata = {
1835
+ ...reference.target,
1836
+ ...handle.resolvedPath ? { resolvedPath: handle.resolvedPath } : {},
1837
+ gatewayId: reference.gatewayId,
1838
+ referenceKind: "current",
1839
+ uri: currentReference(reference.gatewayId, reference.target.pathStyle, path),
1840
+ name,
1841
+ mediaType: handle.mediaType,
1842
+ size: handle.size,
1843
+ fingerprint
1844
+ };
1845
+ const range = call.method === "GET" ? byteRange(handle.size, call.range) : void 0;
1846
+ const bytes = {
1847
+ contentType: handle.mediaType,
1848
+ contentLength: range ? range.end - range.start + 1 : handle.size,
1849
+ contentDisposition: {
1850
+ filename: name,
1851
+ disposition: "attachment"
1852
+ },
1853
+ range
1854
+ };
1855
+ if (call.method === "HEAD") {
1856
+ await close();
1857
+ return {
1858
+ kind: "head",
1859
+ bytes,
1860
+ metadata
1861
+ };
1862
+ }
1863
+ return {
1864
+ kind: "bytes",
1865
+ bytes,
1866
+ metadata,
1867
+ body: (async function* () {
1868
+ try {
1869
+ let offset = range?.start ?? 0;
1870
+ const end = range ? range.end + 1 : handle.size;
1871
+ while (offset < end) {
1872
+ const chunk = await handle.readRange(offset, Math.min(262144, end - offset), call.signal);
1873
+ if (!chunk.byteLength) throw new FileAccessError("stale", 409);
1874
+ offset += chunk.byteLength;
1875
+ yield chunk;
1876
+ }
1877
+ } catch (error) {
1878
+ throw accessError(error);
1879
+ } finally {
1880
+ await close();
1881
+ }
1882
+ })(),
1883
+ close
1884
+ };
1885
+ } catch (error) {
1886
+ await close();
1887
+ throw accessError(error);
1888
+ }
1889
+ }
1890
+ //#endregion
1891
+ //#region src/references/attachments.ts
1892
+ var AttachmentResources = class {
1893
+ references;
1894
+ signal;
1895
+ gatewayId;
1896
+ active = /* @__PURE__ */ new Set();
1897
+ constructor(references, signal, gatewayId) {
1898
+ this.references = references;
1899
+ this.signal = signal;
1900
+ this.gatewayId = gatewayId;
1901
+ }
1902
+ async read(params, call) {
1903
+ if (call.method === "PUT") throw new FileAccessError("invalid-params", 400);
1904
+ if (!this.gatewayId) throw new FileAccessError("unavailable", 503);
1905
+ const signal = AbortSignal.any([this.signal, call.signal]);
1906
+ signal.throwIfAborted();
1907
+ if (!this.references.metadata(params)) throw new FileAccessError("missing", 404);
1908
+ const reader = await this.references.open(params, { signal });
1909
+ let closing;
1910
+ const close = () => {
1911
+ closing ??= Promise.resolve().then(() => reader.close()).then(() => {
1912
+ this.active.delete(close);
1913
+ signal.removeEventListener("abort", aborted);
1914
+ }).catch((error) => {
1915
+ closing = void 0;
1916
+ throw error;
1917
+ });
1918
+ return closing;
1919
+ };
1920
+ const aborted = () => {
1921
+ close().catch(() => {});
1922
+ };
1923
+ this.active.add(close);
1924
+ signal.addEventListener("abort", aborted, { once: true });
1925
+ try {
1926
+ signal.throwIfAborted();
1927
+ const total = reader.metadata.size;
1928
+ const range = call.method === "GET" ? byteRange(total, call.range) : void 0;
1929
+ const bytes = {
1930
+ contentType: reader.metadata.mediaType,
1931
+ contentLength: range ? range.end - range.start + 1 : total,
1932
+ contentDisposition: {
1933
+ filename: reader.metadata.name,
1934
+ disposition: "attachment"
1935
+ },
1936
+ range
1937
+ };
1938
+ const metadata = {
1939
+ referenceKind: "attachment",
1940
+ uri: attachmentReference(this.gatewayId, params),
1941
+ fileId: reader.metadata.id,
1942
+ name: reader.metadata.name,
1943
+ mediaType: reader.metadata.mediaType,
1944
+ size: total,
1945
+ width: reader.metadata.width,
1946
+ height: reader.metadata.height
1947
+ };
1948
+ if (call.method === "HEAD") {
1949
+ await close();
1950
+ return {
1951
+ kind: "head",
1952
+ bytes,
1953
+ metadata
1954
+ };
1955
+ }
1956
+ return {
1957
+ kind: "bytes",
1958
+ bytes,
1959
+ metadata,
1960
+ body: (async function* () {
1961
+ try {
1962
+ let position = range?.start ?? 0;
1963
+ const end = range ? range.end + 1 : total;
1964
+ while (position < end) {
1965
+ signal.throwIfAborted();
1966
+ if (closing) throw new FileAccessError("unavailable", 503);
1967
+ const chunk = await reader.read(position, Math.min(65536, end - position));
1968
+ signal.throwIfAborted();
1969
+ if (!chunk.byteLength) throw new FileAccessError("stale", 409);
1970
+ position += chunk.byteLength;
1971
+ yield chunk;
1972
+ }
1973
+ } catch (error) {
1974
+ throw accessError(error);
1975
+ } finally {
1976
+ await close();
1977
+ }
1978
+ })(),
1979
+ close
1980
+ };
1981
+ } catch (error) {
1982
+ await close();
1983
+ throw accessError(error);
1984
+ }
1985
+ }
1986
+ async close() {
1987
+ const errors = (await Promise.allSettled([...this.active].map((close) => close()))).filter((result) => result.status === "rejected").map((result) => result.reason);
1988
+ if (errors.length) throw new AggregateError(errors, "Attachment drain failed");
1989
+ }
1990
+ };
1991
+ //#endregion
1992
+ //#region src/references/tickets.ts
1993
+ const ReferenceUrlsParamsSchema = z.object({ uris: z.array(z.string().max(393400)).min(1).max(256) }).strict();
1994
+ const ReferenceUrlsResultSchema = z.object({ items: z.array(z.union([z.object({
1995
+ uri: z.string(),
1996
+ url: z.string(),
1997
+ fingerprint: z.string()
1998
+ }).strict(), z.object({
1999
+ uri: z.string(),
2000
+ code: z.enum([
2001
+ "missing",
2002
+ "stale",
2003
+ "invalid-reference",
2004
+ "gateway-mismatch",
2005
+ "unavailable"
2006
+ ])
2007
+ }).strict()])) }).strict();
2008
+ async function referenceUrls(uris, signal, fingerprint, sign) {
2009
+ const items = [];
2010
+ for (const uri of uris) {
2011
+ signal.throwIfAborted();
2012
+ try {
2013
+ const pinned = await fingerprint(uri, signal);
2014
+ signal.throwIfAborted();
2015
+ items.push({
2016
+ uri,
2017
+ fingerprint: pinned,
2018
+ url: sign(uri, pinned)
2019
+ });
2020
+ } catch (error) {
2021
+ signal.throwIfAborted();
2022
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
2023
+ items.push({
2024
+ uri,
2025
+ code: code === "missing" || code === "stale" || code === "invalid-reference" || code === "gateway-mismatch" ? code : "unavailable"
2026
+ });
2027
+ }
2028
+ }
2029
+ return { items };
2030
+ }
2031
+ //#endregion
2032
+ //#region src/references/register.ts
2033
+ const ReferenceBytesParamsSchema = z.object({
2034
+ uri: z.string().max(393400),
2035
+ expectedFingerprint: z.string().regex(/^[0-9a-f]{64}$/).optional()
2036
+ }).strict();
2037
+ const ReferenceMetadataSchema = z.union([GatewayFileMetadataSchema, AttachmentMetadataSchema]);
2038
+ function registerFileReferences(ctx, reader = ctx.services.get("host-file-reader")) {
2039
+ const identity = ctx.services.get("workspace-roots").availability();
2040
+ const controller = new AbortController();
2041
+ const signal = AbortSignal.any([ctx.signal, controller.signal]);
2042
+ const attachments = identity.available ? new AttachmentResources(ctx.services.get("attachment-references"), signal, identity.gatewayId) : void 0;
2043
+ const pending = /* @__PURE__ */ new Set();
2044
+ const opened = /* @__PURE__ */ new Set();
2045
+ let withdrawn = false;
2046
+ let unbind = () => {};
2047
+ let closing;
2048
+ const drain = () => {
2049
+ closing ??= (async () => {
2050
+ controller.abort();
2051
+ await Promise.allSettled([...pending]);
2052
+ const failures = (await Promise.allSettled([...opened].map((close) => close()))).filter((result) => result.status === "rejected").map((result) => result.reason);
2053
+ await attachments?.close();
2054
+ if (failures.length) throw new AggregateError(failures, "Reference drain failed");
2055
+ if (withdrawn) {
2056
+ unbind();
2057
+ unbind = () => {};
2058
+ }
2059
+ })().catch((error) => {
2060
+ closing = void 0;
2061
+ throw error;
2062
+ });
2063
+ return closing;
2064
+ };
2065
+ unbind = ctx.services.get("work-lifecycle").register(drain);
2066
+ ctx.onDispose(async () => {
2067
+ withdrawn = true;
2068
+ await drain();
2069
+ unbind();
2070
+ unbind = () => {};
2071
+ });
2072
+ const formatter = identity.available ? createReferenceFormatter(identity.gatewayId, signal, () => !closing) : void 0;
2073
+ const publishedFormatter = identity.available ? formatter : {
2074
+ fingerprint: () => {
2075
+ throw new FileAccessError("unavailable", 503);
2076
+ },
2077
+ format: () => void 0,
2078
+ formatCurrent: () => void 0
2079
+ };
2080
+ ctx.services.provide("file-reference-formatter", publishedFormatter);
2081
+ const read = async (params, call) => {
2082
+ signal.throwIfAborted();
2083
+ if (!identity.available || !reader || !formatter || !attachments) throw new FileAccessError("unavailable", 503);
2084
+ if (call.method === "PUT") throw new FileAccessError("invalid-params", 400);
2085
+ const reference = parseReference(params.uri, identity.gatewayId);
2086
+ if (call.via === "ticket" && !params.expectedFingerprint) throw new FileAccessError("invalid-reference", 400);
2087
+ if (reference.kind === "attachment" && params.expectedFingerprint && params.expectedFingerprint !== reference.reference.fileId) throw new FileAccessError("stale", 409);
2088
+ if (reference.kind === "attachment") return attachments.read(reference.reference, call);
2089
+ return readFileResource(reader, formatter, reference, params.expectedFingerprint, call);
2090
+ };
2091
+ ctx.client.registerResource({
2092
+ name: "referenceBytes",
2093
+ ticket: { cache: "immutable" },
2094
+ session: { kind: "read" },
2095
+ methods: ["GET", "HEAD"],
2096
+ params: ReferenceBytesParamsSchema,
2097
+ result: z.object({}).strict(),
2098
+ metadata: ReferenceMetadataSchema.optional(),
2099
+ handle: async (params, call) => {
2100
+ const work = read(params, call);
2101
+ pending.add(work);
2102
+ try {
2103
+ const result = await work;
2104
+ if (result.kind !== "bytes") return result;
2105
+ const originalClose = result.close;
2106
+ let released;
2107
+ const close = () => {
2108
+ released ??= Promise.resolve().then(originalClose).then(() => {
2109
+ opened.delete(close);
2110
+ }).catch((error) => {
2111
+ released = void 0;
2112
+ throw error;
2113
+ });
2114
+ return released;
2115
+ };
2116
+ opened.add(close);
2117
+ if (signal.aborted) {
2118
+ await close();
2119
+ throw new FileAccessError("unavailable", 503);
2120
+ }
2121
+ const body = (async function* () {
2122
+ try {
2123
+ yield* result.body;
2124
+ } finally {
2125
+ await close();
2126
+ }
2127
+ })();
2128
+ return {
2129
+ ...result,
2130
+ body,
2131
+ close
2132
+ };
2133
+ } finally {
2134
+ pending.delete(work);
2135
+ }
2136
+ }
2137
+ });
2138
+ ctx.client.registerMethod({
2139
+ name: "referenceUrls",
2140
+ session: { kind: "read" },
2141
+ params: ReferenceUrlsParamsSchema,
2142
+ result: ReferenceUrlsResultSchema,
2143
+ async handle(params, call) {
2144
+ const operation = AbortSignal.any([
2145
+ signal,
2146
+ call.signal,
2147
+ AbortSignal.timeout(1e4)
2148
+ ]);
2149
+ const work = referenceUrls(params.uris, operation, async (uri, signal) => {
2150
+ const result = await read({ uri }, {
2151
+ method: "HEAD",
2152
+ signal
2153
+ });
2154
+ if (result.kind !== "head" || !result.metadata) throw new FileAccessError("unavailable", 503);
2155
+ return result.metadata.referenceKind === "current" ? result.metadata.fingerprint : result.metadata.fileId;
2156
+ }, (uri, expectedFingerprint) => ctx.client.ticketUrl("referenceBytes", {
2157
+ uri,
2158
+ expectedFingerprint
2159
+ }));
2160
+ pending.add(work);
2161
+ try {
2162
+ return await work;
2163
+ } finally {
2164
+ pending.delete(work);
2165
+ }
2166
+ }
2167
+ });
2168
+ return publishedFormatter;
2169
+ }
2170
+ //#endregion
2171
+ //#region src/references/resolve.ts
2172
+ function decode(path, style) {
2173
+ if (/%2f/i.test(path) || style === "windows" && /%5c/i.test(path)) throw new FileAccessError("invalid-path", 400);
2174
+ try {
2175
+ return decodeURIComponent(path);
2176
+ } catch {
2177
+ throw new FileAccessError("invalid-path", 400);
2178
+ }
2179
+ }
2180
+ function filePath(value, style) {
2181
+ if (value.includes("\\")) throw new FileAccessError("invalid-file-uri", 400);
2182
+ const match = /^file:(?:\/\/([^/]*))?(\/.*)$/i.exec(value);
2183
+ if (!match || match[2].startsWith("//")) throw new FileAccessError("invalid-file-uri", 400);
2184
+ const authority = match[1] ?? "";
2185
+ if (authority && !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/i.test(authority)) throw new FileAccessError("invalid-file-uri", 400);
2186
+ const path = decode(match[2], style);
2187
+ if (!authority || authority.toLowerCase() === "localhost") {
2188
+ if (/^\/[a-z]:[/]/i.test(path)) {
2189
+ if (style === "posix") throw new FileAccessError("platform-mismatch", 400);
2190
+ return path.slice(1);
2191
+ }
2192
+ if (style === "windows") throw new FileAccessError("ambiguous-path", 400);
2193
+ return path;
2194
+ }
2195
+ if (style === "posix") throw new FileAccessError("unsupported-file-authority", 400);
2196
+ if (!/^\/[^/]+(?:\/|$)/.test(path)) throw new FileAccessError("invalid-file-uri", 400);
2197
+ return `\\\\${authority}${path.replaceAll("/", "\\")}`;
2198
+ }
2199
+ function resolveDestination(destination, origin) {
2200
+ if (new TextEncoder().encode(destination).length > 131072) throw new FileAccessError("too-large", 413);
2201
+ if (destination === "" || destination.startsWith("#")) return { kind: "passthrough" };
2202
+ checkPathText(destination);
2203
+ const hash = destination.indexOf("#"), fragment = hash >= 0 ? destination.slice(hash + 1) : void 0;
2204
+ const path = hash >= 0 ? destination.slice(0, hash) : destination;
2205
+ const suffix = fragment === void 0 ? {} : { fragment };
2206
+ if (path.startsWith("gfs:")) {
2207
+ const parsed = parseReference(path, origin.gatewayId);
2208
+ return {
2209
+ kind: "file",
2210
+ uri: parsed.kind === "current" ? currentReference(parsed.gatewayId, parsed.target.pathStyle, parsed.target.absolutePath) : attachmentReference(parsed.gatewayId, parsed.reference),
2211
+ ...suffix
2212
+ };
2213
+ }
2214
+ if (!(/^[a-z]:/i.test(path) || path.startsWith("\\\\")) && (path.startsWith("//") || /^[a-z][a-z0-9+.-]*:/i.test(path) && !/^file:/i.test(path))) return { kind: "passthrough" };
2215
+ if ((path.startsWith("\\\\?\\") ? path.slice(4) : path).includes("?")) throw new FileAccessError("unsupported-query", 400);
2216
+ const absolute = nativeAbsolute(/^file:/i.test(path) ? filePath(path, origin.pathStyle) : decode(path, origin.pathStyle), origin.pathStyle, origin.baseDirectory);
2217
+ return {
2218
+ kind: "file",
2219
+ uri: currentReference(origin.gatewayId, origin.pathStyle, absolute),
2220
+ ...suffix
2221
+ };
2222
+ }
2223
+ //#endregion
2224
+ //#region src/references/resolution.ts
2225
+ const ReferenceOriginSchema = z.discriminatedUnion("kind", [
2226
+ z.strictObject({
2227
+ kind: z.literal("message"),
2228
+ sessionId: z.string().min(1),
2229
+ historyGeneration: z.number().int().nonnegative(),
2230
+ messageId: z.string().min(1)
2231
+ }),
2232
+ z.strictObject({
2233
+ kind: z.literal("live"),
2234
+ sessionId: z.string().min(1),
2235
+ processEpoch: z.string().min(1),
2236
+ streamEpoch: z.string().min(1)
2237
+ }),
2238
+ z.strictObject({
2239
+ kind: z.literal("document"),
2240
+ uri: z.string().max(393400)
2241
+ })
2242
+ ]);
2243
+ const ResolveReferencesInputSchema = z.strictObject({
2244
+ origin: ReferenceOriginSchema,
2245
+ items: z.array(z.strictObject({
2246
+ id: z.string().min(1).max(256),
2247
+ destination: z.string(),
2248
+ usage: z.enum(["link", "image"])
2249
+ })).min(1).max(64)
2250
+ }).refine((input) => new TextEncoder().encode(JSON.stringify(input)).length <= 1048576, "too-large");
2251
+ const ResolveReferencesResultSchema = z.strictObject({ items: z.array(z.discriminatedUnion("kind", [
2252
+ z.strictObject({
2253
+ id: z.string(),
2254
+ kind: z.literal("file"),
2255
+ uri: z.string(),
2256
+ fragment: z.string().optional()
2257
+ }),
2258
+ z.strictObject({
2259
+ id: z.string(),
2260
+ kind: z.literal("passthrough")
2261
+ }),
2262
+ z.strictObject({
2263
+ id: z.string(),
2264
+ kind: z.literal("error"),
2265
+ code: z.string(),
2266
+ message: z.string()
2267
+ })
2268
+ ])) });
2269
+ const OriginSchema = z.strictObject({
2270
+ gatewayId: GatewayIdSchema,
2271
+ pathStyle: z.enum(["posix", "windows"]),
2272
+ baseDirectory: z.string().optional()
2273
+ });
2274
+ function registerReferenceResolution(ctx) {
2275
+ const states = ctx.services.get("owner-session-context");
2276
+ const reading = ctx.services.get("owner-context-reading");
2277
+ const reader = ctx.services.get("host-file-reader");
2278
+ const identity = ctx.services.get("workspace-roots").availability();
2279
+ if (!identity.available) return;
2280
+ const gatewayId = identity.gatewayId;
2281
+ ctx.onDispose(states.register({
2282
+ key: "file-origin",
2283
+ order: 100,
2284
+ async prepare(call) {
2285
+ const cwd = ctx.services.find("session-working-directory")?.readSnapshot(call.snapshot);
2286
+ return {
2287
+ revision: cwd?.revision ?? 0,
2288
+ data: {
2289
+ gatewayId,
2290
+ pathStyle: reader.pathStyle,
2291
+ ...cwd ? { baseDirectory: cwd.absolutePath } : {}
2292
+ }
2293
+ };
2294
+ }
2295
+ }));
2296
+ const cache = /* @__PURE__ */ new Map();
2297
+ let cacheBytes = 0;
2298
+ ctx.onDispose(() => {
2299
+ cache.clear();
2300
+ cacheBytes = 0;
2301
+ });
2302
+ async function originOf(origin, signal) {
2303
+ if (origin.kind === "document") {
2304
+ const ref = parseReference(origin.uri, gatewayId);
2305
+ if (ref.kind === "attachment") return {
2306
+ gatewayId,
2307
+ pathStyle: reader.pathStyle
2308
+ };
2309
+ if (ref.target.pathStyle !== reader.pathStyle) throw new FileAccessError("platform-mismatch", 400);
2310
+ return {
2311
+ gatewayId,
2312
+ pathStyle: reader.pathStyle,
2313
+ baseDirectory: nativeParent(ref.target.absolutePath, reader.pathStyle)
2314
+ };
2315
+ }
2316
+ const entry = (await reading.read(origin, signal)).find((entry) => entry.key === "file-origin");
2317
+ const parsed = OriginSchema.safeParse(entry?.data);
2318
+ if (!parsed.success) throw new FileAccessError("origin-unavailable", 409);
2319
+ if (parsed.data.gatewayId !== gatewayId) throw new FileAccessError("gateway-mismatch", 403);
2320
+ if (parsed.data.pathStyle !== reader.pathStyle) throw new FileAccessError("platform-mismatch", 400);
2321
+ return parsed.data;
2322
+ }
2323
+ ctx.client.registerMethod({
2324
+ name: "resolveReferences",
2325
+ session: { kind: "read" },
2326
+ params: ResolveReferencesInputSchema,
2327
+ result: ResolveReferencesResultSchema,
2328
+ async handle(input, call) {
2329
+ const signal = AbortSignal.any([
2330
+ call.signal,
2331
+ ctx.signal,
2332
+ AbortSignal.timeout(1e4)
2333
+ ]);
2334
+ const failure = (id, error) => {
2335
+ const code = error && typeof error === "object" && "code" in error ? String(error.code).slice(0, 64) : signal.aborted ? "deadline-exceeded" : "stale-origin";
2336
+ return {
2337
+ id,
2338
+ kind: "error",
2339
+ code,
2340
+ message: `File reference resolution failed: ${code}`
2341
+ };
2342
+ };
2343
+ let origin;
2344
+ try {
2345
+ origin = await new Promise((resolve, reject) => {
2346
+ const abort = () => reject(signal.reason);
2347
+ signal.addEventListener("abort", abort, { once: true });
2348
+ if (signal.aborted) abort();
2349
+ originOf(input.origin, signal).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
2350
+ });
2351
+ signal.throwIfAborted();
2352
+ } catch (error) {
2353
+ return { items: input.items.map((item) => failure(item.id, error)) };
2354
+ }
2355
+ let responseBytes = 32;
2356
+ const errorReserve = input.items.reduce((size, item) => size + new TextEncoder().encode(JSON.stringify(failure(item.id, { code: "x".repeat(64) }))).length + 1, 0);
2357
+ return { items: input.items.map((item) => {
2358
+ try {
2359
+ signal.throwIfAborted();
2360
+ const key = JSON.stringify([origin, item.destination]);
2361
+ const value = cache.get(key)?.value ?? resolveDestination(item.destination, origin);
2362
+ const result = {
2363
+ id: item.id,
2364
+ ...value
2365
+ }, size = new TextEncoder().encode(JSON.stringify(result)).length + 1;
2366
+ if (responseBytes + size > 1048576 - errorReserve) throw new FileAccessError("too-large", 413);
2367
+ responseBytes += size;
2368
+ if (!cache.has(key)) {
2369
+ const heldSize = new TextEncoder().encode(key).length + size;
2370
+ while (cache.size >= 256 || cacheBytes + heldSize > 4194304 && cache.size) {
2371
+ const oldest = cache.keys().next().value;
2372
+ cacheBytes -= cache.get(oldest).size;
2373
+ cache.delete(oldest);
2374
+ }
2375
+ cache.set(key, {
2376
+ value,
2377
+ size: heldSize
2378
+ });
2379
+ cacheBytes += heldSize;
2380
+ }
2381
+ return result;
2382
+ } catch (error) {
2383
+ return failure(item.id, error);
2384
+ }
2385
+ }) };
2386
+ }
2387
+ });
2388
+ }
2389
+ //#endregion
1268
2390
  //#region src/index.ts
1269
- /** Workspace browsing provider registration; never contributes Agent tools or approvals. */
1270
- /** Registers one activation's provider and awaited shutdown drain. */
1271
- function registerFileExplorer(ctx) {
2391
+ function registerFileExplorer(ctx, referenceFormatter, reader = ctx.services.get("host-file-reader")) {
1272
2392
  const roots = ctx.services.get("workspace-roots");
1273
2393
  const identity = roots.availability();
1274
- if (!identity.available) throw new FileAccessError("unavailable", 503);
2394
+ if (!identity.available) throw new FileAccessError$1("unavailable", 503);
2395
+ const formatter = referenceFormatter ?? createReferenceFormatter(identity.gatewayId, ctx.signal, () => !ctx.signal.aborted);
1275
2396
  const provider = createFileExplorer({
1276
2397
  files: ctx.services.get("client-files"),
1277
- referenceFormatter: ctx.services.get("file-reference-formatter"),
2398
+ referenceFormatter: formatter,
2399
+ performance: ctx.performance,
1278
2400
  roots,
1279
2401
  signal: ctx.signal,
1280
2402
  instanceId: identity.instanceId
@@ -1285,15 +2407,20 @@ function registerFileExplorer(ctx) {
1285
2407
  payload: FilesChangedSchema
1286
2408
  });
1287
2409
  const announced = /* @__PURE__ */ new WeakSet();
2410
+ const publication = (value) => {
2411
+ if (announced.has(value) || value.status !== "succeeded" && !value.error?.details?.destinationCommitted) return false;
2412
+ announced.add(value);
2413
+ return true;
2414
+ };
2415
+ const announce = (value, workspaceId) => {
2416
+ if (publication(value) && !ctx.signal.aborted) changed.emit({ workspaces: [workspaceId] });
2417
+ };
1288
2418
  async function mutate(items, request, work, workspace) {
1289
2419
  const workspaces = /* @__PURE__ */ new Set();
1290
2420
  try {
1291
2421
  return await fileCollection(items, AbortSignal.any([ctx.signal, request]), async (item) => {
1292
2422
  const value = await work(item, request);
1293
- if (!announced.has(value) && (value.status === "succeeded" || value.error?.details?.destinationCommitted)) {
1294
- announced.add(value);
1295
- workspaces.add(workspace(item));
1296
- }
2423
+ if (publication(value)) workspaces.add(workspace(item));
1297
2424
  return value;
1298
2425
  });
1299
2426
  } finally {
@@ -1306,6 +2433,12 @@ function registerFileExplorer(ctx) {
1306
2433
  await drain();
1307
2434
  unbind();
1308
2435
  });
2436
+ ctx.client.registerMethod({
2437
+ name: "observe",
2438
+ params: ObserveParamsSchema,
2439
+ result: ObserveResultSchema,
2440
+ handle: (params, call) => observeReferences(reader, formatter, identity.gatewayId, params, AbortSignal.any([ctx.signal, call.signal]))
2441
+ });
1309
2442
  ctx.client.registerMethod({
1310
2443
  name: "roots",
1311
2444
  params: RootsParamsSchema,
@@ -1328,13 +2461,21 @@ function registerFileExplorer(ctx) {
1328
2461
  name: "mkdir",
1329
2462
  params: MkdirParamsSchema,
1330
2463
  result: OperationResultSchema,
1331
- handle: (params, call) => provider.mkdir(params, call.signal)
2464
+ handle: async (params, call) => {
2465
+ const result = await provider.mkdir(params, call.signal);
2466
+ announce(result, params.target.workspaceId);
2467
+ return result;
2468
+ }
1332
2469
  });
1333
2470
  ctx.client.registerMethod({
1334
2471
  name: "rename",
1335
2472
  params: RenameParamsSchema,
1336
2473
  result: OperationResultSchema,
1337
- handle: (params, call) => provider.rename(params, call.signal)
2474
+ handle: async (params, call) => {
2475
+ const result = await provider.rename(params, call.signal);
2476
+ announce(result, params.source.workspaceId);
2477
+ return result;
2478
+ }
1338
2479
  });
1339
2480
  ctx.client.registerMethod({
1340
2481
  name: "moveFiles",
@@ -1367,21 +2508,37 @@ function registerFileExplorer(ctx) {
1367
2508
  params: FileBytesParamsSchema,
1368
2509
  result: OperationResultSchema,
1369
2510
  metadata: FileEntrySchema.optional(),
1370
- handle: (params, call) => provider.fileBytes(params, call)
2511
+ handle: async (params, call) => {
2512
+ const result = await provider.fileBytes(params, call);
2513
+ if (call.method === "PUT" && result.kind === "json") announce(result.result, params.target.workspaceId);
2514
+ return result;
2515
+ }
1371
2516
  });
1372
2517
  const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
1373
- if (existsSync(module)) ctx.client.registerUi({ module });
2518
+ if (existsSync(module)) ctx.client.registerPackageFiles({
2519
+ root: dirname(module),
2520
+ entry: "ui.js"
2521
+ });
1374
2522
  }
1375
2523
  const plugin = {
1376
2524
  name: "@eum-agent/file-explorer",
1377
- dependencies: { "@eum-agent/file-references": "1.1.0" },
1378
2525
  requires: [
1379
2526
  "client-files",
1380
2527
  "workspace-roots",
1381
2528
  "work-lifecycle",
1382
- "file-reference-formatter"
2529
+ "host-file-reader",
2530
+ "attachment-references",
2531
+ "owner-session-context",
2532
+ "owner-context-reading"
1383
2533
  ],
1384
- apply: registerFileExplorer
2534
+ optionalServices: ["session-working-directory"],
2535
+ provides: ["file-reference-formatter"],
2536
+ apply(ctx) {
2537
+ const reader = createScheduledReader(ctx.services.get("host-file-reader"), ctx.signal, ctx.performance);
2538
+ const formatter = registerFileReferences(ctx, reader);
2539
+ registerReferenceResolution(ctx);
2540
+ if (ctx.services.get("workspace-roots").availability().available) registerFileExplorer(ctx, formatter, reader);
2541
+ }
1385
2542
  };
1386
2543
  //#endregion
1387
2544
  export { plugin as default, registerFileExplorer };