tmux-ide 2.9.10 → 2.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/bin/cli.js +4321 -2596
  2. package/package.json +1 -1
  3. package/packages/contracts/src/index.ts +4 -0
  4. package/packages/contracts/src/pane-stream.ts +72 -0
  5. package/packages/contracts/src/terminal-delivery-binary-chunk.ts +55 -0
  6. package/packages/contracts/src/terminal-delivery.ts +17 -2
  7. package/packages/contracts/src/terminal-graphics.ts +68 -0
  8. package/packages/contracts/src/terminal-projection.ts +153 -0
  9. package/packages/core/src/fixtures/terminal-projection-vectors.json +585 -0
  10. package/packages/core/src/index.ts +2 -0
  11. package/packages/core/src/terminal-delivery-binary.ts +160 -0
  12. package/packages/core/src/terminal-delivery.ts +371 -16
  13. package/packages/core/src/terminal-projection-vectors.mjs +82 -0
  14. package/packages/core/src/terminal-projection.ts +476 -0
  15. package/packages/core/src/terminal-replica-hash-cache.ts +8 -1
  16. package/packages/core/src/terminal-replica.ts +1 -1
  17. package/packages/daemon/dist/lib/daemon-embed.js +39 -3
  18. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +1 -0
  19. package/packages/daemon/dist/lib/tmux-server-owner.js +1 -0
  20. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  21. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  22. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  23. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  24. package/packages/daemon/dist/terminal/graphics/local-image-owner.js +330 -0
  25. package/packages/daemon/dist/terminal/graphics/local-image-store.js +255 -0
  26. package/packages/daemon/dist/terminal/mirror/mirror-service.js +12 -2
  27. package/packages/daemon/dist/terminal/mirror/session-channel.js +46 -23
  28. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +190 -19
  29. package/packages/daemon/dist/terminal/pane-stream/runtime.js +1 -0
  30. package/packages/daemon/dist/terminal/session-runtime/registry.js +19 -6
  31. package/packages/daemon/dist/terminal/session-runtime/terminal-delivery-hub.js +146 -16
  32. package/packages/daemon/dist/terminal/session-runtime/terminal-projection-delivery.js +32 -0
  33. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +95 -36
  34. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +5 -0
  35. package/packages/daemon/dist/terminal/session-runtime/transport-binding.js +2 -2
  36. package/packages/daemon/dist/tui/mirror/open-tui-workspace-runtime-port.js +4 -0
  37. package/packages/daemon/dist/tui/mirror/runtime/application-generation-starter.js +16 -1
  38. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +13 -0
  39. package/packages/daemon/dist/tui/mirror/runtime/application-machine-navigation.js +12 -4
  40. package/packages/daemon/dist/tui/mirror/runtime/application-retained-agent.js +18 -0
  41. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +90 -5
  42. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-workspace.jsx +13 -1
  43. package/packages/daemon/dist/tui/mirror/runtime/open-tui-generation-host.js +2 -2
  44. package/packages/daemon/dist/tui/mirror/runtime/renderer-probe.js +195 -0
  45. package/packages/daemon/dist/tui/mirror/runtime/runtime-layout-presentation.js +6 -3
  46. package/packages/daemon/dist/tui/mirror/runtime/select-terminal-pane.js +7 -2
  47. package/packages/daemon/dist/tui/mirror/runtime/terminal-fast-lane-renderer-adapter.js +6 -0
  48. package/packages/daemon/dist/tui/mirror/runtime/terminal-selection-waiter.js +36 -0
  49. package/packages/daemon/dist/tui/mirror/semantic-pane-render-source.js +4 -0
  50. package/packages/daemon/src/lib/daemon-embed.ts +38 -2
  51. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +3 -0
  52. package/packages/daemon/src/lib/tmux-server-owner.ts +3 -0
  53. package/packages/daemon/src/terminal/graphics/local-image-owner.ts +346 -0
  54. package/packages/daemon/src/terminal/graphics/local-image-store.ts +286 -0
  55. package/packages/daemon/src/terminal/mirror/mirror-service.ts +19 -2
  56. package/packages/daemon/src/terminal/mirror/session-channel.ts +57 -9
  57. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +248 -16
  58. package/packages/daemon/src/terminal/pane-stream/runtime.ts +3 -0
  59. package/packages/daemon/src/terminal/session-runtime/registry.ts +25 -3
  60. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +1 -1
  61. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-hub.ts +216 -22
  62. package/packages/daemon/src/terminal/session-runtime/terminal-delivery-observation-identity.ts +7 -4
  63. package/packages/daemon/src/terminal/session-runtime/terminal-projection-delivery.ts +59 -0
  64. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +102 -44
  65. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +6 -0
  66. package/packages/daemon/src/terminal/session-runtime/transport-binding.ts +3 -0
  67. package/packages/daemon/src/tui/mirror/open-tui-workspace-runtime-port.ts +6 -0
  68. package/packages/daemon/src/tui/mirror/runtime/application-generation-starter.ts +17 -1
  69. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +15 -0
  70. package/packages/daemon/src/tui/mirror/runtime/application-machine-navigation.ts +18 -4
  71. package/packages/daemon/src/tui/mirror/runtime/application-retained-agent.ts +29 -0
  72. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +89 -6
  73. package/packages/daemon/src/tui/mirror/runtime/application-terminal-workspace.tsx +20 -1
  74. package/packages/daemon/src/tui/mirror/runtime/open-tui-generation-host.ts +2 -2
  75. package/packages/daemon/src/tui/mirror/runtime/renderer-probe.ts +257 -0
  76. package/packages/daemon/src/tui/mirror/runtime/runtime-layout-presentation.ts +7 -4
  77. package/packages/daemon/src/tui/mirror/runtime/select-terminal-pane.ts +9 -1
  78. package/packages/daemon/src/tui/mirror/runtime/terminal-fast-lane-renderer-adapter.ts +15 -0
  79. package/packages/daemon/src/tui/mirror/runtime/terminal-selection-waiter.ts +36 -0
  80. package/packages/daemon/src/tui/mirror/semantic-pane-render-source.ts +4 -0
  81. package/packages/daemon-client/src/pane-stream-client.ts +92 -1
