@yu_robotics/remote-cli-router 1.6.219 → 1.6.221

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.
@@ -0,0 +1,704 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OutputTransfers = exports.OutputApiRejection = void 0;
7
+ const promises_1 = __importDefault(require("fs/promises"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const crypto_1 = require("crypto");
10
+ const stream_1 = require("stream");
11
+ const promises_2 = require("stream/promises");
12
+ const FileIO_1 = require("../files/FileIO");
13
+ const PrivateOutputRoot_1 = require("./PrivateOutputRoot");
14
+ const Durable_1 = require("./Durable");
15
+ const Protocol_1 = require("./Protocol");
16
+ class OutputApiRejection extends Error {
17
+ constructor() { super('File delivery was rejected.'); }
18
+ }
19
+ exports.OutputApiRejection = OutputApiRejection;
20
+ const terminal = new Set(['delivered', 'send-uncertain', 'expired', 'revoked']);
21
+ const ACTIVE_LEASE = 5 * 60_000;
22
+ const states = new Set(['queued', 'waiting-device', 'receiving', 'staged-verified', 'upload-intent', 'file-key-saved', 'send-intent', 'delivered', 'send-uncertain', 'failed', 'expired', 'revoked']);
23
+ function label(value) { return typeof value === 'string' && value.length > 0 && value.length <= 200; }
24
+ function validCard(value) {
25
+ return value === undefined || (!!value && ['intent', 'known', 'uncertain', 'unavailable'].includes(value.state)
26
+ && typeof value.uuid === 'string' && value.uuid.length > 0 && value.uuid.length <= 50
27
+ && typeof value.content === 'string' && value.content.length <= 16_384 && Number.isSafeInteger(value.firstAt)
28
+ && (value.id === undefined || (typeof value.id === 'string' && value.id.length > 0 && value.id.length <= 512))
29
+ && (value.state !== 'known' || !!value.id));
30
+ }
31
+ function validSource(value) {
32
+ return !!value && ['messageId', 'deviceId', 'openId', 'epoch'].every(key => label(value[key]))
33
+ && (value.threadId === undefined || label(value.threadId)) && Number.isSafeInteger(value.expiresAt)
34
+ && (value.notices === undefined || (typeof value.notices === 'object' && value.notices !== null
35
+ && Object.keys(value.notices).length <= 16 && Object.entries(value.notices).every(([key, intent]) => Protocol_1.OPAQUE_ID.test(key) && validCard(intent))));
36
+ }
37
+ function validState(data) {
38
+ return data.sources.every(validSource) && new Set(data.sources.map(s => s.messageId)).size === data.sources.length
39
+ && data.references.every(r => validSource(r) && (0, Protocol_1.validReference)(r.reference) && validCard(r.card)
40
+ && r.messageId === r.reference.messageId && (!r.threadId || r.threadId === r.reference.threadId))
41
+ && new Set(data.references.map(r => r.reference.id)).size === data.references.length
42
+ && new Set(data.jobs.map(j => j.id)).size === data.jobs.length
43
+ && data.jobs.every(j => {
44
+ const ref = data.references.find(r => r.reference.id === j.refId);
45
+ return Protocol_1.OPAQUE_ID.test(j.id) && Protocol_1.OPAQUE_ID.test(j.refId) && label(j.openId) && label(j.deviceId) && label(j.epoch)
46
+ && states.has(j.state) && Number.isSafeInteger(j.createdAt) && Number.isSafeInteger(j.updatedAt)
47
+ && Number.isSafeInteger(j.revision) && j.revision >= 0 && Number.isSafeInteger(j.received) && j.received >= 0
48
+ && validCard(j.card) && (j.spoolBytes === undefined || (Number.isSafeInteger(j.spoolBytes) && j.spoolBytes >= 0 && j.spoolBytes <= Protocol_1.OUTPUT_LIMITS.file))
49
+ && (j.fileKey === undefined || (typeof j.fileKey === 'string' && j.fileKey.length > 0 && j.fileKey.length <= 512))
50
+ && (!ref ? terminal.has(j.state) || j.state === 'failed' : ref.openId === j.openId && ref.deviceId === j.deviceId && ref.epoch === j.epoch);
51
+ });
52
+ }
53
+ function card(title, text, action) {
54
+ return JSON.stringify({ schema: '2.0', header: { title: { tag: 'plain_text', content: title } }, body: { elements: [
55
+ { tag: 'div', text: { tag: 'plain_text', content: text } },
56
+ ...(action ? [{ tag: 'button', type: 'default', text: { tag: 'plain_text', content: action.op === 'retry' ? 'Retry' : 'Get file' },
57
+ behaviors: [{ type: 'callback', value: action }] }] : []),
58
+ ] } });
59
+ }
60
+ async function bounded(operation, ms = 15_000) {
61
+ let timer;
62
+ try {
63
+ return await Promise.race([operation, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('External outcome unknown.')), ms); timer.unref(); })]);
64
+ }
65
+ finally {
66
+ clearTimeout(timer);
67
+ }
68
+ }
69
+ /** Durable file delivery business state is independent of card presentation. */
70
+ class OutputTransfers {
71
+ deps;
72
+ state = { version: 1, sources: [], references: [], jobs: [] };
73
+ serial = Promise.resolve();
74
+ running = new Map();
75
+ presentations = new Map();
76
+ grants = new Map();
77
+ entryWork = new Map();
78
+ timer;
79
+ stopped = false;
80
+ ticking = false;
81
+ currentTick;
82
+ healthy = true;
83
+ loading;
84
+ noticeWork = new Set();
85
+ cleanedAt = 0;
86
+ storage;
87
+ get root() { return this.storage.path; }
88
+ constructor(root, deps) {
89
+ this.deps = deps;
90
+ this.storage = new PrivateOutputRoot_1.PrivateOutputRoot(root);
91
+ }
92
+ persist() { return (0, Durable_1.durableJson)(path_1.default.join(this.root, 'state.json'), this.state, this.storage.check); }
93
+ lock(operation) {
94
+ const result = this.serial.then(async () => {
95
+ if (!this.healthy)
96
+ throw new Error('Output receipt storage is unavailable.');
97
+ this.storage.check();
98
+ try {
99
+ return await operation();
100
+ }
101
+ catch (error) {
102
+ throw error;
103
+ }
104
+ });
105
+ this.serial = result.catch(() => { });
106
+ return result;
107
+ }
108
+ async save() {
109
+ try {
110
+ await this.persist();
111
+ }
112
+ catch {
113
+ this.healthy = false;
114
+ throw new Error('Output receipt storage is unavailable.');
115
+ }
116
+ }
117
+ initialize() {
118
+ return this.loading ??= (async () => {
119
+ await this.storage.initialize();
120
+ try {
121
+ const filename = path_1.default.join(this.root, 'state.json'), stat = await promises_1.default.lstat(filename);
122
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16 * 1024 * 1024)
123
+ throw new Error('Invalid output receipts.');
124
+ const data = JSON.parse(await promises_1.default.readFile(filename, 'utf8'));
125
+ if (data.version !== 1 || !Array.isArray(data.sources) || !Array.isArray(data.references) || !Array.isArray(data.jobs)
126
+ || data.sources.length > 1024 || data.references.length > 100 || data.jobs.length > 1000
127
+ || data.references.some(r => !(0, Protocol_1.validReference)(r.reference))
128
+ || !validState(data))
129
+ throw new Error('Invalid output receipts.');
130
+ this.state = data;
131
+ }
132
+ catch (error) {
133
+ if (error.code !== 'ENOENT')
134
+ throw error;
135
+ }
136
+ for (const ref of this.state.references)
137
+ if (ref.card?.state === 'intent')
138
+ ref.card.state = 'uncertain';
139
+ for (const job of this.state.jobs) {
140
+ if (job.card?.state === 'intent')
141
+ job.card.state = 'uncertain';
142
+ if (job.state === 'send-intent')
143
+ job.state = 'send-uncertain';
144
+ if (job.state === 'upload-intent')
145
+ job.state = 'failed';
146
+ if (job.state === 'receiving') {
147
+ const ref = this.state.references.find(r => r.reference.id === job.refId);
148
+ job.state = ref && await this.hasSpool(job, ref) ? 'staged-verified' : 'queued';
149
+ job.spoolBytes = job.state === 'staged-verified' ? ref.reference.size : 0;
150
+ }
151
+ if (job.card?.id)
152
+ job.displayPending = true;
153
+ }
154
+ await this.cleanup();
155
+ await this.save();
156
+ this.timer = setInterval(() => { void this.tick().catch(() => { }); }, 2000);
157
+ this.timer.unref();
158
+ })();
159
+ }
160
+ async admitSource(source) {
161
+ await this.initialize();
162
+ await this.lock(async () => {
163
+ if (this.stopped)
164
+ return;
165
+ const prior = this.state.sources.find(s => s.messageId === source.messageId);
166
+ if (prior) {
167
+ if (prior.openId !== source.openId || prior.deviceId !== source.deviceId || prior.epoch !== source.epoch
168
+ || (prior.threadId && source.threadId && prior.threadId !== source.threadId))
169
+ throw new Error('Output source conflict.');
170
+ if (prior.expiresAt <= Date.now()) {
171
+ prior.expiresAt = Date.now() + Protocol_1.OUTPUT_LIMITS.ttl;
172
+ await this.save();
173
+ }
174
+ return;
175
+ }
176
+ this.state.sources = this.state.sources.filter(s => s.expiresAt > Date.now());
177
+ if (this.state.sources.length >= 1024)
178
+ throw new Error('Output source limit reached.');
179
+ this.state.sources.push({ ...source, expiresAt: Date.now() + Protocol_1.OUTPUT_LIMITS.ttl });
180
+ await this.save();
181
+ });
182
+ }
183
+ async offer(deviceId, value) {
184
+ const expectedSession = this.deps.session(deviceId)?.id;
185
+ await this.initialize();
186
+ if (!(0, Protocol_1.validReference)(value) || value.expiresAt <= Date.now() || value.expiresAt > Date.now() + Protocol_1.OUTPUT_LIMITS.ttl + 5000)
187
+ return;
188
+ const reference = { ...(value.discoveryIncomplete ? { discoveryIncomplete: true } : {}), id: value.id, messageId: value.messageId, threadId: value.threadId, taskId: value.taskId,
189
+ generation: value.generation, name: value.name, source: value.source, size: value.size, sha256: value.sha256, expiresAt: value.expiresAt };
190
+ let accepted;
191
+ await this.lock(async () => {
192
+ const session = this.deps.session(deviceId);
193
+ const prior = this.state.references.find(r => r.reference.id === reference.id);
194
+ const source = prior ?? this.state.sources.find(s => s.messageId === reference.messageId && s.deviceId === deviceId && s.expiresAt > Date.now());
195
+ if (this.stopped || !expectedSession || session?.id !== expectedSession || !source || session?.openId !== source.openId || (source.threadId && source.threadId !== reference.threadId)
196
+ || !await this.deps.owns(source.openId, deviceId, source.epoch))
197
+ return;
198
+ if (prior) {
199
+ if (prior.deviceId !== deviceId || JSON.stringify(prior.reference) !== JSON.stringify(reference))
200
+ return;
201
+ accepted = prior;
202
+ }
203
+ else {
204
+ if (this.state.references.length >= Protocol_1.OUTPUT_LIMITS.references)
205
+ return;
206
+ const { notices: _notices, ...binding } = source;
207
+ accepted = { ...binding, reference };
208
+ this.state.references.push(accepted);
209
+ await this.save();
210
+ }
211
+ this.deps.send(deviceId, { type: 'output_registered', id: reference.id });
212
+ });
213
+ if (accepted)
214
+ this.entry(accepted);
215
+ }
216
+ discovery(deviceId, value) {
217
+ if (this.stopped || this.noticeWork.size >= 4)
218
+ return Promise.resolve();
219
+ const work = this.discoveryNow(deviceId, value).finally(() => this.noticeWork.delete(work));
220
+ this.noticeWork.add(work);
221
+ return work;
222
+ }
223
+ async discoveryNow(deviceId, value) {
224
+ if (!Number.isInteger(value.unavailable) || value.unavailable < 0 || value.unavailable > Protocol_1.OUTPUT_LIMITS.candidates
225
+ || typeof value.omitted !== 'boolean' || typeof value.taskId !== 'string' || value.taskId.length > 200)
226
+ return;
227
+ let source, intent;
228
+ await this.lock(async () => {
229
+ source = this.state.sources.find(s => s.deviceId === deviceId && s.messageId === value.messageId && s.expiresAt > Date.now());
230
+ if (!source || this.deps.session(deviceId)?.openId !== source.openId || !await this.deps.owns(source.openId, deviceId, source.epoch))
231
+ return;
232
+ if (this.state.sources.reduce((n, s) => n + Object.keys(s.notices ?? {}).length, 0) >= 100)
233
+ return;
234
+ const key = (0, crypto_1.createHash)('sha256').update(value.taskId).digest('hex');
235
+ source.notices ??= {};
236
+ if (source.notices[key] || Object.keys(source.notices).length >= 16)
237
+ return;
238
+ intent = { uuid: (0, crypto_1.randomUUID)(), firstAt: Date.now(), state: 'intent', content: card('Output files unavailable', `${value.unavailable} linked files could not be exported.${value.omitted ? ' Discovery limits were reached; the list is not exhaustive.' : ''}`) };
239
+ source.notices[key] = intent;
240
+ await this.save();
241
+ });
242
+ if (this.stopped || !source || !intent || !await this.deps.owns(source.openId, deviceId, source.epoch))
243
+ return;
244
+ try {
245
+ intent.id = await bounded(this.deps.create(source.openId, intent.content, intent.uuid), 8000);
246
+ intent.state = 'known';
247
+ }
248
+ catch {
249
+ intent.state = 'uncertain';
250
+ }
251
+ await this.lock(() => this.save());
252
+ }
253
+ entry(ref) {
254
+ if (ref.card || this.entryWork.has(ref.reference.id) || this.stopped || this.entryWork.size >= 4)
255
+ return;
256
+ const work = (async () => {
257
+ await this.lock(async () => {
258
+ if (ref.card || !await this.deps.owns(ref.openId, ref.deviceId, ref.epoch))
259
+ return;
260
+ ref.card = { state: 'intent', uuid: (0, crypto_1.randomUUID)(), firstAt: Date.now(), content: card('Output file', `${ref.reference.name}\n${ref.reference.size} bytes · ${ref.reference.source}\nExpires ${new Date(ref.reference.expiresAt).toISOString()}${ref.reference.discoveryIncomplete ? '\nDiscovery was capped; this list is not exhaustive.' : ''}`, { action: 'output_file', id: ref.reference.id, op: 'get' }) };
261
+ await this.save();
262
+ });
263
+ if (!ref.card || ref.card.state !== 'intent' || this.stopped || !await this.deps.owns(ref.openId, ref.deviceId, ref.epoch))
264
+ return;
265
+ let id, rejected = false;
266
+ try {
267
+ id = await bounded(this.deps.create(ref.openId, ref.card.content, ref.card.uuid), 8000);
268
+ }
269
+ catch (error) {
270
+ rejected = error instanceof OutputApiRejection;
271
+ }
272
+ await this.lock(async () => { ref.card.id = id; ref.card.state = id ? 'known' : rejected ? 'unavailable' : 'uncertain'; await this.save(); });
273
+ })().catch(() => { }).finally(() => this.entryWork.delete(ref.reference.id));
274
+ this.entryWork.set(ref.reference.id, work);
275
+ }
276
+ async click(openId, cardId, action) {
277
+ await this.initialize();
278
+ let result = 'This file is unavailable.';
279
+ await this.lock(async () => {
280
+ if (this.stopped || !Protocol_1.OPAQUE_ID.test(action?.id))
281
+ return;
282
+ const ref = this.state.references.find(r => r.reference.id === action.id);
283
+ if (!ref || ref.openId !== openId || !await this.deps.owns(openId, ref.deviceId, ref.epoch))
284
+ return;
285
+ let job = this.state.jobs.find(j => j.refId === ref.reference.id && j.openId === openId && j.epoch === ref.epoch);
286
+ if (action.op === 'get') {
287
+ if (ref.card?.state !== 'known' || ref.card.id !== cardId)
288
+ return;
289
+ if (job) {
290
+ result = this.status(job);
291
+ return;
292
+ }
293
+ if (ref.reference.expiresAt <= Date.now()) {
294
+ result = 'This file has expired.';
295
+ return;
296
+ }
297
+ if (this.state.jobs.length >= 1000 || this.state.jobs.filter(j => j.openId === openId && !terminal.has(j.state) && j.state !== 'failed').length >= 20) {
298
+ result = 'File queue is full.';
299
+ return;
300
+ }
301
+ job = { id: (0, crypto_1.randomBytes)(32).toString('hex'), refId: ref.reference.id, openId, deviceId: ref.deviceId, epoch: ref.epoch,
302
+ state: 'queued', revision: 0, received: 0, createdAt: Date.now(), updatedAt: Date.now() };
303
+ this.state.jobs.push(job);
304
+ await this.save();
305
+ result = 'File retrieval accepted.';
306
+ }
307
+ else if (action.op === 'retry' && job?.card?.state === 'known' && job.card.id === cardId && action.rev === job.revision
308
+ && job.state === 'failed' && !this.running.has(job.id) && ref.reference.expiresAt > Date.now()) {
309
+ job.state = job.fileKey ? 'file-key-saved' : await this.hasSpool(job, ref) ? 'staged-verified' : 'queued';
310
+ job.revision++;
311
+ job.updatedAt = Date.now();
312
+ job.displayPending = true;
313
+ await this.save();
314
+ result = 'Retry accepted.';
315
+ }
316
+ });
317
+ void this.tick().catch(() => { });
318
+ return result;
319
+ }
320
+ status(job) {
321
+ if (job.state === 'delivered')
322
+ return 'File already delivered.';
323
+ if (job.state === 'send-uncertain')
324
+ return 'File send outcome is unknown. It will not be sent again automatically.';
325
+ const labels = {
326
+ queued: 'File retrieval queued.', 'waiting-device': 'Waiting for the original device to reconnect.',
327
+ receiving: 'Receiving the snapshot.', 'staged-verified': 'Snapshot received and verified.',
328
+ 'upload-intent': 'Uploading to Feishu.', 'file-key-saved': 'Upload complete; preparing the file message.',
329
+ 'send-intent': 'Sending the file message.', failed: 'Retrieval failed. You can retry on the transfer card.',
330
+ expired: 'This file has expired.', revoked: 'Device ownership changed; retrieval is unavailable.',
331
+ };
332
+ return labels[job.state];
333
+ }
334
+ content(job, ref) {
335
+ const progress = job.state === 'receiving' ? `\nReceived ${job.received}/${ref.reference.size} bytes (${Math.floor(job.received * 100 / ref.reference.size)}%)` : '';
336
+ return card('File transfer', `${ref.reference.name}\n${this.status(job)}${progress}`, job.state === 'failed' && ref.reference.expiresAt > Date.now() ? { action: 'output_file', id: job.refId, op: 'retry', rev: job.revision } : undefined);
337
+ }
338
+ async present(job, ref) {
339
+ if (this.presentations.has(job.id))
340
+ return this.presentations.get(job.id);
341
+ if (this.presentations.size >= 4)
342
+ return;
343
+ if (job.card?.id && job.display) {
344
+ if (Date.now() < job.display.after || (job.display.revision === job.revision && job.display.failures >= 3))
345
+ return;
346
+ }
347
+ const work = (async () => {
348
+ let create = false, content = '';
349
+ await this.lock(async () => {
350
+ content = this.content(job, ref);
351
+ if (!job.card) {
352
+ job.card = { uuid: (0, crypto_1.randomUUID)(), firstAt: Date.now(), content, state: 'intent' };
353
+ create = true;
354
+ await this.save();
355
+ }
356
+ });
357
+ if (this.stopped || !await this.deps.owns(job.openId, job.deviceId, job.epoch))
358
+ return;
359
+ if (create) {
360
+ let id, rejected = false;
361
+ try {
362
+ id = await bounded(this.deps.create(job.openId, job.card.content, job.card.uuid), 8000);
363
+ }
364
+ catch (error) {
365
+ rejected = error instanceof OutputApiRejection;
366
+ }
367
+ await this.lock(async () => { job.card.id = id; job.card.state = id ? 'known' : rejected ? 'unavailable' : 'uncertain'; job.displayPending = !!id; await this.save(); });
368
+ }
369
+ else if (job.card?.id && job.displayPending) {
370
+ const revision = job.revision;
371
+ await this.lock(async () => {
372
+ const failures = job.display?.revision === revision ? job.display.failures : 0;
373
+ // Persist a bounded presentation attempt before the external PATCH too.
374
+ job.display = { revision, failures: failures + 1, after: Date.now() + Math.min(60_000, 2000 * 2 ** failures) };
375
+ await this.save();
376
+ });
377
+ try {
378
+ await bounded(this.deps.patch(job.card.id, content), 8000);
379
+ await this.lock(async () => {
380
+ if (revision === job.revision) {
381
+ job.displayPending = false;
382
+ job.display.failures = 0;
383
+ await this.save();
384
+ }
385
+ });
386
+ }
387
+ catch { /* Presentation failure never retries the file send. */ }
388
+ }
389
+ })().catch(() => { }).finally(() => this.presentations.delete(job.id));
390
+ this.presentations.set(job.id, work);
391
+ return work;
392
+ }
393
+ spool(job) { return path_1.default.join(this.root, `${job.id}.bin`); }
394
+ async hasSpool(job, ref) {
395
+ try {
396
+ const stream = (0, FileIO_1.readOwnedFile)(this.spool(job));
397
+ const hash = (0, crypto_1.createHash)('sha256');
398
+ let size = 0;
399
+ try {
400
+ for await (const chunk of stream) {
401
+ size += chunk.length;
402
+ if (size > ref.reference.size)
403
+ return false;
404
+ hash.update(chunk);
405
+ }
406
+ }
407
+ finally {
408
+ stream.destroy();
409
+ }
410
+ return size === ref.reference.size && hash.digest('hex') === ref.reference.sha256;
411
+ }
412
+ catch {
413
+ return false;
414
+ }
415
+ }
416
+ async change(job, state) {
417
+ await this.lock(async () => { job.state = state; job.revision++; job.updatedAt = Date.now(); job.displayPending = true; await this.save(); });
418
+ }
419
+ tick() {
420
+ if (this.currentTick)
421
+ return this.currentTick;
422
+ const work = this.tickNow().finally(() => { this.currentTick = undefined; });
423
+ this.currentTick = work;
424
+ return work;
425
+ }
426
+ async tickNow() {
427
+ if (this.stopped || !this.healthy || this.ticking)
428
+ return;
429
+ this.ticking = true;
430
+ try {
431
+ if (Date.now() - this.cleanedAt > 60_000) {
432
+ await this.lock(async () => { await this.cleanup(); await this.save(); this.cleanedAt = Date.now(); });
433
+ }
434
+ for (const ref of this.state.references)
435
+ if (ref.reference.expiresAt > Date.now())
436
+ this.entry(ref);
437
+ const activeDevices = new Set([...this.running.keys()].map(id => this.state.jobs.find(j => j.id === id).deviceId));
438
+ for (const job of this.state.jobs) {
439
+ const ref = this.state.references.find(r => r.reference.id === job.refId);
440
+ if (!ref)
441
+ continue;
442
+ if (job.displayPending || !job.card)
443
+ void this.present(job, ref);
444
+ if (terminal.has(job.state) || job.state === 'failed' || this.running.has(job.id))
445
+ continue;
446
+ if (ref.reference.expiresAt <= Date.now()) {
447
+ await this.change(job, 'expired');
448
+ continue;
449
+ }
450
+ if (!await this.deps.owns(job.openId, job.deviceId, job.epoch)) {
451
+ await this.change(job, 'revoked');
452
+ continue;
453
+ }
454
+ if (!['staged-verified', 'file-key-saved'].includes(job.state) && !this.deps.session(job.deviceId)) {
455
+ if (job.state !== 'waiting-device')
456
+ await this.change(job, 'waiting-device');
457
+ continue;
458
+ }
459
+ if (this.stopped)
460
+ return;
461
+ if (this.running.size >= 4 || activeDevices.has(job.deviceId))
462
+ continue;
463
+ const operation = this.run(job, ref).catch(async () => {
464
+ if (!this.stopped && !['delivered', 'send-uncertain', 'send-intent'].includes(job.state))
465
+ await this.change(job, 'failed').catch(() => { });
466
+ }).finally(() => { this.running.delete(job.id); void this.present(job, ref); });
467
+ this.running.set(job.id, operation);
468
+ activeDevices.add(job.deviceId);
469
+ }
470
+ }
471
+ finally {
472
+ this.ticking = false;
473
+ }
474
+ }
475
+ async run(job, ref) {
476
+ if (this.stopped)
477
+ return;
478
+ await this.present(job, ref);
479
+ if (this.stopped)
480
+ return;
481
+ if (!['staged-verified', 'file-key-saved'].includes(job.state)) {
482
+ const session = this.deps.session(job.deviceId);
483
+ if (!session || session.openId !== job.openId) {
484
+ await this.change(job, 'waiting-device');
485
+ return;
486
+ }
487
+ await this.lock(async () => {
488
+ let diskBytes = 0;
489
+ for (const name of await promises_1.default.readdir(this.root))
490
+ if (/^[a-f0-9]{64}\.(bin|tmp)$/.test(name)) {
491
+ const stat = await promises_1.default.lstat(path_1.default.join(this.root, name));
492
+ if (!stat.isFile() || stat.isSymbolicLink())
493
+ throw new Error('Unsafe output spool.');
494
+ diskBytes += stat.size;
495
+ }
496
+ const recordedBytes = this.state.jobs.reduce((total, item) => total + (item.spoolBytes ?? 0), 0);
497
+ const reservations = this.state.jobs.reduce((total, item) => total + (item.state === 'receiving'
498
+ ? this.state.references.find(r => r.reference.id === item.refId)?.reference.size ?? 0 : 0), 0);
499
+ const used = Math.max(diskBytes, recordedBytes) + reservations;
500
+ if (used + ref.reference.size > Protocol_1.OUTPUT_LIMITS.routerBytes)
501
+ throw new Error('Output spool quota reached.');
502
+ job.state = 'receiving';
503
+ job.received = 0;
504
+ job.revision++;
505
+ job.updatedAt = Date.now();
506
+ job.displayPending = true;
507
+ await this.save();
508
+ });
509
+ const transferId = (0, crypto_1.randomBytes)(32).toString('hex');
510
+ const grant = { token: (0, crypto_1.randomBytes)(32).toString('hex'), sessionId: session.id, expiresAt: Math.min(Date.now() + Protocol_1.OUTPUT_LIMITS.transfer, ref.reference.expiresAt + ACTIVE_LEASE),
511
+ job, abort: new AbortController(), receiving: false, revision: job.revision };
512
+ this.grants.set(transferId, grant);
513
+ try {
514
+ this.deps.send(job.deviceId, { type: 'output_grant', id: job.refId, transferId, token: grant.token, expiresAt: grant.expiresAt });
515
+ await new Promise((resolve, reject) => {
516
+ const poll = setInterval(() => {
517
+ if (job.state === 'staged-verified') {
518
+ clearInterval(poll);
519
+ resolve();
520
+ }
521
+ else if (grant.abort.signal.aborted || grant.expiresAt <= Date.now() || this.stopped) {
522
+ clearInterval(poll);
523
+ reject(new Error('Output transfer interrupted.'));
524
+ }
525
+ }, 50);
526
+ poll.unref();
527
+ });
528
+ }
529
+ catch (error) {
530
+ if (grant.disconnected && !this.stopped) {
531
+ await this.change(job, 'waiting-device');
532
+ return;
533
+ }
534
+ throw error;
535
+ }
536
+ finally {
537
+ grant.abort.abort();
538
+ this.grants.delete(transferId);
539
+ }
540
+ }
541
+ if (this.stopped || !await this.deps.owns(job.openId, job.deviceId, job.epoch)) {
542
+ await this.change(job, 'revoked');
543
+ return;
544
+ }
545
+ if (!job.fileKey) {
546
+ if (!await this.hasSpool(job, ref))
547
+ throw new Error('Output spool integrity failed.');
548
+ await this.change(job, 'upload-intent');
549
+ const key = await bounded(this.deps.upload(this.spool(job), ref.reference.name), Protocol_1.OUTPUT_LIMITS.transfer);
550
+ if (typeof key !== 'string' || !key || key.length > 512)
551
+ throw new Error('Invalid file upload receipt.');
552
+ await this.lock(async () => { job.fileKey = key; job.state = 'file-key-saved'; job.revision++; await this.save(); });
553
+ }
554
+ if (this.stopped || !await this.deps.owns(job.openId, job.deviceId, job.epoch)) {
555
+ await this.change(job, 'revoked');
556
+ return;
557
+ }
558
+ await this.lock(async () => {
559
+ job.send = { uuid: (0, crypto_1.randomUUID)(), content: JSON.stringify({ file_key: job.fileKey }), firstAt: Date.now() };
560
+ job.state = 'send-intent';
561
+ job.revision++;
562
+ await this.save();
563
+ });
564
+ let messageId, rejected = false;
565
+ try {
566
+ messageId = await bounded(this.deps.sendFile(job.openId, job.send.content, job.send.uuid));
567
+ }
568
+ catch (error) {
569
+ rejected = error instanceof OutputApiRejection;
570
+ }
571
+ await this.lock(async () => {
572
+ if (typeof messageId === 'string' && messageId && messageId.length <= 512) {
573
+ job.messageId = messageId;
574
+ job.state = 'delivered';
575
+ }
576
+ else
577
+ job.state = rejected ? 'failed' : 'send-uncertain';
578
+ job.revision++;
579
+ job.updatedAt = Date.now();
580
+ job.displayPending = true;
581
+ await this.save();
582
+ });
583
+ await promises_1.default.rm(this.spool(job), { force: true });
584
+ await this.lock(async () => { job.spoolBytes = 0; await this.save(); });
585
+ }
586
+ async receive(ctx, transferId) {
587
+ const grant = this.grants.get(transferId), token = ctx.get('authorization').replace(/^Bearer /, '');
588
+ if (!grant || !/^[a-f0-9]{64}$/.test(token) || !(0, crypto_1.timingSafeEqual)(Buffer.from(token), Buffer.from(grant.token))
589
+ || grant.receiving || grant.expiresAt <= Date.now() || this.stopped) {
590
+ ctx.status = 403;
591
+ return;
592
+ }
593
+ const job = grant.job, ref = this.state.references.find(r => r.reference.id === job.refId);
594
+ const current = () => this.deps.session(job.deviceId)?.id === grant.sessionId && !grant.abort.signal.aborted
595
+ && this.grants.get(transferId) === grant && grant.revision === job.revision && job.state === 'receiving'
596
+ && grant.expiresAt > Date.now();
597
+ if (!current() || !await this.deps.owns(job.openId, job.deviceId, job.epoch)) {
598
+ ctx.status = 403;
599
+ return;
600
+ }
601
+ grant.receiving = true;
602
+ const temporary = path_1.default.join(this.root, `${transferId}.tmp`);
603
+ let handle;
604
+ let idle;
605
+ const timer = setTimeout(() => grant.abort.abort(), Math.max(1, grant.expiresAt - Date.now()));
606
+ timer.unref();
607
+ let bytes = 0, lastProgress = 0;
608
+ const hash = (0, crypto_1.createHash)('sha256');
609
+ const meter = new stream_1.Transform({ transform: (chunk, _encoding, done) => {
610
+ bytes += chunk.length;
611
+ if (!current() || bytes > ref.reference.size) {
612
+ done(new Error('Output transfer rejected.'));
613
+ return;
614
+ }
615
+ hash.update(chunk);
616
+ clearTimeout(idle);
617
+ idle = setTimeout(() => grant.abort.abort(), Protocol_1.OUTPUT_LIMITS.idle);
618
+ idle.unref();
619
+ job.received = bytes;
620
+ if (Date.now() - lastProgress > 2000) {
621
+ lastProgress = Date.now();
622
+ job.displayPending = true;
623
+ void this.present(job, ref);
624
+ }
625
+ done(null, chunk);
626
+ } });
627
+ try {
628
+ handle = await promises_1.default.open(temporary, 'wx', 0o600);
629
+ await (0, promises_2.pipeline)(ctx.req, meter, new stream_1.Writable({ write(chunk, _encoding, done) { handle.writeFile(chunk).then(() => done(), done); } }), { signal: grant.abort.signal });
630
+ if (bytes !== ref.reference.size || hash.digest('hex') !== ref.reference.sha256 || !current()
631
+ || !await this.deps.owns(job.openId, job.deviceId, job.epoch))
632
+ throw new Error('Output integrity failed.');
633
+ await handle.sync();
634
+ await handle.close();
635
+ handle = undefined;
636
+ await promises_1.default.rename(temporary, this.spool(job));
637
+ await (0, Durable_1.syncDirectory)(this.root);
638
+ if (!current())
639
+ throw new Error('Output connection changed.');
640
+ await this.lock(async () => {
641
+ if (!current())
642
+ throw new Error('Output transfer superseded.');
643
+ job.spoolBytes = bytes;
644
+ job.state = 'staged-verified';
645
+ job.revision++;
646
+ job.updatedAt = Date.now();
647
+ job.displayPending = true;
648
+ await this.save();
649
+ });
650
+ ctx.status = 204;
651
+ }
652
+ catch {
653
+ grant.abort.abort();
654
+ ctx.status = 400;
655
+ }
656
+ finally {
657
+ clearTimeout(timer);
658
+ clearTimeout(idle);
659
+ await handle?.close();
660
+ this.storage.check();
661
+ await promises_1.default.rm(temporary, { force: true });
662
+ }
663
+ }
664
+ failed(deviceId, transferId) {
665
+ const grant = this.grants.get(transferId);
666
+ if (grant?.job.deviceId === deviceId)
667
+ grant.abort.abort();
668
+ }
669
+ disconnect(deviceId) { for (const grant of this.grants.values())
670
+ if (grant.job.deviceId === deviceId) {
671
+ grant.disconnected = true;
672
+ grant.abort.abort();
673
+ } }
674
+ async cleanup() {
675
+ const now = Date.now();
676
+ this.state.sources = this.state.sources.filter(s => s.expiresAt > now);
677
+ this.state.jobs = this.state.jobs.filter(j => j.createdAt + 7 * Protocol_1.OUTPUT_LIMITS.ttl > now);
678
+ this.state.references = this.state.references.filter(r => r.reference.expiresAt > now
679
+ || this.state.jobs.some(j => j.refId === r.reference.id && !terminal.has(j.state) && j.state !== 'failed'));
680
+ for (const name of await promises_1.default.readdir(this.root)) {
681
+ if (/^[a-f0-9]{64}\.tmp$/.test(name) && !this.grants.has(name.slice(0, 64)))
682
+ await promises_1.default.rm(path_1.default.join(this.root, name), { force: true });
683
+ if (/^[a-f0-9]{64}\.bin$/.test(name)) {
684
+ const job = this.state.jobs.find(j => j.id === name.slice(0, 64));
685
+ if (!job || (!this.running.has(job.id) && (terminal.has(job.state) || !this.state.references.some(r => r.reference.id === job.refId)))) {
686
+ await promises_1.default.rm(path_1.default.join(this.root, name), { force: true });
687
+ if (job)
688
+ job.spoolBytes = 0;
689
+ }
690
+ }
691
+ }
692
+ }
693
+ async destroy() {
694
+ this.stopped = true;
695
+ clearInterval(this.timer);
696
+ for (const grant of this.grants.values())
697
+ grant.abort.abort();
698
+ await this.currentTick;
699
+ await Promise.allSettled([...this.running.values(), ...this.presentations.values(), ...this.entryWork.values(), ...this.noticeWork]);
700
+ await this.serial;
701
+ }
702
+ }
703
+ exports.OutputTransfers = OutputTransfers;
704
+ //# sourceMappingURL=OutputTransfers.js.map