@anusornneal/chat-relay 1.8.0 → 2.0.1
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/README.md +60 -0
- package/agent/activity-capture.mjs +165 -0
- package/agent/capability-scheduler.mjs +83 -6
- package/agent/file-manager.mjs +188 -77
- package/agent/fs-batch-preview.mjs +70 -0
- package/agent/full-bridge.mjs +53 -0
- package/agent/full-desktop-actions.mjs +124 -0
- package/agent/full-desktop-auth.mjs +53 -0
- package/agent/full-desktop-broker.mjs +308 -0
- package/agent/full-host.mjs +153 -0
- package/agent/full-job-broker.mjs +360 -0
- package/agent/full-native-job.mjs +205 -0
- package/agent/full-presentation-changes.mjs +191 -0
- package/agent/full-remote-diagnostics.mjs +129 -0
- package/agent/full-resources.mjs +343 -0
- package/agent/full-runtime-supervisor.mjs +67 -0
- package/agent/full-session-dispatch.mjs +167 -0
- package/agent/full-workspace-broker.mjs +290 -0
- package/agent/git-worktree-manager.mjs +170 -4
- package/agent/lifecycle.mjs +17 -0
- package/agent/local-agent.mjs +182 -33
- package/agent/local-usage.mjs +275 -0
- package/agent/monitor-activity.mjs +111 -0
- package/agent/presentation-redaction.mjs +10 -0
- package/agent/process-manager.mjs +32 -0
- package/agent/protocol.mjs +5 -1
- package/agent/terminal-manager.mjs +240 -29
- package/agent/terminal-output.mjs +136 -0
- package/agent/toolcall-context.mjs +35 -5
- package/agent/toolcall-summary.mjs +10 -0
- package/agent/windows-desktop-runner.mjs +65 -61
- package/agent/windows-desktop-worker.ps1 +33 -18
- package/agent/windows-powershell.mjs +51 -0
- package/cli/full-background.mjs +69 -0
- package/cli/full-launch.mjs +94 -0
- package/cli/full-prepare-child.mjs +48 -0
- package/cli/full-prepare.mjs +171 -0
- package/cli/full-release-default.json +4 -0
- package/cli/full-release-files.mjs +36 -0
- package/cli/full-release-official.mjs +48 -0
- package/cli/full-release-source.mjs +37 -0
- package/cli/index.mjs +8 -4
- package/cli/mod-cache.mjs +170 -0
- package/cli/mod-loader.mjs +67 -0
- package/cli/mod-manifest.mjs +63 -0
- package/cli/remote.mjs +172 -17
- package/cli/runner-ownership.mjs +116 -3
- package/cli/self-update.mjs +1 -1
- package/cli/tui.mjs +2 -20
- package/package.json +9 -6
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/native-job.mjs +13 -0
- package/packages/full-contracts/package.json +7 -0
- package/packages/full-contracts/remote-session.mjs +239 -0
package/agent/file-manager.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { deduplicateSearchPreviews } from "./fs-batch-preview.mjs";
|
|
5
|
+
import {recordActivityEdit} from "./activity-capture.mjs";
|
|
4
6
|
|
|
5
7
|
const MAX_READ_BYTES = 256 * 1024;
|
|
6
8
|
const DEFAULT_READ_RESPONSE_BYTES = 32 * 1024;
|
|
@@ -8,6 +10,8 @@ const DEFAULT_MULTI_READ_RESPONSE_BYTES = 48 * 1024;
|
|
|
8
10
|
const DEFAULT_BATCH_RESPONSE_BYTES = 48 * 1024;
|
|
9
11
|
const MAX_BATCH_OPERATIONS = 20;
|
|
10
12
|
const MAX_BATCH_SEARCHES = 8;
|
|
13
|
+
const MAX_BATCH_EDIT_BYTES = 48 * 1024;
|
|
14
|
+
const MAX_BATCH_EDITS = 100;
|
|
11
15
|
const MAX_ARTIFACT_BYTES = 40 * 1024;
|
|
12
16
|
const ARTIFACT_MIME_TYPES = new Map([
|
|
13
17
|
[".txt", "text/plain; charset=utf-8"],
|
|
@@ -93,10 +97,24 @@ function normalizeReadRequest(input) {
|
|
|
93
97
|
return typeof input === "string" ? { path: input } : { ...(input || {}) };
|
|
94
98
|
}
|
|
95
99
|
|
|
100
|
+
function utf8Bytes(text, max) {
|
|
101
|
+
if (typeof text !== "string" || !text.isWellFormed() || text.includes("\0")) throw new Error("invalid_utf8");
|
|
102
|
+
const bytes = Buffer.from(text, "utf8");
|
|
103
|
+
if (bytes.length > max) throw new Error("file_too_large");
|
|
104
|
+
return bytes;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function editError(error) {
|
|
108
|
+
// Return a compact stable error, not paths or an arbitrary OS exception string.
|
|
109
|
+
const code = typeof error?.code === "string" ? error.code : error?.message;
|
|
110
|
+
return typeof code === "string" && /^[a-zA-Z0-9_:-]{1,100}$/.test(code) ? code : "batch_edit_failed";
|
|
111
|
+
}
|
|
112
|
+
|
|
96
113
|
export class FileManager {
|
|
97
114
|
constructor(rootSpec) {
|
|
98
115
|
this.roots = splitRoots(rootSpec);
|
|
99
116
|
this.searches = new Map();
|
|
117
|
+
this.editBatchTail = Promise.resolve();
|
|
100
118
|
}
|
|
101
119
|
|
|
102
120
|
getRoots() {
|
|
@@ -123,6 +141,35 @@ export class FileManager {
|
|
|
123
141
|
throw new Error("path_not_allowed");
|
|
124
142
|
}
|
|
125
143
|
|
|
144
|
+
async #resolveBatchBase(basePath) {
|
|
145
|
+
if (basePath === undefined || basePath === null) return null;
|
|
146
|
+
if (typeof basePath !== "string" || !path.isAbsolute(basePath)) throw new Error("invalid_base_path");
|
|
147
|
+
const base = await this.#resolveExisting(basePath);
|
|
148
|
+
if (!(await fs.stat(base)).isDirectory()) throw new Error("base_not_directory");
|
|
149
|
+
return base;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async #batchPath(input, base, create = false) {
|
|
153
|
+
if (typeof input !== "string" || !input || input.includes("\0")) throw new Error("invalid_path");
|
|
154
|
+
if (process.platform === "win32" && input.replace(/^[a-z]:/i, "").includes(":")) {
|
|
155
|
+
throw new Error("invalid_path");
|
|
156
|
+
}
|
|
157
|
+
if (!base && !create) return input;
|
|
158
|
+
if (base && (path.isAbsolute(input) || path.win32.isAbsolute(input) || /^[a-z]:/i.test(input))) {
|
|
159
|
+
throw new Error("relative_path_required");
|
|
160
|
+
}
|
|
161
|
+
const target = path.resolve(base || process.cwd(), input);
|
|
162
|
+
if (base && !within(base, target)) throw new Error("path_outside_base");
|
|
163
|
+
if (create) {
|
|
164
|
+
const parent = await this.#resolveExisting(path.dirname(target));
|
|
165
|
+
if (base && !within(base, parent)) throw new Error("path_outside_base");
|
|
166
|
+
return path.join(parent, path.basename(target));
|
|
167
|
+
}
|
|
168
|
+
const canonical = await this.#resolveExisting(target);
|
|
169
|
+
if (base && !within(base, canonical)) throw new Error("path_outside_base");
|
|
170
|
+
return canonical;
|
|
171
|
+
}
|
|
172
|
+
|
|
126
173
|
async stat(input) {
|
|
127
174
|
const target = await this.#resolveExisting(input);
|
|
128
175
|
const info = await fs.stat(target);
|
|
@@ -221,11 +268,12 @@ export class FileManager {
|
|
|
221
268
|
};
|
|
222
269
|
}
|
|
223
270
|
|
|
224
|
-
async readMany(paths, maxTotalBytes = DEFAULT_MULTI_READ_RESPONSE_BYTES) {
|
|
271
|
+
async readMany(paths, maxTotalBytes = DEFAULT_MULTI_READ_RESPONSE_BYTES, basePath) {
|
|
225
272
|
if (!Array.isArray(paths) || paths.length === 0 || paths.length > 20) {
|
|
226
273
|
throw new Error("invalid_paths");
|
|
227
274
|
}
|
|
228
275
|
|
|
276
|
+
const base = basePath == null ? null : await this.#resolveBatchBase(basePath);
|
|
229
277
|
const requests = paths.map(normalizeReadRequest);
|
|
230
278
|
if (requests.some((entry) => typeof entry.path !== "string" || entry.path.length === 0)) {
|
|
231
279
|
throw new Error("invalid_paths");
|
|
@@ -247,8 +295,9 @@ export class FileManager {
|
|
|
247
295
|
let candidate;
|
|
248
296
|
|
|
249
297
|
try {
|
|
298
|
+
const target = base ? await this.#batchPath(request.path, base) : request.path;
|
|
250
299
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
251
|
-
const result = await this.read(
|
|
300
|
+
const result = await this.read(target, start, length, fileBudget);
|
|
252
301
|
candidate = { ok: true, ...result };
|
|
253
302
|
const projected = {
|
|
254
303
|
files: [...files, candidate],
|
|
@@ -301,17 +350,24 @@ export class FileManager {
|
|
|
301
350
|
}
|
|
302
351
|
|
|
303
352
|
|
|
304
|
-
async batch(operations, maxTotalBytes = DEFAULT_BATCH_RESPONSE_BYTES) {
|
|
353
|
+
async batch(operations, maxTotalBytes = DEFAULT_BATCH_RESPONSE_BYTES, options = {}) {
|
|
305
354
|
if (!Array.isArray(operations) || operations.length === 0 || operations.length > MAX_BATCH_OPERATIONS) {
|
|
306
355
|
throw new Error("invalid_batch");
|
|
307
356
|
}
|
|
308
|
-
|
|
309
357
|
if (operations.filter((item) => item?.op === "search").length > MAX_BATCH_SEARCHES) {
|
|
310
358
|
throw new Error("too_many_batch_searches");
|
|
311
359
|
}
|
|
360
|
+
const batchBase = options.basePath == null ? null : await this.#resolveBatchBase(options.basePath);
|
|
312
361
|
const totalBudget = boundedReadBytes(maxTotalBytes, DEFAULT_BATCH_RESPONSE_BYTES, 4 * 1024);
|
|
313
362
|
const results = [];
|
|
314
363
|
let nextIndex = null;
|
|
364
|
+
const payloadFor = (rows, next, truncated = false) => ({
|
|
365
|
+
...(options.deduplicatePreviews === true ? deduplicateSearchPreviews(rows) : { results: rows }),
|
|
366
|
+
totalOperations: operations.length,
|
|
367
|
+
nextIndex: next,
|
|
368
|
+
truncated,
|
|
369
|
+
maxTotalBytes: totalBudget,
|
|
370
|
+
});
|
|
315
371
|
|
|
316
372
|
for (let index = 0; index < operations.length; index++) {
|
|
317
373
|
const operation = operations[index] || {};
|
|
@@ -322,106 +378,160 @@ export class FileManager {
|
|
|
322
378
|
op,
|
|
323
379
|
...(typeof operation.path === "string" ? { path: operation.path } : {}),
|
|
324
380
|
};
|
|
381
|
+
const next = index + 1 < operations.length ? index + 1 : null;
|
|
382
|
+
const fits = candidate => byteSize(payloadFor([...results, candidate], next)) <= totalBudget;
|
|
325
383
|
const minimumBudget = op === "list" ? 4 * 1024 : MIN_READ_RESPONSE_BYTES;
|
|
326
384
|
const fallbackBudget = op === "list" ? DEFAULT_LIST_RESPONSE_BYTES : DEFAULT_READ_RESPONSE_BYTES;
|
|
327
385
|
let operationBudget = boundedReadBytes(operation.maxBytes, fallbackBudget, minimumBudget);
|
|
328
386
|
let candidate;
|
|
329
|
-
|
|
330
387
|
try {
|
|
331
|
-
if (typeof operation.path !== "string" || operation.path
|
|
332
|
-
|
|
333
|
-
}
|
|
334
|
-
|
|
388
|
+
if (typeof operation.path !== "string" || !operation.path) throw new Error("invalid_path");
|
|
389
|
+
const target = batchBase ? await this.#batchPath(operation.path, batchBase) : operation.path;
|
|
335
390
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
336
391
|
let result;
|
|
337
|
-
if (op === "stat")
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
result = await this.list(operation.path, operation.depth, operation.offset, operation.limit, operationBudget);
|
|
343
|
-
} else if (op === "search") {
|
|
344
|
-
result = await this.startSearch(operation.path, operation.pattern, operation.searchType, operation.maxResults ?? 10, operation.previewLines);
|
|
345
|
-
} else {
|
|
346
|
-
throw new Error("invalid_batch_operation");
|
|
347
|
-
}
|
|
392
|
+
if (op === "stat") result = await this.stat(target);
|
|
393
|
+
else if (op === "read") result = await this.read(target, operation.offset, operation.length, operationBudget);
|
|
394
|
+
else if (op === "list") result = await this.list(target, operation.depth, operation.offset, operation.limit, operationBudget);
|
|
395
|
+
else if (op === "search") result = await this.startSearch(target, operation.pattern, operation.searchType, operation.maxResults ?? 10, operation.previewLines);
|
|
396
|
+
else throw new Error("invalid_batch_operation");
|
|
348
397
|
|
|
349
398
|
candidate = { ...base, ok: true, result };
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
totalOperations: operations.length,
|
|
353
|
-
nextIndex: index + 1 < operations.length ? index + 1 : null,
|
|
354
|
-
truncated: false,
|
|
355
|
-
maxTotalBytes: totalBudget,
|
|
356
|
-
};
|
|
357
|
-
if (byteSize(projected) <= totalBudget) break;
|
|
399
|
+
if (fits(candidate)) break;
|
|
400
|
+
candidate = undefined;
|
|
358
401
|
if (op === "search") {
|
|
359
|
-
//
|
|
360
|
-
// the aggregate response budget. The caller can continue from
|
|
361
|
-
// sessionId + nextOffset without repeating the scan.
|
|
362
|
-
candidate = undefined;
|
|
402
|
+
// Do not repeat a scan just to fit its initial response page.
|
|
363
403
|
for (let keep = result.results.length - 1; keep >= 0; keep--) {
|
|
364
|
-
const page = {
|
|
365
|
-
|
|
366
|
-
results: result.results.slice(0, keep),
|
|
367
|
-
nextOffset: keep < result.totalResults ? keep : null,
|
|
368
|
-
};
|
|
404
|
+
const page = { ...result, results: result.results.slice(0, keep),
|
|
405
|
+
nextOffset: keep < result.totalResults ? keep : null };
|
|
369
406
|
const reduced = { ...base, ok: true, result: page };
|
|
370
|
-
if (
|
|
371
|
-
candidate = reduced;
|
|
372
|
-
break;
|
|
373
|
-
}
|
|
407
|
+
if (fits(reduced)) { candidate = reduced; break; }
|
|
374
408
|
}
|
|
375
409
|
break;
|
|
376
410
|
}
|
|
377
|
-
if (op === "stat")
|
|
378
|
-
candidate = undefined;
|
|
379
|
-
break;
|
|
380
|
-
}
|
|
381
|
-
|
|
411
|
+
if (op === "stat") break;
|
|
382
412
|
operationBudget = Math.floor(operationBudget * 0.65);
|
|
383
|
-
candidate = undefined;
|
|
384
413
|
if (operationBudget < minimumBudget) break;
|
|
385
414
|
}
|
|
386
415
|
} catch (error) {
|
|
387
|
-
candidate = {
|
|
388
|
-
...base,
|
|
389
|
-
ok: false,
|
|
390
|
-
error: error instanceof Error ? error.message : "batch_operation_failed",
|
|
391
|
-
};
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
if (!candidate) {
|
|
395
|
-
nextIndex = index;
|
|
396
|
-
break;
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
const projected = {
|
|
400
|
-
results: [...results, candidate],
|
|
401
|
-
totalOperations: operations.length,
|
|
402
|
-
nextIndex: index + 1 < operations.length ? index + 1 : null,
|
|
403
|
-
truncated: false,
|
|
404
|
-
maxTotalBytes: totalBudget,
|
|
405
|
-
};
|
|
406
|
-
if (byteSize(projected) > totalBudget) {
|
|
407
|
-
nextIndex = index;
|
|
408
|
-
break;
|
|
416
|
+
candidate = { ...base, ok: false, error: error instanceof Error ? error.message : "batch_operation_failed" };
|
|
409
417
|
}
|
|
418
|
+
if (!candidate || !fits(candidate)) { nextIndex = index; break; }
|
|
410
419
|
results.push(candidate);
|
|
411
420
|
}
|
|
412
421
|
|
|
413
|
-
const nestedTruncated = results.some(
|
|
422
|
+
const nestedTruncated = results.some(entry => entry.ok && (
|
|
414
423
|
entry.result?.truncated === true || (entry.op === "search" && entry.result?.nextOffset !== null)
|
|
415
424
|
));
|
|
416
|
-
return
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
};
|
|
425
|
+
return payloadFor(results, nextIndex, nextIndex !== null || nestedTruncated);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// One entry per file, multiple exact replacements per entry. Separate from read-only batch.
|
|
429
|
+
editMany(operations, basePath, {strictPaths=false}={}) {
|
|
430
|
+
const run = this.editBatchTail.then(() => this.#editMany(operations, basePath,strictPaths));
|
|
431
|
+
this.editBatchTail = run.catch(() => {});
|
|
432
|
+
return run;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async #editMany(operations, basePath, strictPaths) {
|
|
436
|
+
if (!Array.isArray(operations) || !operations.length || operations.length > MAX_BATCH_OPERATIONS) {
|
|
437
|
+
throw new Error("invalid_edit_batch");
|
|
438
|
+
}
|
|
439
|
+
if (byteSize({ operations, basePath }) > MAX_BATCH_EDIT_BYTES) throw new Error("edit_batch_too_large");
|
|
440
|
+
const count = operations.reduce((sum, op) => sum + (Array.isArray(op?.edits) ? op.edits.length : 0), 0);
|
|
441
|
+
if (count > MAX_BATCH_EDITS) throw new Error("too_many_batch_edits");
|
|
442
|
+
const base = await this.#resolveBatchBase(basePath);
|
|
443
|
+
if(strictPaths&&(!base||path.relative(basePath,base)!==""))throw new Error("target_changed");
|
|
444
|
+
const resolved = [];
|
|
445
|
+
const targets = new Map();
|
|
446
|
+
for (const [index, operation] of operations.entries()) {
|
|
447
|
+
const input = typeof operation?.path === "string" ? operation.path : "";
|
|
448
|
+
const row = { index, path: input.slice(0, 512), ...(input.length > 512 ? { pathTruncated: true } : {}) };
|
|
449
|
+
try {
|
|
450
|
+
if (!["create", "edit"].includes(operation?.op)) throw new Error("invalid_edit_batch_operation");
|
|
451
|
+
const create = operation.op === "create";
|
|
452
|
+
const selected = await this.#batchPath(input, base, create);
|
|
453
|
+
const target = create ? selected : await this.#resolveExisting(selected);
|
|
454
|
+
if(strictPaths&&path.relative(path.resolve(base,input),target)!=="")throw new Error("target_changed");
|
|
455
|
+
const key = process.platform === "win32" ? target.toLowerCase() : target;
|
|
456
|
+
resolved.push({ row, operation, target, key });
|
|
457
|
+
targets.set(key, (targets.get(key) || 0) + 1);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
resolved.push({ row: { ...row, ok: false, error: editError(error) } });
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
const results = [];
|
|
464
|
+
for (const entry of resolved) {
|
|
465
|
+
if (!entry.target) { results.push(entry.row); continue; }
|
|
466
|
+
const { row, operation, target, key } = entry;
|
|
467
|
+
try {
|
|
468
|
+
if (targets.get(key) > 1) throw new Error("duplicate_batch_target");
|
|
469
|
+
const create = operation.op === "create";
|
|
470
|
+
let original = null, mode, updated, replacements = 0;
|
|
471
|
+
if (create) {
|
|
472
|
+
updated = utf8Bytes(operation.content, MAX_WRITE_BYTES);
|
|
473
|
+
} else {
|
|
474
|
+
const info = await fs.lstat(target);
|
|
475
|
+
if (!info.isFile() || info.isSymbolicLink()) throw new Error("not_a_file");
|
|
476
|
+
if (info.size > MAX_WRITE_BYTES * 8) throw new Error("file_too_large");
|
|
477
|
+
original = await fs.readFile(target);
|
|
478
|
+
if (original.length > MAX_WRITE_BYTES * 8) throw new Error("file_too_large");
|
|
479
|
+
if (original.includes(0)) throw new Error("invalid_utf8");
|
|
480
|
+
let text;
|
|
481
|
+
try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(original); }
|
|
482
|
+
catch { throw new Error("invalid_utf8"); }
|
|
483
|
+
mode = info.mode & 0o777;
|
|
484
|
+
if (!Array.isArray(operation.edits) || !operation.edits.length || operation.edits.length > 20) throw new Error("invalid_edit");
|
|
485
|
+
const crlf = text.includes("\r\n") && !text.replace(/\r\n/g, "").includes("\n");
|
|
486
|
+
const eol = value => crlf ? value.replace(/\r?\n/g, "\r\n") : value;
|
|
487
|
+
for (const edit of operation.edits) {
|
|
488
|
+
if (typeof edit?.oldText !== "string" || !edit.oldText || typeof edit.newText !== "string" ||
|
|
489
|
+
!edit.oldText.isWellFormed() || !edit.newText.isWellFormed()) throw new Error("invalid_edit");
|
|
490
|
+
const expected = edit.expectedReplacements ?? 1;
|
|
491
|
+
if (!Number.isInteger(expected) || expected < 1 || expected > 100) throw new Error("invalid_edit");
|
|
492
|
+
const parts = text.split(eol(edit.oldText));
|
|
493
|
+
const matches = parts.length - 1;
|
|
494
|
+
if (matches !== expected) throw new Error("replacement_count_mismatch:" + matches);
|
|
495
|
+
text = parts.join(eol(edit.newText));
|
|
496
|
+
replacements += matches;
|
|
497
|
+
}
|
|
498
|
+
updated = utf8Bytes(text, MAX_WRITE_BYTES * 8);
|
|
499
|
+
}
|
|
500
|
+
await this.#commitBatchFile(target, original, updated, mode, base);
|
|
501
|
+
recordActivityEdit(row.index,row.path,original,updated,create?"added":"modified",target);
|
|
502
|
+
results.push({ ...row, ok: true, op: operation.op, bytes: updated.length, ...(create ? {} : { replacements }) });
|
|
503
|
+
} catch (error) {
|
|
504
|
+
results.push({ ...row, ok: false, op: operation.op, error: editError(error) });
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
const succeeded = results.filter(row => row.ok).length;
|
|
508
|
+
return { ok: succeeded === results.length, requested: results.length, succeeded, failed: results.length - succeeded,
|
|
509
|
+
...(succeeded === results.length ? {} : { error: "batch_edit_partial_failure" }), results };
|
|
423
510
|
}
|
|
424
511
|
|
|
512
|
+
async #commitBatchFile(target, original, updated, mode, base) {
|
|
513
|
+
const parent = await this.#resolveExisting(path.dirname(target));
|
|
514
|
+
if (base && !within(base, parent)) throw new Error("path_outside_base");
|
|
515
|
+
if (path.relative(parent, path.dirname(target)) !== "") throw new Error("target_changed");
|
|
516
|
+
const temporary = path.join(parent, ".chat-relay-" + randomUUID() + ".tmp");
|
|
517
|
+
try {
|
|
518
|
+
await fs.writeFile(temporary, updated, { flag: "wx", ...(mode === undefined ? {} : { mode }) });
|
|
519
|
+
const currentParent = await this.#resolveExisting(parent);
|
|
520
|
+
if (path.relative(parent, currentParent) !== "") throw new Error("target_changed");
|
|
521
|
+
if (original === null) {
|
|
522
|
+
// Same-directory link is an atomic no-clobber publish, even if another creator wins.
|
|
523
|
+
await fs.link(temporary, target);
|
|
524
|
+
} else {
|
|
525
|
+
const info = await fs.lstat(target);
|
|
526
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size !== original.length ||
|
|
527
|
+
!(await fs.readFile(target)).equals(original)) throw new Error("target_changed");
|
|
528
|
+
// Atomic replacement per file, not a transaction across files or an OS-level CAS.
|
|
529
|
+
await fs.rename(temporary, target);
|
|
530
|
+
}
|
|
531
|
+
} finally {
|
|
532
|
+
await fs.unlink(temporary).catch(() => {});
|
|
533
|
+
}
|
|
534
|
+
}
|
|
425
535
|
|
|
426
536
|
async exportArtifact(input, maxBytes = MAX_ARTIFACT_BYTES) {
|
|
427
537
|
const target = await this.#resolveExisting(input);
|
|
@@ -473,6 +583,7 @@ export class FileManager {
|
|
|
473
583
|
const updated = parts.join(newText);
|
|
474
584
|
if (Buffer.byteLength(updated, "utf8") > MAX_WRITE_BYTES * 8) throw new Error("file_too_large");
|
|
475
585
|
await fs.writeFile(target, updated, "utf8");
|
|
586
|
+
recordActivityEdit(0,input,text,updated,"modified",target);
|
|
476
587
|
return { path: target, replacements: matches };
|
|
477
588
|
}
|
|
478
589
|
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Opt-in response packing only: preserve each match and its original preview range.
|
|
2
|
+
const size = value => Buffer.byteLength(JSON.stringify(value), "utf8");
|
|
3
|
+
|
|
4
|
+
export function deduplicateSearchPreviews(results) {
|
|
5
|
+
const byPath = new Map();
|
|
6
|
+
for (const [rowIndex, row] of results.entries()) {
|
|
7
|
+
if (!row.ok || row.op !== "search" || !Array.isArray(row.result?.results)) continue;
|
|
8
|
+
for (const [matchIndex, match] of row.result.results.entries()) {
|
|
9
|
+
const preview = match.preview;
|
|
10
|
+
if (!match.path || !preview || typeof preview.content !== "string" ||
|
|
11
|
+
!Number.isInteger(preview.offset) || !Number.isInteger(preview.length) || preview.length < 1) continue;
|
|
12
|
+
const lines = preview.content.split("\n");
|
|
13
|
+
if (lines.length !== preview.length) continue;
|
|
14
|
+
const group = byPath.get(match.path) || [];
|
|
15
|
+
group.push({ rowIndex, matchIndex, preview, lines });
|
|
16
|
+
byPath.set(match.path, group);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const sharedPreviews = [];
|
|
21
|
+
const references = new Map();
|
|
22
|
+
for (const [filePath, previews] of byPath) {
|
|
23
|
+
if (previews.length < 2) continue;
|
|
24
|
+
previews.sort((a, b) => a.preview.offset - b.preview.offset);
|
|
25
|
+
let group = null;
|
|
26
|
+
const emit = () => {
|
|
27
|
+
if (!group || group.members.length < 2) return;
|
|
28
|
+
const id = "p" + (sharedPreviews.length + 1);
|
|
29
|
+
const shared = { id, path: filePath, offset: group.offset, length: group.lines.length,
|
|
30
|
+
content: group.lines.join("\n") };
|
|
31
|
+
const replacements = group.members.map(member => {
|
|
32
|
+
const { content, ...metadata } = member.preview;
|
|
33
|
+
return { member, preview: { ...metadata, ref: id } };
|
|
34
|
+
});
|
|
35
|
+
// Short previews can cost more as references. Keep them inline in that case.
|
|
36
|
+
if (size(shared) + size(replacements.map(x => x.preview)) >=
|
|
37
|
+
size(group.members.map(x => x.preview))) return;
|
|
38
|
+
sharedPreviews.push(shared);
|
|
39
|
+
for (const { member, preview } of replacements) {
|
|
40
|
+
references.set(member.rowIndex + ":" + member.matchIndex, preview);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
for (const item of previews) {
|
|
44
|
+
const offset = item.preview.offset;
|
|
45
|
+
const start = group ? offset - group.offset : 0;
|
|
46
|
+
const overlap = group ? Math.min(group.lines.length - start, item.lines.length) : 0;
|
|
47
|
+
// Never combine inconsistent snapshots (e.g. a file changed during the batch).
|
|
48
|
+
const compatible = group && overlap > 0 && item.preview.totalLines === group.totalLines &&
|
|
49
|
+
item.lines.slice(0, overlap).every((line, index) => line === group.lines[start + index]);
|
|
50
|
+
if (compatible) {
|
|
51
|
+
if (start + item.lines.length > group.lines.length) group.lines.push(...item.lines.slice(overlap));
|
|
52
|
+
group.members.push(item);
|
|
53
|
+
} else {
|
|
54
|
+
emit();
|
|
55
|
+
group = { offset, lines: [...item.lines], totalLines: item.preview.totalLines, members: [item] };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
emit();
|
|
59
|
+
}
|
|
60
|
+
if (!sharedPreviews.length) return { results };
|
|
61
|
+
const packed = results.map((row, rowIndex) => {
|
|
62
|
+
if (!row.ok || row.op !== "search") return row;
|
|
63
|
+
return { ...row, result: { ...row.result, results: row.result.results.map((match, matchIndex) => {
|
|
64
|
+
const preview = references.get(rowIndex + ":" + matchIndex);
|
|
65
|
+
return preview ? { ...match, preview } : match;
|
|
66
|
+
}) } };
|
|
67
|
+
});
|
|
68
|
+
const candidate = { results: packed, sharedPreviews };
|
|
69
|
+
return size(candidate) < size({ results }) ? candidate : { results };
|
|
70
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createEventBuffer, fullUnavailable, hasFullSessionRequest, toolCorrelation } from "../packages/full-contracts/index.mjs";
|
|
3
|
+
|
|
4
|
+
export { fullUnavailable, hasFullSessionRequest };
|
|
5
|
+
|
|
6
|
+
// Optional best-effort IPC projection. Exactly one send is in flight; the ring
|
|
7
|
+
// bounds backlog, and a consumer sees an explicit gap after a slow/disconnected
|
|
8
|
+
// subscriber. Critical state never relies on this channel.
|
|
9
|
+
export function createCoreEventBridge({ enabled = false, send, producerEpoch = randomUUID, now = () => new Date().toISOString(), capacity } = {}) {
|
|
10
|
+
if (!enabled || typeof send !== "function") return null;
|
|
11
|
+
const epoch = producerEpoch();
|
|
12
|
+
const buffer = createEventBuffer({ producerEpoch: epoch, ...(capacity === undefined ? {} : { capacity }) });
|
|
13
|
+
let cursor = { producerEpoch: epoch, sequence: 0 };
|
|
14
|
+
let sending = false;
|
|
15
|
+
let scheduled = false;
|
|
16
|
+
let closed = false;
|
|
17
|
+
function schedule() {
|
|
18
|
+
if (closed || sending || scheduled) return;
|
|
19
|
+
scheduled = true;
|
|
20
|
+
setImmediate(flush);
|
|
21
|
+
}
|
|
22
|
+
function flush() {
|
|
23
|
+
scheduled = false;
|
|
24
|
+
if (closed || sending) return;
|
|
25
|
+
const batch = buffer.readAfter(cursor);
|
|
26
|
+
if (!batch.events.length) return;
|
|
27
|
+
sending = true;
|
|
28
|
+
let settled = false;
|
|
29
|
+
const finish = (error) => {
|
|
30
|
+
if (settled) return;
|
|
31
|
+
settled = true;
|
|
32
|
+
sending = false;
|
|
33
|
+
if (error) { closed = true; return; }
|
|
34
|
+
cursor = batch.cursor;
|
|
35
|
+
if (buffer.readAfter(cursor).events.length) schedule();
|
|
36
|
+
};
|
|
37
|
+
try { send({ type: "chat-relay-full-events", ...batch }, finish); }
|
|
38
|
+
catch (error) { finish(error); }
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
publish(type, requestId, action, observability, outcome = {}) {
|
|
42
|
+
if (closed) return;
|
|
43
|
+
// A malformed or failing observer never changes the tool result.
|
|
44
|
+
try {
|
|
45
|
+
buffer.append({ type, requestId, action, at: now(), ...toolCorrelation(observability),
|
|
46
|
+
...(typeof outcome.ok === "boolean" ? { ok: outcome.ok } : {}),
|
|
47
|
+
...(Number.isFinite(outcome.durationMs) ? { durationMs: outcome.durationMs } : {}) });
|
|
48
|
+
schedule();
|
|
49
|
+
} catch {}
|
|
50
|
+
},
|
|
51
|
+
close() { closed = true; },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import {createHash,randomUUID} from "node:crypto";
|
|
2
|
+
import {FullContractError} from "../packages/full-contracts/index.mjs";
|
|
3
|
+
import {DESKTOP_BROKER_OPERATION,RESOURCE_HEALTH_OPERATION} from "../packages/full-contracts/remote-session.mjs";
|
|
4
|
+
import {AGENT_EFFECT_KEY} from "./full-job-broker.mjs";
|
|
5
|
+
const check=(ok,code)=>{if(!ok)throw new FullContractError(code);};
|
|
6
|
+
const hash=value=>createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
7
|
+
const unresolved=error=>["full_outcome_unknown","full_settlement_unknown","full_unavailable"].includes(error?.code);
|
|
8
|
+
const sameCoreReceipts=new WeakMap();
|
|
9
|
+
const timing=result=>Object.fromEntries(Object.entries(result?.timing??{}).filter(([key,value])=>
|
|
10
|
+
["queueWaitMs","inputMs","explicitWaitMs","settleMs","workerMs","managerMs","totalMs","requestedActions","executedActions"].includes(key)&&Number.isFinite(value)&&value>=0));
|
|
11
|
+
|
|
12
|
+
/** Uses the existing Core DesktopManager and scheduler. Desktop input can
|
|
13
|
+
* affect arbitrary applications/files, so it holds the same agent-wide
|
|
14
|
+
* exclusive effect claim as arbitrary shell jobs. Delivery is not app success.
|
|
15
|
+
* No screenshot, clipboard value, action text, window title or result is persisted. */
|
|
16
|
+
export async function createRemoteDesktopActions({host,artifact,scheduler,desktop,legacyBusy=()=>false}){
|
|
17
|
+
const config=desktop?.getConfig?.();
|
|
18
|
+
if(!artifact.capabilities.includes("full.desktop")||!host.operations.includes(DESKTOP_BROKER_OPERATION)||!config?.enabled||!config.supported)return null;
|
|
19
|
+
check(scheduler?.fullAdmission&&typeof desktop.listWindows==="function"&&typeof desktop.step==="function","full_capability_unavailable");
|
|
20
|
+
const held=sameCoreReceipts.get(scheduler)??new Map();sameCoreReceipts.set(scheduler,held);
|
|
21
|
+
const running=new Map();
|
|
22
|
+
let closing=false,starts=0;
|
|
23
|
+
const rpc=(invocation,kind,fields={})=>host.request(DESKTOP_BROKER_OPERATION,{invocation,kind,...fields},
|
|
24
|
+
{taskSessionId:invocation.input.taskSessionId,timeoutMs:8000,waitForSettlement:true});
|
|
25
|
+
const fields=entry=>({attemptId:entry.attemptId,requestFingerprint:entry.fingerprint});
|
|
26
|
+
async function health(){
|
|
27
|
+
const result=await host.request(RESOURCE_HEALTH_OPERATION,undefined,{timeoutMs:1000});
|
|
28
|
+
check(Number.isSafeInteger(result?.unresolved)&&result.unresolved>=0,"full_recovery_state_unknown");
|
|
29
|
+
scheduler.fullAdmission.setRecoveryBlocked(result.unresolved>0||held.size>0);
|
|
30
|
+
}
|
|
31
|
+
function fence(entry){
|
|
32
|
+
entry.lease.quarantine();held.set(entry.attemptId,entry);scheduler.fullAdmission.setRecoveryBlocked(true);
|
|
33
|
+
}
|
|
34
|
+
async function reconcile(entry){
|
|
35
|
+
if(!entry.receiptKnown)return false;
|
|
36
|
+
const prior=await rpc(entry.invocation,"lookup",fields(entry));
|
|
37
|
+
if(prior){
|
|
38
|
+
const saved=await rpc(entry.invocation,"finish",{...fields(entry),previousOwnerEpoch:entry.epoch,state:"released",notIssued:entry.notIssued});
|
|
39
|
+
check(saved?.acknowledged===true&&saved.deliveryState===(entry.notIssued?"not-dispatched":"settled"),"full_desktop_receipt_pending");
|
|
40
|
+
}else check(entry.notIssued===true,"full_desktop_intent_required");
|
|
41
|
+
// Exact same-Core receipt + authoritative durable finish/absence ACK.
|
|
42
|
+
entry.lease.confirmRequestSettled({commitConfirmed:true,ownerEpoch:entry.epoch,attemptId:entry.attemptId});
|
|
43
|
+
held.delete(entry.attemptId);await health();return true;
|
|
44
|
+
}
|
|
45
|
+
for(const entry of [...held.values()]){
|
|
46
|
+
try{await reconcile(entry);}catch{/* missing/unknown receipt stays fenced */}
|
|
47
|
+
}
|
|
48
|
+
if(held.size)scheduler.fullAdmission.setRecoveryBlocked(true);
|
|
49
|
+
async function dispatch(invocation,parsed){
|
|
50
|
+
check(!closing,"full_unavailable");
|
|
51
|
+
const {input,principal,operation}=parsed,taskSessionId=input.taskSessionId;
|
|
52
|
+
const step=operation==="full.desktop.step";
|
|
53
|
+
if(step)starts++; // Fence new legacy mutations before the first await.
|
|
54
|
+
try{
|
|
55
|
+
const binding=await rpc(invocation,"snapshot");
|
|
56
|
+
const owner={accountId:principal.accountId,agentId:principal.agentId,taskSessionId};
|
|
57
|
+
const attemptId=step?"desktop-"+hash([principal.accountId,principal.agentId,taskSessionId,input.idempotencyKey]):randomUUID();
|
|
58
|
+
const fingerprint=hash([binding.workspaceId,input.actions??null,input.settleMs??null]);
|
|
59
|
+
if(step){
|
|
60
|
+
const active=running.get(attemptId);
|
|
61
|
+
if(active){check(active.fingerprint===fingerprint,"full_idempotency_conflict");return {attemptId,deliveryState:"running",replayed:false,applicationOutcome:"not-verified"};}
|
|
62
|
+
let prior=await rpc(invocation,"lookup",{attemptId,requestFingerprint:fingerprint});
|
|
63
|
+
const receipt=held.get(attemptId);
|
|
64
|
+
if(receipt?.receiptKnown){await reconcile(receipt);prior=await rpc(invocation,"lookup",{attemptId,requestFingerprint:fingerprint});}
|
|
65
|
+
if(prior){
|
|
66
|
+
if(["settled","not-dispatched"].includes(prior.deliveryState)&&scheduler.fullAdmission.recoveryBlocked)await health();
|
|
67
|
+
const state=receipt?.notIssued&&!held.has(attemptId)?"not-dispatched":prior.deliveryState;
|
|
68
|
+
return {attemptId,deliveryState:state,replayed:false,resultRetained:false,applicationOutcome:"not-verified"};
|
|
69
|
+
}
|
|
70
|
+
check(!legacyBusy(),"full_legacy_effect_active");
|
|
71
|
+
}
|
|
72
|
+
check(!scheduler.fullAdmission.recoveryBlocked,"full_recovery_state_unknown");
|
|
73
|
+
if(step)check(!["completed","cancelled"].includes(binding.status),"full_session_terminal");
|
|
74
|
+
const claims=[{key:AGENT_EFFECT_KEY,mode:step?"exclusive":"read"},{key:"desktop:agent",mode:step?"exclusive":"read"},{key:"workspace:"+binding.workspaceId,mode:"read"}];
|
|
75
|
+
return await scheduler.runFull("desktop.window.list",async(_meta,lease)=>{
|
|
76
|
+
check(!closing,"full_unavailable");
|
|
77
|
+
const current=await rpc(invocation,"snapshot");
|
|
78
|
+
check(current.workspaceId===binding.workspaceId,"full_workspace_conflict");
|
|
79
|
+
if(!step){
|
|
80
|
+
const result=await desktop.listWindows({limit:input.limit??32});
|
|
81
|
+
check(result?.ok===true&&Array.isArray(result.windows),"full_desktop_unavailable");
|
|
82
|
+
return {workspaceId:binding.workspaceId,windows:result.windows.slice(0,input.limit??32).map(row=>({
|
|
83
|
+
windowId:String(row.windowId).slice(0,128),processId:row.processId,title:String(row.title).slice(0,512),
|
|
84
|
+
x:row.x,y:row.y,width:row.width,height:row.height,isForeground:row.isForeground===true
|
|
85
|
+
})),provenance:"core-desktop-observation"};
|
|
86
|
+
}
|
|
87
|
+
check(!legacyBusy(),"full_legacy_effect_active");
|
|
88
|
+
check(!["completed","cancelled"].includes(current.status),"full_session_terminal");
|
|
89
|
+
const entry={invocation,attemptId,fingerprint,epoch:host.ownerEpoch,lease,receiptKnown:false,notIssued:true};
|
|
90
|
+
running.set(attemptId,entry);
|
|
91
|
+
let reserved=false;
|
|
92
|
+
try{
|
|
93
|
+
let saved;
|
|
94
|
+
try{saved=await rpc(invocation,"reserve",{...fields(entry),claims:lease.snapshot().claims});}
|
|
95
|
+
catch(error){if(unresolved(error)){entry.receiptKnown=true;fence(entry);}throw error;}
|
|
96
|
+
if(saved?.acknowledged!==true||typeof saved.accepted!=="boolean"){entry.receiptKnown=true;fence(entry);throw new FullContractError("full_desktop_intent_unsaved");}
|
|
97
|
+
if(saved.accepted!==true)return {attemptId,deliveryState:"previously-accepted",replayed:false,applicationOutcome:"not-verified"};
|
|
98
|
+
reserved=true;entry.notIssued=false;
|
|
99
|
+
let result;
|
|
100
|
+
try{result=await desktop.step({actions:input.actions,settleMs:input.settleMs,captureAfter:false});}
|
|
101
|
+
catch{fence(entry);throw new FullContractError("full_desktop_outcome_unknown");}
|
|
102
|
+
// Only the actual worker's successful reply proves input delivery.
|
|
103
|
+
// An arbitrary error, timeout or process exit does not prove no effect.
|
|
104
|
+
if(result?.ok!==true){
|
|
105
|
+
fence(entry);
|
|
106
|
+
try{await rpc(invocation,"finish",{...fields(entry),previousOwnerEpoch:entry.epoch,state:"quarantined"});}catch{}
|
|
107
|
+
throw new FullContractError("full_desktop_outcome_unknown");
|
|
108
|
+
}
|
|
109
|
+
entry.receiptKnown=true;
|
|
110
|
+
try{
|
|
111
|
+
const finished=await rpc(invocation,"finish",{...fields(entry),previousOwnerEpoch:entry.epoch,state:"released"});
|
|
112
|
+
check(finished?.acknowledged===true&&finished.deliveryState==="settled","full_desktop_receipt_pending");
|
|
113
|
+
}catch{fence(entry);throw new FullContractError("full_desktop_receipt_pending");}
|
|
114
|
+
return {attemptId,deliveryState:"completed",replayed:false,applicationOutcome:"not-verified",timing:timing(result)};
|
|
115
|
+
}catch(error){
|
|
116
|
+
if(reserved&&!entry.receiptKnown&&!held.has(attemptId))fence(entry);
|
|
117
|
+
throw error;
|
|
118
|
+
}finally{running.delete(attemptId);}
|
|
119
|
+
},{owner,ownerEpoch:host.ownerEpoch,attemptId,claims,priority:"task",dependenciesReady:true,queueTimeoutMs:8000});
|
|
120
|
+
}finally{if(step)starts--;}
|
|
121
|
+
}
|
|
122
|
+
return Object.freeze({dispatch,capabilities:["full.desktop"],blocksLegacyEffects:()=>starts>0||running.size>0||held.size>0,
|
|
123
|
+
close(){closing=true;return held.size===0;}});
|
|
124
|
+
}
|