@@ -0,0 +1,330 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { link, lstat, mkdir, open, readdir, realpath, rename, rmdir, unlink, } from "node:fs/promises";
4
+ import { basename, join } from "node:path";
5
+ import { z } from "zod";
6
+ import { LocalImageStore } from "./local-image-store.js";
7
+ const OwnerSchema = z
8
+ .object({
9
+ generation: z.uuid(),
10
+ pid: z.number().int().positive().max(2147483647),
11
+ startedAt: z.iso.datetime(),
12
+ })
13
+ .strict();
14
+ const FileSchema = z
15
+ .object({
16
+ dev: z.number().nonnegative(),
17
+ ino: z.number().nonnegative(),
18
+ mode: z.number().int(),
19
+ size: z.number().nonnegative(),
20
+ mtimeMs: z.number(),
21
+ ctimeMs: z.number(),
22
+ })
23
+ .strict();
24
+ const ManifestSchema = z
25
+ .object({
26
+ version: z.literal(1),
27
+ owner: OwnerSchema,
28
+ directory: FileSchema,
29
+ store: z
30
+ .object({ name: z.string().regex(/^local-images-[A-Za-z0-9]+$/u), identity: FileSchema })
31
+ .strict(),
32
+ files: z
33
+ .array(z.object({ name: z.string().regex(/^[a-f0-9]{64}$/u), identity: FileSchema }).strict())
34
+ .max(512),
35
+ })
36
+ .strict();
37
+ const record = (s) => ({
38
+ dev: s.dev,
39
+ ino: s.ino,
40
+ mode: s.mode,
41
+ size: s.size,
42
+ mtimeMs: s.mtimeMs,
43
+ ctimeMs: s.ctimeMs,
44
+ });
45
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino;
46
+ const privateDir = (s) => s.isDirectory() && s.uid === process.getuid?.() && (s.mode & 0o077) === 0;
47
+ const privateFile = (s) => s.isFile() && s.uid === process.getuid?.() && (s.mode & 0o077) === 0;
48
+ async function directory(path, expected) {
49
+ const stat = await lstat(path);
50
+ if (!privateDir(stat) || (expected && !same(stat, expected)))
51
+ throw new Error("Local image owner directory replaced");
52
+ return stat;
53
+ }
54
+ async function readManifest(path) {
55
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
56
+ try {
57
+ const stat = await file.stat();
58
+ if (!privateFile(stat) || stat.size > 256 * 1024)
59
+ throw new Error("Invalid local image manifest file");
60
+ const bytes = Buffer.alloc(stat.size);
61
+ let offset = 0;
62
+ while (offset < bytes.length) {
63
+ const read = await file.read(bytes, offset, bytes.length - offset, offset);
64
+ if (!read.bytesRead)
65
+ throw new Error("Truncated local image manifest");
66
+ offset += read.bytesRead;
67
+ }
68
+ const current = await lstat(path);
69
+ if (!same(stat, current) || current.size !== stat.size || current.mtimeMs !== stat.mtimeMs)
70
+ throw new Error("Local image manifest replaced");
71
+ const manifest = ManifestSchema.parse(JSON.parse(bytes.toString("utf8")));
72
+ if (new Set(manifest.files.map((f) => f.name)).size !== manifest.files.length)
73
+ throw new Error("Duplicate local image manifest file");
74
+ return { manifest, identity: stat };
75
+ }
76
+ finally {
77
+ await file.close();
78
+ }
79
+ }
80
+ /** Per-generation lifecycle wrapper. The lease is never published before its
81
+ * owned file identity is persisted. A crash before journal publication leaves
82
+ * an unrecorded file, which cleanup deliberately preserves rather than guesses.
83
+ */
84
+ export class LocalImageOwner {
85
+ path;
86
+ identity;
87
+ store;
88
+ root;
89
+ rootIdentity;
90
+ pathIdentity;
91
+ storeIdentity;
92
+ #tail = Promise.resolve();
93
+ #disposal;
94
+ #manifestIdentity;
95
+ constructor(path, identity, store, root, rootIdentity, pathIdentity, storeIdentity) {
96
+ this.path = path;
97
+ this.identity = identity;
98
+ this.store = store;
99
+ this.root = root;
100
+ this.rootIdentity = rootIdentity;
101
+ this.pathIdentity = pathIdentity;
102
+ this.storeIdentity = storeIdentity;
103
+ }
104
+ static async create(options) {
105
+ const identity = OwnerSchema.parse({
106
+ generation: options.generation,
107
+ pid: options.pid,
108
+ startedAt: options.startedAt,
109
+ });
110
+ const rootIdentity = await directory(options.root);
111
+ const root = await realpath(options.root);
112
+ await directory(root, rootIdentity);
113
+ const path = join(root, `local-images-${identity.generation}`);
114
+ await mkdir(path, { mode: 0o700 }); // Exclusive: never adopt another instance directory.
115
+ const pathIdentity = await directory(path);
116
+ const store = await LocalImageStore.create({
117
+ parent: path,
118
+ generation: identity.generation,
119
+ ...options.store,
120
+ });
121
+ const owner = new LocalImageOwner(path, identity, store, root, rootIdentity, pathIdentity, await directory(store.directory));
122
+ try {
123
+ await owner.#persist();
124
+ }
125
+ catch (error) {
126
+ await store.dispose().catch(() => { });
127
+ throw error;
128
+ }
129
+ return owner;
130
+ }
131
+ #serial(run) {
132
+ const result = this.#tail.then(run);
133
+ this.#tail = result.catch(() => { });
134
+ return result;
135
+ }
136
+ async #check() {
137
+ await directory(this.root, this.rootIdentity);
138
+ await directory(this.path, this.pathIdentity);
139
+ }
140
+ async #persist() {
141
+ await this.#check();
142
+ const files = await this.store.ownedFiles();
143
+ const manifest = {
144
+ version: 1,
145
+ owner: this.identity,
146
+ directory: record(this.pathIdentity),
147
+ store: { name: basename(this.store.directory), identity: record(this.storeIdentity) },
148
+ files: files.map((f) => ({ name: basename(f.path), identity: record(f.identity) })),
149
+ };
150
+ const encoded = JSON.stringify(ManifestSchema.parse(manifest));
151
+ const path = join(this.path, "owner.json");
152
+ if (this.#manifestIdentity) {
153
+ const current = await readManifest(path);
154
+ if (JSON.stringify(record(current.identity)) !== JSON.stringify(record(this.#manifestIdentity)))
155
+ throw new Error("Local image manifest replaced");
156
+ // Leases are in-memory; only the owned file set is crash-recovery data.
157
+ // Reuse its durable record after checking identity, including on shared leases.
158
+ if (JSON.stringify(current.manifest) === encoded)
159
+ return;
160
+ }
161
+ const temporary = join(this.path, `.owner-${randomUUID()}`);
162
+ const file = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
163
+ const stat = await file.stat();
164
+ try {
165
+ await file.writeFile(encoded);
166
+ await file.sync();
167
+ await this.#check();
168
+ if (!same(await lstat(temporary), stat))
169
+ throw new Error("Local image manifest staging replaced");
170
+ if (this.#manifestIdentity)
171
+ await rename(temporary, path);
172
+ else {
173
+ await link(temporary, path);
174
+ await unlink(temporary);
175
+ }
176
+ this.#manifestIdentity = await lstat(path);
177
+ if (!same(this.#manifestIdentity, stat))
178
+ throw new Error("Local image manifest publication replaced");
179
+ }
180
+ finally {
181
+ await file.close();
182
+ await this.#removeStaging(temporary, stat);
183
+ }
184
+ }
185
+ async #removeStaging(path, identity) {
186
+ await this.#check();
187
+ let remaining;
188
+ try {
189
+ remaining = await lstat(path);
190
+ }
191
+ catch (error) {
192
+ if (error.code === "ENOENT")
193
+ return;
194
+ throw error;
195
+ }
196
+ if (!remaining.isFile() || !same(remaining, identity))
197
+ throw new Error("Local image manifest cleanup refused replacement");
198
+ await unlink(path);
199
+ }
200
+ acquire(input) {
201
+ // Store admission snapshots mutable bytes synchronously and bounds queued memory.
202
+ const lease = this.store.acquire(input);
203
+ void lease.catch(() => { });
204
+ return this.#serial(async () => {
205
+ const result = await lease;
206
+ try {
207
+ await this.#persist();
208
+ }
209
+ catch (error) {
210
+ await this.store.release(result).catch(() => { });
211
+ throw error;
212
+ }
213
+ return result;
214
+ });
215
+ }
216
+ release(scope) {
217
+ return this.#serial(async () => {
218
+ const result = await this.store.release(scope);
219
+ await this.#persist();
220
+ return result;
221
+ });
222
+ }
223
+ releaseClient(scope) {
224
+ return this.#serial(async () => {
225
+ await this.store.releaseClient(scope);
226
+ await this.#persist();
227
+ });
228
+ }
229
+ dispose() {
230
+ return (this.#disposal ??= this.#serial(async () => {
231
+ await this.#check();
232
+ await this.store.dispose();
233
+ const path = join(this.path, "owner.json");
234
+ const current = await readManifest(path);
235
+ if (!this.#manifestIdentity ||
236
+ JSON.stringify(record(current.identity)) !== JSON.stringify(record(this.#manifestIdentity)))
237
+ throw new Error("Local image manifest replaced");
238
+ await unlink(path);
239
+ await rmdir(this.path);
240
+ }));
241
+ }
242
+ }
243
+ /** No directory discovery. Caller supplies the exact predecessor read under the
244
+ * canonical claim, and its existing authoritative dead-owner check. PID reuse
245
+ * or uncertainty retains files even if generation/start identity differs.
246
+ */
247
+ export async function cleanupLocalImageOwner(options) {
248
+ const owner = OwnerSchema.parse(options.owner);
249
+ const rootIdentity = await directory(options.root);
250
+ const path = join(options.root, `local-images-${owner.generation}`);
251
+ let pathIdentity;
252
+ try {
253
+ pathIdentity = await directory(path);
254
+ }
255
+ catch (error) {
256
+ if (error.code === "ENOENT")
257
+ return false;
258
+ throw error;
259
+ }
260
+ const manifestPath = join(path, "owner.json");
261
+ const { manifest, identity: manifestIdentity } = await readManifest(manifestPath);
262
+ if (JSON.stringify(manifest.owner) !== JSON.stringify(owner) ||
263
+ !same(manifest.directory, pathIdentity))
264
+ return false;
265
+ if (!(await options.proveDead(owner)))
266
+ return false;
267
+ try {
268
+ process.kill(owner.pid, 0);
269
+ return false;
270
+ }
271
+ catch (error) {
272
+ if (error.code !== "ESRCH")
273
+ return false;
274
+ }
275
+ await directory(options.root, rootIdentity);
276
+ await directory(path, pathIdentity);
277
+ const storePath = join(path, manifest.store.name);
278
+ let storePresent = true;
279
+ try {
280
+ await directory(storePath, manifest.store.identity);
281
+ }
282
+ catch (error) {
283
+ if (error.code !== "ENOENT")
284
+ throw error;
285
+ storePresent = false;
286
+ }
287
+ for (const entry of storePresent ? manifest.files : []) {
288
+ await directory(options.root, rootIdentity);
289
+ await directory(path, pathIdentity);
290
+ await directory(storePath, manifest.store.identity);
291
+ const file = join(storePath, entry.name);
292
+ let stat;
293
+ try {
294
+ stat = await lstat(file);
295
+ }
296
+ catch (error) {
297
+ if (error.code === "ENOENT")
298
+ continue;
299
+ throw error;
300
+ }
301
+ if (!privateFile(stat) || JSON.stringify(record(stat)) !== JSON.stringify(entry.identity))
302
+ return false;
303
+ await unlink(file);
304
+ }
305
+ // Unknown/staging/replaced files make rmdir fail; none are removed speculatively.
306
+ try {
307
+ if (storePresent)
308
+ await rmdir(storePath);
309
+ }
310
+ catch (error) {
311
+ if (error.code === "ENOTEMPTY")
312
+ return false;
313
+ throw error;
314
+ }
315
+ const current = await readManifest(manifestPath);
316
+ if (JSON.stringify(record(current.identity)) !== JSON.stringify(record(manifestIdentity)))
317
+ return false;
318
+ if ((await readdir(path)).some((name) => name !== "owner.json"))
319
+ return false;
320
+ await unlink(manifestPath);
321
+ try {
322
+ await rmdir(path);
323
+ }
324
+ catch (error) {
325
+ if (error.code === "ENOTEMPTY")
326
+ return false;
327
+ throw error;
328
+ }
329
+ return true;
330
+ }
@@ -0,0 +1,255 @@
1
+ import { randomUUID, webcrypto } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { chmod, link, lstat, mkdtemp, open, realpath, rmdir, unlink } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ const IMAGE_LIMIT = 64 * 1024 * 1024;
6
+ const same = (a, b) => a.dev === b.dev && a.ino === b.ino;
7
+ const privateDirectory = (s) => s.isDirectory() && s.uid === process.getuid?.() && (s.mode & 0o077) === 0;
8
+ const bounded = (value, max) => Number.isSafeInteger(value) && value > 0 && value <= max;
9
+ const identity = (value) => value.length > 0 &&
10
+ value.length <= 512 &&
11
+ ![...value].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127);
12
+ /** Immutable copy-reduced transport files, not a persistent asset cache. Only owner
13
+ * metadata crosses this API. A live daemon expires crashed clients' leases; its
14
+ * owner must clean abandoned instance directories after a daemon process crash.
15
+ * The private parent is trusted: Node has no descriptor-relative unlink primitive.
16
+ */
17
+ export class LocalImageStore {
18
+ directory;
19
+ generation;
20
+ directoryIdentity;
21
+ #entries = new Map();
22
+ #leases = new Map();
23
+ #maxBytes;
24
+ #maxFiles;
25
+ #maxLeases;
26
+ #ttl;
27
+ #now;
28
+ #timer;
29
+ #tail = Promise.resolve();
30
+ #bytes = 0;
31
+ #pendingBytes = 0;
32
+ #pending = 0;
33
+ #closed = false;
34
+ constructor(directory, generation, directoryIdentity, options) {
35
+ this.directory = directory;
36
+ this.generation = generation;
37
+ this.directoryIdentity = directoryIdentity;
38
+ this.#maxBytes = options.maxBytes ?? 256 * 1024 * 1024;
39
+ this.#maxFiles = options.maxFiles ?? 512;
40
+ this.#maxLeases = options.maxLeases ?? 1024;
41
+ this.#ttl = options.ttlMs ?? 30_000;
42
+ this.#now = options.now ?? Date.now;
43
+ this.#timer = setInterval(() => void this.sweep().catch(() => { }), Math.min(this.#ttl, 1000));
44
+ this.#timer.unref();
45
+ }
46
+ static async create(options) {
47
+ if (!identity(options.generation) ||
48
+ !bounded(options.maxBytes ?? 256 * 1024 * 1024, 256 * 1024 * 1024) ||
49
+ !bounded(options.maxFiles ?? 512, 512) ||
50
+ !bounded(options.maxLeases ?? 1024, 1024) ||
51
+ !bounded(options.ttlMs ?? 30_000, 60_000))
52
+ throw new Error("Invalid local image store bounds");
53
+ const parentIdentity = await lstat(options.parent);
54
+ if (!privateDirectory(parentIdentity))
55
+ throw new Error("Local image parent is not private");
56
+ const parent = await realpath(options.parent);
57
+ if (!same(parentIdentity, await lstat(parent)))
58
+ throw new Error("Local image parent replaced");
59
+ const directory = await mkdtemp(join(parent, "local-images-"));
60
+ await chmod(directory, 0o700);
61
+ const stat = await lstat(directory);
62
+ if (!privateDirectory(stat))
63
+ throw new Error("Local image directory is not private");
64
+ return new LocalImageStore(directory, options.generation, stat, options);
65
+ }
66
+ #serial(run) {
67
+ const result = this.#tail.then(run);
68
+ this.#tail = result.catch(() => { });
69
+ return result;
70
+ }
71
+ async #checkDirectory() {
72
+ const stat = await lstat(this.directory);
73
+ if (!privateDirectory(stat) || !same(stat, this.directoryIdentity))
74
+ throw new Error("Local image directory replaced");
75
+ }
76
+ #scope(scope) {
77
+ if (scope.generation !== this.generation || !identity(scope.client))
78
+ throw new Error("Local image scope mismatch");
79
+ }
80
+ async #checkFile(entry) {
81
+ await this.#checkDirectory();
82
+ const stat = await lstat(entry.path);
83
+ if (!stat.isFile() ||
84
+ !same(stat, entry.identity) ||
85
+ stat.size !== entry.bytes ||
86
+ stat.mode !== entry.identity.mode ||
87
+ stat.mtimeMs !== entry.identity.mtimeMs ||
88
+ stat.ctimeMs !== entry.identity.ctimeMs)
89
+ throw new Error("Local image file replaced");
90
+ }
91
+ acquire(input) {
92
+ const { generation, client, digest: requestedDigest } = input;
93
+ this.#scope({ generation, client });
94
+ if (this.#closed ||
95
+ !/^[a-f0-9]{32}$/u.test(input.digest) ||
96
+ !bounded(input.bytes.byteLength, Math.min(IMAGE_LIMIT, this.#maxBytes)) ||
97
+ this.#pending >= this.#maxLeases ||
98
+ input.bytes.byteLength > this.#maxBytes - this.#pendingBytes)
99
+ return Promise.reject(new Error("Local image acquisition unavailable"));
100
+ // Detach caller memory before the first await; queued acquisition memory is bounded too.
101
+ const data = Uint8Array.from(input.bytes);
102
+ this.#pending++;
103
+ this.#pendingBytes += data.byteLength;
104
+ return this.#serial(async () => {
105
+ if (this.#closed)
106
+ throw new Error("Local image store closed");
107
+ await this.#expire();
108
+ await this.#checkDirectory();
109
+ if (this.#leases.size >= this.#maxLeases)
110
+ throw new Error("Local image lease bound");
111
+ const fullDigest = Buffer.from(await webcrypto.subtle.digest("SHA-256", data)).toString("hex");
112
+ const digest = fullDigest.slice(0, 32);
113
+ if (digest !== requestedDigest)
114
+ throw new Error("Local image digest mismatch");
115
+ let entry = this.#entries.get(digest);
116
+ if (entry) {
117
+ if (entry.path !== join(this.directory, fullDigest))
118
+ throw new Error("Local image digest collision");
119
+ await this.#checkFile(entry);
120
+ }
121
+ else {
122
+ if (this.#entries.size >= this.#maxFiles || data.byteLength > this.#maxBytes - this.#bytes)
123
+ throw new Error("Local image storage bound");
124
+ entry = await this.#write(fullDigest, data);
125
+ this.#entries.set(digest, entry);
126
+ this.#bytes += entry.bytes;
127
+ }
128
+ const lease = Object.freeze({
129
+ id: randomUUID(),
130
+ generation: this.generation,
131
+ client,
132
+ digest,
133
+ path: entry.path,
134
+ bytes: entry.bytes,
135
+ expiresAt: this.#now() + this.#ttl,
136
+ });
137
+ this.#leases.set(lease.id, lease);
138
+ return lease;
139
+ }).finally(() => {
140
+ this.#pending--;
141
+ this.#pendingBytes -= data.byteLength;
142
+ });
143
+ }
144
+ async #write(digest, data) {
145
+ const path = join(this.directory, digest);
146
+ const temporary = join(this.directory, `.pending-${randomUUID()}`);
147
+ const file = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
148
+ let temporaryIdentity = await file.stat();
149
+ try {
150
+ await file.writeFile(data);
151
+ await file.chmod(0o400);
152
+ temporaryIdentity = await file.stat();
153
+ await this.#checkDirectory();
154
+ const current = await lstat(temporary);
155
+ if (!same(current, temporaryIdentity) || !current.isFile())
156
+ throw new Error("Local image staging replaced");
157
+ // link is atomic and fails if a digest path already exists; never overwrite it.
158
+ await link(temporary, path);
159
+ }
160
+ finally {
161
+ await file.close();
162
+ await this.#unlinkOwned(temporary, temporaryIdentity);
163
+ }
164
+ const stat = await lstat(path);
165
+ if (!same(stat, temporaryIdentity) || !stat.isFile() || stat.size !== data.byteLength)
166
+ throw new Error("Local image publication replaced");
167
+ return { path, bytes: data.byteLength, identity: stat };
168
+ }
169
+ async #unlinkOwned(path, expected, immutable = false) {
170
+ await this.#checkDirectory();
171
+ let stat;
172
+ try {
173
+ stat = await lstat(path);
174
+ }
175
+ catch (error) {
176
+ if (error.code === "ENOENT")
177
+ return;
178
+ throw error;
179
+ }
180
+ if (!stat.isFile() ||
181
+ !same(stat, expected) ||
182
+ (immutable &&
183
+ (stat.size !== expected.size ||
184
+ stat.mode !== expected.mode ||
185
+ stat.uid !== expected.uid ||
186
+ stat.mtimeMs !== expected.mtimeMs ||
187
+ stat.ctimeMs !== expected.ctimeMs)))
188
+ throw new Error("Local image cleanup refused replacement");
189
+ await unlink(path);
190
+ }
191
+ async #collect() {
192
+ const referenced = new Set([...this.#leases.values()].map((lease) => lease.digest));
193
+ for (const [digest, entry] of this.#entries) {
194
+ if (referenced.has(digest))
195
+ continue;
196
+ // Inodes can be reused after unlink. Published files must retain their
197
+ // immutable metadata; staging links intentionally change ctime instead.
198
+ await this.#unlinkOwned(entry.path, entry.identity, true);
199
+ this.#entries.delete(digest);
200
+ this.#bytes -= entry.bytes;
201
+ }
202
+ }
203
+ async #expire() {
204
+ const now = this.#now();
205
+ for (const [id, lease] of this.#leases)
206
+ if (lease.expiresAt <= now)
207
+ this.#leases.delete(id);
208
+ await this.#collect();
209
+ }
210
+ release(scope) {
211
+ return this.#serial(async () => {
212
+ this.#scope(scope);
213
+ const lease = this.#leases.get(scope.id);
214
+ if (!lease || lease.client !== scope.client)
215
+ return false;
216
+ this.#leases.delete(scope.id);
217
+ await this.#collect();
218
+ return true;
219
+ });
220
+ }
221
+ releaseClient(scope) {
222
+ return this.#serial(async () => {
223
+ this.#scope(scope);
224
+ for (const [id, lease] of this.#leases)
225
+ if (lease.client === scope.client)
226
+ this.#leases.delete(id);
227
+ await this.#collect();
228
+ });
229
+ }
230
+ sweep() {
231
+ return this.#serial(() => this.#expire());
232
+ }
233
+ /** Bounded lifecycle manifest; no image bytes. Caller persists before publishing a lease. */
234
+ ownedFiles() {
235
+ return this.#serial(async () => {
236
+ await this.#checkDirectory();
237
+ const files = [];
238
+ for (const entry of this.#entries.values()) {
239
+ await this.#checkFile(entry);
240
+ files.push({ path: entry.path, identity: entry.identity });
241
+ }
242
+ return files;
243
+ });
244
+ }
245
+ dispose() {
246
+ this.#closed = true;
247
+ clearInterval(this.#timer);
248
+ return this.#serial(async () => {
249
+ this.#leases.clear();
250
+ await this.#collect();
251
+ await this.#checkDirectory();
252
+ await rmdir(this.directory); // Not recursive: unexpected entries must survive.
253
+ });
254
+ }
255
+ }
@@ -84,11 +84,21 @@ export class MirrorService {
84
84
  this.release(session, entry);
85
85
  }
86
86
  }
87
- async describeSessionAuthority(session) {
87
+ async describeSessionAuthority(session, expectedSemanticPaneIds) {
88
88
  const entry = await this.acquire(session);
89
89
  try {
90
90
  const identity = await entry.channel.attachedSessionIdentity();
91
- return { description: entry.channel.describe(), runtimeSessionId: identity.runtimeSessionId };
91
+ let description = entry.channel.describe();
92
+ if (expectedSemanticPaneIds?.some((id) => !description.panes.some((pane) => pane.semanticPaneId === id))) {
93
+ // A mutation receipt and fresh catalog can precede debounced mirror
94
+ // discovery. Join the verified native inventory before declaring a
95
+ // requested pane absent; never substitute receipt IDs for tmux truth.
96
+ await entry.channel.describeTrustedInventory(identity.runtimeSessionId, true);
97
+ description = entry.channel.describe();
98
+ }
99
+ if (this.disposed || entry.retired || this.channels.get(session) !== entry)
100
+ throw new Error("Mirror authority retired during description");
101
+ return { description, runtimeSessionId: identity.runtimeSessionId };
92
102
  }
93
103
  finally {
94
104
  this.release(session, entry);