@agentconnect.md/computer 2.12.0-rc.13 → 2.12.0-rc.18

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.
@@ -67280,2131 +67280,2159 @@ var StdioServerTransport = class {
67280
67280
  }
67281
67281
  };
67282
67282
 
67283
- // src/admin-prompts.ts
67284
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67285
- import { spawn } from "node:child_process";
67286
- import { createInterface } from "node:readline";
67287
- var ANSWER_TIMEOUT_MS = 1e4;
67288
- var RESTART_MS = 5e3;
67289
- var str = (value) => typeof value === "string" && value !== "" ? value : void 0;
67290
- var AdminPromptHelper = class _AdminPromptHelper {
67291
- constructor(path, options) {
67292
- this.path = path;
67293
- this.options = options;
67294
- }
67295
- path;
67296
- options;
67297
- problem;
67298
- current;
67299
- child;
67300
- closed = false;
67301
- waiting = /* @__PURE__ */ new Map();
67302
- static start(path, options) {
67303
- const helper = new _AdminPromptHelper(path, options);
67304
- helper.spawn();
67305
- return helper;
67306
- }
67307
- pending() {
67308
- return this.current;
67309
- }
67310
- answer(id, answer) {
67311
- const child2 = this.child;
67312
- if (!child2?.stdin || this.problem)
67313
- return Promise.reject(new Error(this.problem ?? "the prompt helper is not running"));
67314
- return new Promise((resolve5, reject) => {
67315
- const timer = setTimeout(() => {
67316
- this.waiting.delete(id);
67317
- reject(new Error("the prompt helper did not answer in time"));
67318
- }, ANSWER_TIMEOUT_MS);
67319
- timer.unref();
67320
- this.waiting.set(id, {
67321
- resolve: () => (clearTimeout(timer), resolve5()),
67322
- reject: (error63) => (clearTimeout(timer), reject(error63))
67323
- });
67324
- child2.stdin.write(`${JSON.stringify({ id, answer })}
67325
- `);
67326
- });
67327
- }
67328
- close() {
67329
- this.closed = true;
67330
- this.child?.stdin?.end();
67331
- }
67332
- spawn() {
67333
- const child2 = (this.options.spawnHelper ?? ((file2) => spawn(file2, [], { stdio: ["pipe", "pipe", "inherit"], windowsHide: true })))(this.path);
67334
- this.child = child2;
67335
- child2.stdin?.on("error", () => void 0);
67336
- child2.on("error", (error63) => this.gone(`cannot start the administrator prompt helper: ${error63.message}`));
67337
- child2.on(
67338
- "exit",
67339
- (code, signal) => this.gone(`the administrator prompt helper exited (${signal ?? `code ${code}`})`)
67340
- );
67341
- if (child2.stdout) createInterface({ input: child2.stdout }).on("line", (line) => this.received(line));
67342
- }
67343
- received(line) {
67344
- let message;
67345
- try {
67346
- message = JSON.parse(line);
67347
- } catch {
67348
- return;
67349
- }
67350
- const id = str(message.id);
67351
- switch (message.event) {
67352
- case "prompt": {
67353
- if (!id) return;
67354
- this.current = {
67355
- id,
67356
- kind: message.kind === "credentials" ? "credentials" : "consent",
67357
- ...str(message.app) ? { app: str(message.app) } : {},
67358
- ...str(message.publisher) ? { publisher: str(message.publisher) } : {},
67359
- ...str(message.command) ? { command: str(message.command) } : {},
67360
- lines: Array.isArray(message.lines) ? message.lines.filter((l) => typeof l === "string") : []
67361
- };
67362
- this.options.log(`administrator prompt: ${this.current.app ?? "an app"} asks to run as administrator`);
67363
- return this.options.onChange();
67364
- }
67365
- case "gone":
67366
- if (id && this.current?.id === id) {
67367
- this.current = void 0;
67368
- this.options.onChange();
67369
- }
67370
- return;
67371
- case "answered": {
67372
- const waiter = id ? this.waiting.get(id) : void 0;
67373
- if (!waiter || !id) return;
67374
- this.waiting.delete(id);
67375
- if (message.ok === true) waiter.resolve();
67376
- else waiter.reject(new Error(str(message.error) ?? "the prompt could not be answered"));
67377
- return;
67378
- }
67379
- case "problem": {
67380
- const problem = str(message.message);
67381
- if (problem === this.problem) return;
67382
- this.problem = problem;
67383
- if (problem) this.options.log(`administrator prompts: ${problem}`);
67384
- return this.options.onChange();
67385
- }
67386
- }
67387
- }
67388
- gone(problem) {
67389
- if (this.closed) return;
67390
- this.problem = problem;
67391
- this.current = void 0;
67392
- for (const waiter of this.waiting.values()) waiter.reject(new Error(problem));
67393
- this.waiting.clear();
67394
- this.options.log(`administrator prompts: ${problem}; starting it again`);
67395
- this.options.onChange();
67396
- const child2 = this.child;
67397
- this.child = void 0;
67398
- if (child2)
67399
- setTimeout(() => {
67400
- if (this.closed) return;
67401
- this.problem = void 0;
67402
- this.spawn();
67403
- }, this.options.restartMs ?? RESTART_MS).unref();
67404
- }
67405
- };
67406
-
67407
- // src/audit.ts
67283
+ // ../protocol/src/frames/computer.ts
67408
67284
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67409
- import { AsyncLocalStorage } from "node:async_hooks";
67410
- import { appendFileSync, mkdirSync } from "node:fs";
67411
- import { dirname } from "node:path";
67412
- var callContext = new AsyncLocalStorage();
67413
- var withCallContext = (context, fn) => callContext.run(context, fn);
67414
- var currentCallContext = () => callContext.getStore() ?? {};
67415
- function auditSinks(...sinks) {
67416
- return (record2) => {
67417
- const full = { ...callContext.getStore(), ...record2 };
67418
- for (const sink of sinks) sink(full);
67419
- };
67420
- }
67421
- function redactArgs(args) {
67422
- const out = {};
67423
- for (const [key, value] of Object.entries(args)) {
67424
- out[key] = (key === "text" || key === "value" || key === "content") && typeof value === "string" ? `<${value.length} chars>` : value;
67425
- }
67426
- return out;
67427
- }
67428
- function fileAuditSink(path) {
67429
- mkdirSync(dirname(path), { recursive: true });
67430
- return (record2) => {
67431
- const line = JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record2, args: redactArgs(record2.args) });
67432
- try {
67433
- appendFileSync(path, `${line}
67434
- `);
67435
- } catch (error63) {
67436
- console.error(`audit write failed: ${error63.message}`);
67437
- }
67438
- };
67439
- }
67440
67285
 
67441
- // src/browser/command.ts
67286
+ // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/index.js
67442
67287
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67443
67288
 
67444
- // src/browser/close.ts
67289
+ // ../protocol/src/envelope.ts
67445
67290
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67291
+ var Envelope = external_exports.object({
67292
+ v: external_exports.literal(1),
67293
+ // protocol major; bump = breaking
67294
+ id: external_exports.string().uuid(),
67295
+ // unique per frame (sender-generated)
67296
+ ts: external_exports.string().datetime(),
67297
+ // RFC3339, sender clock (advisory only)
67298
+ type: external_exports.string(),
67299
+ // frame discriminator, e.g. "register"
67300
+ corr: external_exports.string().uuid().optional(),
67301
+ // correlation: set on a reply to the request's `id`
67302
+ orgId: external_exports.string().min(1).max(64).optional(),
67303
+ // tenant context on an install-wide daemon connection
67304
+ payload: external_exports.unknown()
67305
+ // validated by the per-type schema
67306
+ });
67307
+ var ControlExt = external_exports.object({
67308
+ epoch: external_exports.number().int(),
67309
+ // sessionEpoch this frame was issued under (§3.1 fencing)
67310
+ agentId: external_exports.string().uuid().optional(),
67311
+ // present on agent-scoped frames
67312
+ launchId: external_exports.string().uuid().optional()
67313
+ // per-launch fence, §4.4
67314
+ });
67315
+ var NIL_UUID = "00000000-0000-0000-0000-000000000000";
67316
+ function frameSchema(type, payload) {
67317
+ return external_exports.object({
67318
+ v: external_exports.literal(1),
67319
+ id: external_exports.string().uuid(),
67320
+ ts: external_exports.string().datetime(),
67321
+ type: external_exports.literal(type),
67322
+ corr: external_exports.string().uuid().optional(),
67323
+ orgId: external_exports.string().min(1).max(64).optional(),
67324
+ payload
67325
+ });
67326
+ }
67446
67327
 
67447
- // src/linux/x11.ts
67328
+ // ../protocol/src/tolerant.ts
67448
67329
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67449
- import { readFileSync } from "node:fs";
67450
- import { createConnection } from "node:net";
67451
- import { homedir, hostname as hostname3 } from "node:os";
67452
- import { join } from "node:path";
67453
- function parseDisplay(display) {
67454
- const match = /^([^:]*):(\d+)(?:\.\d+)?$/.exec(display ?? "");
67455
- if (!match) return void 0;
67456
- const host = match[1] ?? "";
67457
- const number4 = Number(match[2]);
67458
- if (host === "" || host === "unix") return { path: `/tmp/.X11-unix/X${number4}`, number: number4 };
67459
- return { host, port: 6e3 + number4, number: number4 };
67330
+ var memo3 = /* @__PURE__ */ new WeakMap();
67331
+ function tolerantReader(schema) {
67332
+ const hit = memo3.get(schema);
67333
+ if (hit) return hit;
67334
+ const built = rebuild(schema);
67335
+ memo3.set(schema, built);
67336
+ return built;
67460
67337
  }
67461
- var FAMILY_LOCAL = 256;
67462
- var FAMILY_WILD = 65535;
67463
- var COOKIE = "MIT-MAGIC-COOKIE-1";
67464
- function xauthCookie(file2, number4, host = hostname3()) {
67465
- let offset = 0;
67466
- let fallback;
67467
- const field = () => {
67468
- const length = file2.readUInt16BE(offset);
67469
- const value = file2.subarray(offset + 2, offset + 2 + length);
67470
- offset += 2 + length;
67471
- return value;
67472
- };
67473
- try {
67474
- while (offset < file2.length) {
67475
- const family = file2.readUInt16BE(offset);
67476
- offset += 2;
67477
- const address = field().toString("latin1");
67478
- const display = field().toString("latin1");
67479
- const name = field().toString("latin1");
67480
- const data = field();
67481
- if (name !== COOKIE || display !== "" && display !== String(number4)) continue;
67482
- if (family === FAMILY_WILD || family === FAMILY_LOCAL && address === host) return Buffer.from(data);
67483
- fallback ??= Buffer.from(data);
67484
- }
67485
- } catch {
67486
- }
67487
- return fallback;
67338
+ function tolerantSchemas(schemas) {
67339
+ return Object.fromEntries(Object.entries(schemas).map(([type, schema]) => [type, tolerantReader(schema)]));
67488
67340
  }
67489
- var pad4 = (n) => (4 - n % 4) % 4;
67490
- var X11Error = class extends Error {
67491
- constructor(code, sequence) {
67492
- super(`X11 error ${code} (request ${sequence})`);
67493
- this.code = code;
67494
- this.sequence = sequence;
67495
- this.name = "X11Error";
67496
- }
67497
- code;
67498
- sequence;
67499
- };
67500
- var X11Connection = class _X11Connection {
67501
- constructor(socket, setup2) {
67502
- this.socket = socket;
67503
- this.setup = setup2;
67504
- socket.on("data", (chunk) => this.receive(chunk));
67505
- socket.on("error", (error63) => this.close(error63));
67506
- socket.on("close", () => this.close());
67507
- }
67508
- socket;
67509
- setup;
67510
- buffer = Buffer.alloc(0);
67511
- sequence = 0;
67512
- pending = /* @__PURE__ */ new Map();
67513
- errors = /* @__PURE__ */ new Map();
67514
- closed = false;
67515
- onEvent = () => void 0;
67516
- onClose = () => void 0;
67517
- static async connect(options = {}) {
67518
- const address = parseDisplay(options.display ?? process.env.DISPLAY);
67519
- if (!address) throw new Error("DISPLAY is not set to an X11 display");
67520
- const authFile = options.xauthority ?? process.env.XAUTHORITY ?? join(homedir(), ".Xauthority");
67521
- let cookie;
67522
- try {
67523
- cookie = xauthCookie(readFileSync(authFile), address.number);
67524
- } catch {
67341
+ function isSchema(value) {
67342
+ return typeof value === "object" && value !== null && "_zod" in value;
67343
+ }
67344
+ function defOf(schema) {
67345
+ return schema._zod.def;
67346
+ }
67347
+ function child(value) {
67348
+ return tolerantReader(value);
67349
+ }
67350
+ function withDef(schema, def) {
67351
+ return external_exports.clone(schema, def);
67352
+ }
67353
+ function rebuild(schema) {
67354
+ const def = defOf(schema);
67355
+ switch (def.type) {
67356
+ case "object": {
67357
+ const shape = Object.fromEntries(
67358
+ Object.entries(def.shape).map(([key, value]) => [key, child(value)])
67359
+ );
67360
+ const catchall = isNeverSchema(def.catchall) ? void 0 : def.catchall ? child(def.catchall) : void 0;
67361
+ return withDef(schema, { ...def, shape, catchall });
67525
67362
  }
67526
- const socket = options.socketPath ? createConnection(options.socketPath) : "path" in address ? createConnection(address.path) : createConnection(address.port, address.host);
67527
- socket.setNoDelay(true);
67528
- const timeoutMs = options.timeoutMs ?? 5e3;
67529
- const setup2 = await new Promise((resolve5, reject) => {
67530
- let data = Buffer.alloc(0);
67531
- const timer = setTimeout(() => fail(new Error("X11 connection setup timed out")), timeoutMs);
67532
- const fail = (error63) => {
67533
- clearTimeout(timer);
67534
- socket.off("data", onData);
67535
- socket.destroy();
67536
- reject(error63);
67537
- };
67538
- const onData = (chunk) => {
67539
- data = Buffer.concat([data, chunk]);
67540
- if (data.length < 8) return;
67541
- const total = 8 + data.readUInt16LE(6) * 4;
67542
- if (data.length < total) return;
67543
- clearTimeout(timer);
67544
- socket.off("data", onData);
67545
- socket.off("error", fail);
67546
- if (data[0] !== 1) {
67547
- const reason = data.subarray(8, 8 + (data[1] ?? 0)).toString("latin1");
67548
- socket.destroy();
67549
- return reject(new Error(`X11 server refused the connection: ${reason || "authorization required"}`));
67550
- }
67551
- try {
67552
- resolve5({ setup: parseSetup(data.subarray(0, total)), rest: data.subarray(total) });
67553
- } catch (error63) {
67554
- fail(error63);
67555
- }
67556
- };
67557
- socket.once("error", fail);
67558
- socket.on("data", onData);
67559
- socket.write(setupRequest(cookie));
67560
- });
67561
- const connection = new _X11Connection(socket, setup2.setup);
67562
- if (setup2.rest.length) connection.receive(setup2.rest);
67563
- return connection;
67564
- }
67565
- listen(listener) {
67566
- this.onEvent = listener;
67567
- }
67568
- whenClosed(listener) {
67569
- this.onClose = listener;
67570
- }
67571
- /** Sends a request that has a reply and resolves with the whole reply. */
67572
- request(body) {
67573
- if (this.closed) return Promise.reject(new Error("X11 connection closed"));
67574
- const sequence = this.send(body);
67575
- return new Promise((resolve5, reject) => this.pending.set(sequence, { resolve: resolve5, reject }));
67363
+ case "array":
67364
+ return withDef(schema, { ...def, element: child(def.element) });
67365
+ // Both plain and discriminated unions; the discriminator rides along in the spread def.
67366
+ case "union":
67367
+ return withDef(schema, { ...def, options: def.options.map(child) });
67368
+ case "intersection":
67369
+ return withDef(schema, { ...def, left: child(def.left), right: child(def.right) });
67370
+ case "tuple":
67371
+ return withDef(schema, {
67372
+ ...def,
67373
+ items: def.items.map(child),
67374
+ ...isSchema(def.rest) ? { rest: child(def.rest) } : {}
67375
+ });
67376
+ case "record":
67377
+ case "map":
67378
+ return withDef(schema, { ...def, keyType: child(def.keyType), valueType: child(def.valueType) });
67379
+ case "set":
67380
+ return withDef(schema, { ...def, valueType: child(def.valueType) });
67381
+ case "optional":
67382
+ case "nullable":
67383
+ case "nonoptional":
67384
+ case "default":
67385
+ case "prefault":
67386
+ case "catch":
67387
+ case "readonly":
67388
+ case "promise":
67389
+ return withDef(schema, { ...def, innerType: child(def.innerType) });
67390
+ case "pipe":
67391
+ return withDef(schema, { ...def, in: child(def.in), out: child(def.out) });
67392
+ case "lazy":
67393
+ return external_exports.lazy(() => child(def.getter()));
67394
+ default:
67395
+ return schema;
67576
67396
  }
67577
- /** Sends a request without a reply; resolves once the server processed it, rejecting with its error. */
67578
- async checked(body) {
67579
- const sequence = this.send(body);
67580
- await this.request(request(43, 0, Buffer.alloc(0)));
67581
- const error63 = this.errors.get(sequence);
67582
- this.errors.delete(sequence);
67583
- if (error63) throw error63;
67397
+ }
67398
+ function isNeverSchema(value) {
67399
+ return isSchema(value) && defOf(value).type === "never";
67400
+ }
67401
+
67402
+ // ../protocol/src/wire.ts
67403
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67404
+ import { randomUUID } from "node:crypto";
67405
+ var MAX_FRAME_BYTES = 256 * 1024;
67406
+ var REPLY_BUDGET = MAX_FRAME_BYTES - 4096;
67407
+ var textEncoder = new TextEncoder();
67408
+ function byteLength(text) {
67409
+ return textEncoder.encode(text).length;
67410
+ }
67411
+ function extractControlExt(json5) {
67412
+ if (typeof json5 !== "object" || json5 === null) return void 0;
67413
+ const o = json5;
67414
+ const ext = {};
67415
+ if (typeof o.epoch === "number") ext.epoch = o.epoch;
67416
+ if (typeof o.agentId === "string") ext.agentId = o.agentId;
67417
+ if (typeof o.launchId === "string") ext.launchId = o.launchId;
67418
+ return Object.keys(ext).length > 0 ? ext : void 0;
67419
+ }
67420
+ function decodeEnvelopeWith(schemas, text, opts = {}) {
67421
+ if (byteLength(text) > (opts.maxBytes ?? MAX_FRAME_BYTES)) {
67422
+ return { ok: false, id: NIL_UUID, msg: "FRAME_TOO_LARGE" };
67584
67423
  }
67585
- close(error63) {
67586
- if (this.closed) return;
67587
- this.closed = true;
67588
- this.socket.destroy();
67589
- for (const pending of this.pending.values()) pending.reject(error63 ?? new Error("X11 connection closed"));
67590
- this.pending.clear();
67591
- this.onClose(error63);
67424
+ let json5;
67425
+ try {
67426
+ json5 = JSON.parse(text);
67427
+ } catch {
67428
+ return { ok: false, id: NIL_UUID, msg: "invalid json" };
67592
67429
  }
67593
- send(body) {
67594
- this.sequence = this.sequence + 1 & 65535;
67595
- this.socket.write(body);
67596
- return this.sequence;
67430
+ const env = Envelope.safeParse(json5);
67431
+ if (!env.success) {
67432
+ const id = typeof json5 === "object" && json5 !== null && typeof json5.id === "string" ? json5.id : NIL_UUID;
67433
+ return { ok: false, id, msg: env.error.message };
67597
67434
  }
67598
- receive(chunk) {
67599
- this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;
67600
- while (this.buffer.length >= 32) {
67601
- const kind = this.buffer[0] & 127;
67602
- const total = kind === 1 || kind === 35 ? 32 + this.buffer.readUInt32LE(4) * 4 : 32;
67603
- if (this.buffer.length < total) return;
67604
- const message = this.buffer.subarray(0, total);
67605
- this.buffer = this.buffer.subarray(total);
67606
- this.dispatch(kind, message);
67607
- }
67435
+ const schema = Object.hasOwn(schemas, env.data.type) ? schemas[env.data.type] : void 0;
67436
+ if (!schema) {
67437
+ return {
67438
+ ok: false,
67439
+ id: env.data.id,
67440
+ msg: "UNKNOWN_FRAME",
67441
+ ...env.data.corr ? { corr: env.data.corr } : {}
67442
+ };
67608
67443
  }
67609
- dispatch(kind, message) {
67610
- const sequence = message.readUInt16LE(2);
67611
- if (kind === 1 || kind === 0) {
67612
- const pending = this.pending.get(sequence);
67613
- if (pending) {
67614
- this.pending.delete(sequence);
67615
- if (kind === 1) pending.resolve(Buffer.from(message));
67616
- else pending.reject(new X11Error(message[1], sequence));
67617
- return;
67618
- }
67619
- if (kind === 0) {
67620
- this.errors.set(sequence, new X11Error(message[1], sequence));
67621
- if (this.errors.size > 64) this.errors.delete(this.errors.keys().next().value);
67622
- }
67623
- return;
67624
- }
67625
- this.onEvent(Buffer.from(message));
67444
+ const payload = schema.safeParse(env.data.payload);
67445
+ if (!payload.success) {
67446
+ return {
67447
+ ok: false,
67448
+ id: env.data.id,
67449
+ msg: payload.error.message,
67450
+ ...env.data.corr ? { corr: env.data.corr } : {}
67451
+ };
67626
67452
  }
67627
- };
67628
- function setupRequest(cookie) {
67629
- const name = cookie ? Buffer.from(COOKIE, "latin1") : Buffer.alloc(0);
67630
- const data = cookie ?? Buffer.alloc(0);
67631
- const out = Buffer.alloc(12 + name.length + pad4(name.length) + data.length + pad4(data.length));
67632
- out.write("l", 0, "latin1");
67633
- out.writeUInt16LE(11, 2);
67634
- out.writeUInt16LE(0, 4);
67635
- out.writeUInt16LE(name.length, 6);
67636
- out.writeUInt16LE(data.length, 8);
67637
- name.copy(out, 12);
67638
- data.copy(out, 12 + name.length + pad4(name.length));
67639
- return out;
67640
- }
67641
- function parseSetup(reply2) {
67642
- const vendorLength = reply2.readUInt16LE(24);
67643
- const formats = reply2[29];
67644
- const minKeycode = reply2[34];
67645
- const maxKeycode = reply2[35];
67646
- const screens = 40 + vendorLength + pad4(vendorLength) + formats * 8;
67647
- if (reply2.length < screens + 4) throw new Error("X11 setup reply has no screen");
67648
- return { root: reply2.readUInt32LE(screens), minKeycode, maxKeycode };
67453
+ const ext = extractControlExt(json5);
67454
+ return {
67455
+ ok: true,
67456
+ frame: { ...env.data, payload: payload.data },
67457
+ ...ext ? { ext } : {}
67458
+ };
67649
67459
  }
67650
- function request(opcode, minor, body) {
67651
- const out = Buffer.alloc(4 + body.length + pad4(body.length));
67652
- out[0] = opcode;
67653
- out[1] = minor;
67654
- out.writeUInt16LE(out.length / 4, 2);
67655
- body.copy(out, 4);
67656
- return out;
67657
- }
67658
- var OP_GRAB_KEY = 33;
67659
- var OP_UNGRAB_KEY = 34;
67660
- var OP_QUERY_EXTENSION = 98;
67661
- var OP_GET_KEYBOARD_MAPPING = 101;
67662
- var OP_GET_MODIFIER_MAPPING = 119;
67663
- async function queryExtension(x, name) {
67664
- const bytes = Buffer.from(name, "latin1");
67665
- const body = Buffer.alloc(4 + bytes.length);
67666
- body.writeUInt16LE(bytes.length, 0);
67667
- bytes.copy(body, 4);
67668
- const reply2 = await x.request(request(OP_QUERY_EXTENSION, 0, body));
67669
- return reply2[8] ? reply2[9] : void 0;
67460
+ function buildEnvelopeRaw(type, payload, opts = {}) {
67461
+ return {
67462
+ v: 1,
67463
+ id: opts.id ?? randomUUID(),
67464
+ ts: opts.ts ?? (/* @__PURE__ */ new Date()).toISOString(),
67465
+ type,
67466
+ payload,
67467
+ ...opts.corr ? { corr: opts.corr } : {},
67468
+ ...opts.orgId ? { orgId: opts.orgId } : {},
67469
+ ...opts.ext ?? {}
67470
+ };
67670
67471
  }
67671
67472
 
67672
- // src/browser/launcher.ts
67473
+ // ../protocol/src/frames/error.ts
67673
67474
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67674
- import { spawn as spawn2 } from "node:child_process";
67675
- import {
67676
- accessSync,
67677
- closeSync,
67678
- constants,
67679
- cpSync as cpSync2,
67680
- existsSync as existsSync3,
67681
- mkdirSync as mkdirSync3,
67682
- openSync,
67683
- readlinkSync,
67684
- realpathSync as realpathSync2,
67685
- rmSync as rmSync3,
67686
- statSync as statSync2
67687
- } from "node:fs";
67688
- import { hostname as hostname4 } from "node:os";
67689
- import { basename as basename2, delimiter, dirname as dirname2, join as join4, resolve } from "node:path";
67475
+ var ErrorCode = external_exports.enum([
67476
+ // protocol / framing
67477
+ "UNKNOWN_FRAME",
67478
+ "FRAME_TOO_LARGE",
67479
+ "PROTOCOL_STATE",
67480
+ "BAD_PAYLOAD",
67481
+ // auth / identity
67482
+ "AUTH_FAILED",
67483
+ "ATTESTATION_INVALID",
67484
+ // fencing / ordering
67485
+ "STALE_EPOCH",
67486
+ "STALE_LAUNCH",
67487
+ // delivery
67488
+ "NO_SESSION",
67489
+ "SCOPE_DENIED",
67490
+ // delegated MCP authority / invocation binding
67491
+ "DELEGATION_DENIED",
67492
+ "INVOCATION_CONFLICT",
67493
+ // secrets
67494
+ "LEASE_EXPIRED",
67495
+ "LEASE_DENIED",
67496
+ // generic
67497
+ "RATE_LIMITED",
67498
+ "CONFLICT",
67499
+ "INTERNAL"
67500
+ ]);
67501
+ var ErrorFrame = external_exports.object({
67502
+ code: ErrorCode,
67503
+ message: external_exports.string(),
67504
+ // human-readable, redacted of secrets
67505
+ retryable: external_exports.boolean(),
67506
+ details: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
67507
+ });
67690
67508
 
67691
- // src/browser/profile-merge.ts
67509
+ // ../protocol/src/frames/computer-lease.ts
67692
67510
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67693
- import {
67694
- cpSync,
67695
- existsSync as existsSync2,
67696
- mkdtempSync,
67697
- readFileSync as readFileSync3,
67698
- readdirSync as readdirSync2,
67699
- realpathSync,
67700
- rmSync as rmSync2,
67701
- statSync,
67702
- writeFileSync as writeFileSync2
67703
- } from "node:fs";
67704
- import { tmpdir } from "node:os";
67705
- import { basename, join as join3 } from "node:path";
67511
+ var ComputerDesktopId = external_exports.string().regex(/^[A-Za-z0-9_-]{1,32}$/);
67512
+ var COMPUTER_LEASE_AGENT_NAME_MAX = 200;
67513
+ var ComputerLeaseHolder = external_exports.object({
67514
+ sessionId: external_exports.string().min(1).max(256),
67515
+ agentId: external_exports.string().uuid(),
67516
+ agentName: external_exports.string().min(1).max(COMPUTER_LEASE_AGENT_NAME_MAX).optional()
67517
+ });
67518
+ var computerLeaseHolderName = (holder) => `${holder.agentId}/${holder.sessionId}`;
67519
+ var ComputerControlLease = external_exports.object({
67520
+ leaseId: external_exports.string().uuid(),
67521
+ computerId: external_exports.string().uuid(),
67522
+ holder: ComputerLeaseHolder,
67523
+ acquiredAt: external_exports.string().datetime(),
67524
+ expiresAt: external_exports.string().datetime(),
67525
+ // Behind `computer-desktops-v1`: the agent desktop it covers, keyed by that agent's id; absent, the main desktop.
67526
+ desktop: external_exports.string().uuid().optional()
67527
+ });
67528
+ var COMPUTER_LEASE_REFUSALS = ["computer_busy", "human_in_control", "unavailable", "denied"];
67529
+ var COMPUTER_LEASE_POLL_MAX_MS = 1e4;
67530
+ var COMPUTER_LEASE_WAIT_MAX_SECONDS = 600;
67531
+ var ComputerLeaseAcquire = external_exports.object({
67532
+ computerId: external_exports.string().uuid(),
67533
+ agentId: external_exports.string().uuid(),
67534
+ sessionId: external_exports.string().min(1).max(256),
67535
+ // The daemon-clock time of the request, compared with the `event/session` turn end on the same clock.
67536
+ requestedAt: external_exports.string().datetime(),
67537
+ // Behind COMPUTER_LEASE_QUEUE_FEATURE: wait in the Computer's FIFO queue, holding the reply up to this long.
67538
+ waitMs: external_exports.number().int().min(0).max(COMPUTER_LEASE_POLL_MAX_MS).optional()
67539
+ });
67540
+ var ComputerLeaseQueued = external_exports.object({
67541
+ position: external_exports.number().int().min(1),
67542
+ waitedMs: external_exports.number().int().min(0),
67543
+ // Time left before the wait ends in `computer_busy`.
67544
+ leftMs: external_exports.number().int().min(0)
67545
+ });
67546
+ var ComputerLeaseAcquireResult = external_exports.discriminatedUnion("granted", [
67547
+ external_exports.object({ granted: external_exports.literal(true), lease: ComputerControlLease }),
67548
+ external_exports.object({
67549
+ granted: external_exports.literal(false),
67550
+ code: external_exports.enum(COMPUTER_LEASE_REFUSALS),
67551
+ message: external_exports.string().max(500),
67552
+ holder: ComputerLeaseHolder.optional(),
67553
+ queued: ComputerLeaseQueued.optional()
67554
+ })
67555
+ ]);
67556
+ var ComputerLeaseRelease = external_exports.object({
67557
+ computerId: external_exports.string().uuid(),
67558
+ agentId: external_exports.string().uuid(),
67559
+ sessionId: external_exports.string().min(1).max(256)
67560
+ });
67706
67561
 
67707
- // src/browser/leveldb.ts
67562
+ // ../protocol/src/frames/computer-channel.ts
67708
67563
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67709
- import { existsSync, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
67710
- import { join as join2 } from "node:path";
67711
- var BLOCK_SIZE = 32 * 1024;
67712
- var HEADER_SIZE = 7;
67713
- var FULL = 1;
67714
- var FIRST = 2;
67715
- var MIDDLE = 3;
67716
- var LAST = 4;
67717
- var TYPE_DELETION = 0;
67718
- var TYPE_VALUE = 1;
67719
- var TABLE_MAGIC = 0xdb4775248b80fb57n;
67720
- var BATCH_LIMIT_BYTES = 1024 * 1024;
67721
- var CRC_TABLE = (() => {
67722
- const table = new Uint32Array(256);
67723
- for (let n = 0; n < 256; n++) {
67724
- let c = n;
67725
- for (let k = 0; k < 8; k++) c = c & 1 ? 2197175160 ^ c >>> 1 : c >>> 1;
67726
- table[n] = c >>> 0;
67727
- }
67728
- return table;
67729
- })();
67730
- function crc32c(data, initial = 0) {
67731
- let crc = ~initial >>> 0;
67732
- for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
67733
- return ~crc >>> 0;
67564
+
67565
+ // ../protocol/src/computer-channel-token.ts
67566
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67567
+ import { createHmac, timingSafeEqual } from "node:crypto";
67568
+
67569
+ // ../protocol/src/computer-viewer.ts
67570
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67571
+ var COMPUTER_VIEWER_API_PREFIX = "/view/api/";
67572
+ var COMPUTER_VIEWER_MAX_REQUEST_BYTES = 64 * 1024;
67573
+ var COMPUTER_VIEWER_TRANSPORTS = ["direct", "stun", "turn"];
67574
+ var ComputerIceServer = external_exports.object({
67575
+ urls: external_exports.array(
67576
+ external_exports.string().regex(/^turns?:/).max(256)
67577
+ ).min(1).max(4),
67578
+ username: external_exports.string().min(1).max(256),
67579
+ credential: external_exports.string().min(1).max(256)
67580
+ }).strict();
67581
+ var COMPUTER_ICE_SERVERS_MAX = 2;
67582
+ var ComputerStunUrl = external_exports.string().max(256).regex(/^stun:(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+)(:\d{1,5})?$/, "expected stun:<host>[:<port>]");
67583
+ var ComputerTurnUrl = external_exports.string().max(256).regex(
67584
+ /^turns?:(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+)(:\d{1,5})?(\?transport=(udp|tcp))?$/,
67585
+ "expected turn:<host>[:<port>][?transport=udp|tcp] or turns:"
67586
+ );
67587
+ var COMPUTER_STUN_URLS_MAX = 2;
67588
+ var ComputerViewerCandidate = external_exports.object({
67589
+ id: external_exports.string().min(1).max(64),
67590
+ candidate: external_exports.object({
67591
+ candidate: external_exports.string().max(1024),
67592
+ sdpMid: external_exports.string().max(64).nullish(),
67593
+ sdpMLineIndex: external_exports.number().int().min(0).max(64).nullish()
67594
+ }).nullable()
67595
+ });
67596
+ var ComputerViewerCandidatesRequest = external_exports.object({
67597
+ id: external_exports.string().min(1).max(64),
67598
+ after: external_exports.number().int().min(0).max(1e3).default(0)
67599
+ });
67600
+ var ComputerViewerOfferRequest = external_exports.object({ transport: external_exports.enum(COMPUTER_VIEWER_TRANSPORTS).optional() });
67601
+ var ComputerViewerRenewal = external_exports.object({ type: external_exports.literal("auth"), token: external_exports.string().min(1).max(4096) });
67602
+
67603
+ // ../protocol/src/computer-command-line.ts
67604
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67605
+ var COMPUTER_SHELL_MODES = ["off", "ask", "on"];
67606
+ var COMPUTER_FILES_MODES = ["off", "read", "read-write"];
67607
+ var COMPUTER_FILE_ROOTS_MAX = 32;
67608
+ var ComputerFileRoot = external_exports.string().trim().min(1).max(1024).refine((p) => /^(\/|~(\/|$)|[A-Za-z]:[\\/])/.test(p) && !p.includes("\0"), "expected an absolute path");
67609
+ var COMPUTER_EXEC_TIMEOUT_DEFAULT_MS = 3e4;
67610
+ var COMPUTER_EXEC_TIMEOUT_MAX_MS = 9e4;
67611
+ var COMPUTER_EXEC_COMMAND_MAX_CHARS = 16384;
67612
+ var COMPUTER_EXEC_OUTPUT_TAIL_BYTES = 32 * 1024;
67613
+ var COMPUTER_EXEC_PER_SESSION_MAX = 4;
67614
+ var COMPUTER_EXEC_TOTAL_MAX = 8;
67615
+ var COMPUTER_READ_TEXT_MAX_BYTES = 256 * 1024;
67616
+ var COMPUTER_READ_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
67617
+ var COMPUTER_WRITE_MAX_BYTES = 1024 * 1024;
67618
+ var COMPUTER_LIST_DIR_MAX = 1e3;
67619
+ var SHELL_RANK = { off: 0, ask: 1, on: 2 };
67620
+ var FILES_RANK = { off: 0, read: 1, "read-write": 2 };
67621
+ var narrowerShell = (a, b) => SHELL_RANK[a] <= SHELL_RANK[b] ? a : b;
67622
+ var narrowerFiles = (a, b) => FILES_RANK[a] <= FILES_RANK[b] ? a : b;
67623
+
67624
+ // ../protocol/src/computer-channel-token.ts
67625
+ var COMPUTER_CHANNEL_TOKEN_PREFIX = "actk1";
67626
+ var COMPUTER_CHANNEL_TOKEN_AUDIENCES = ["mcp", "relay", "view"];
67627
+ var COMPUTER_CHANNEL_TOKEN_MAX_TTL_MS = 5 * 6e4;
67628
+ var COMPUTER_AGENT_MODES = ["view", "control"];
67629
+ var ComputerChannelTokenClaims = external_exports.object({
67630
+ aud: external_exports.enum(COMPUTER_CHANNEL_TOKEN_AUDIENCES),
67631
+ // The Computer the token is for, and the id of the channel key that signed it.
67632
+ cmp: external_exports.string().uuid(),
67633
+ kid: external_exports.string().min(1).max(64),
67634
+ // Issue and expiry times, epoch milliseconds on the issuer's clock.
67635
+ iat: external_exports.number().int().nonnegative(),
67636
+ exp: external_exports.number().int().positive(),
67637
+ // `mcp` only: the agent session the calls belong to, its agent and daemon, and what the policy lets it do.
67638
+ ses: external_exports.string().min(1).max(256).optional(),
67639
+ agt: external_exports.string().uuid().optional(),
67640
+ dmn: external_exports.string().uuid().optional(),
67641
+ mode: external_exports.enum(COMPUTER_AGENT_MODES).optional(),
67642
+ // `mcp` only: the command-line tier the policy allows (§5.7); absent, as from an older CP, means none.
67643
+ sh: external_exports.enum(COMPUTER_SHELL_MODES).optional(),
67644
+ fs: external_exports.enum(COMPUTER_FILES_MODES).optional(),
67645
+ // `view` only: the member watching, the TURN servers the desktop may relay media through, and the STUN servers it may punch with.
67646
+ usr: external_exports.string().min(1).max(128).optional(),
67647
+ ice: external_exports.array(ComputerIceServer).max(COMPUTER_ICE_SERVERS_MAX).optional(),
67648
+ stun: external_exports.array(ComputerStunUrl).max(COMPUTER_STUN_URLS_MAX).optional(),
67649
+ // `view` only, behind `computer-desktops-v1`: the one desktop it may watch (§3.9); absent, the main desktop.
67650
+ dsk: ComputerDesktopId.optional()
67651
+ }).strip().refine((c) => c.aud !== "mcp" || c.ses !== void 0 && c.agt !== void 0 && c.mode !== void 0, {
67652
+ message: "an mcp token names its session, agent and mode"
67653
+ }).refine((c) => c.aud !== "view" || c.usr !== void 0 && c.mode !== void 0, {
67654
+ message: "a view token names its member and mode"
67655
+ }).refine((c) => c.exp > c.iat && c.exp - c.iat <= COMPUTER_CHANNEL_TOKEN_MAX_TTL_MS, {
67656
+ message: "token lifetime out of range"
67657
+ });
67658
+ var MAC_DOMAIN = "agentconnect/computer-channel-token/v1\n";
67659
+ var MAX_TOKEN_CHARS = 4096;
67660
+ function mac3(key, signed) {
67661
+ return createHmac("sha256", key).update(MAC_DOMAIN + signed).digest();
67734
67662
  }
67735
- function maskCrc(crc) {
67736
- return (crc >>> 15 | crc << 17) + 2726488792 >>> 0;
67663
+ function signComputerChannelToken(claims, key) {
67664
+ const parsed = ComputerChannelTokenClaims.parse(claims);
67665
+ const signed = `${COMPUTER_CHANNEL_TOKEN_PREFIX}.${Buffer.from(JSON.stringify(parsed)).toString("base64url")}`;
67666
+ return `${signed}.${mac3(key, signed).toString("base64url")}`;
67737
67667
  }
67738
- var Reader = class {
67739
- constructor(buf, pos = 0) {
67740
- this.buf = buf;
67741
- this.pos = pos;
67742
- }
67743
- buf;
67744
- pos;
67745
- get done() {
67746
- return this.pos >= this.buf.length;
67747
- }
67748
- varint() {
67749
- let result = 0;
67750
- let shift = 0;
67751
- for (; ; ) {
67752
- if (this.pos >= this.buf.length) throw new Error("leveldb: truncated varint");
67753
- const byte = this.buf[this.pos++];
67754
- result += (byte & 127) * 2 ** shift;
67755
- if (!(byte & 128)) return result;
67756
- shift += 7;
67757
- if (shift > 63) throw new Error("leveldb: varint too long");
67758
- }
67759
- }
67760
- bytes(length) {
67761
- if (this.pos + length > this.buf.length) throw new Error("leveldb: truncated slice");
67762
- const out = this.buf.subarray(this.pos, this.pos + length);
67763
- this.pos += length;
67764
- return out;
67765
- }
67766
- slice() {
67767
- return this.bytes(this.varint());
67768
- }
67769
- };
67770
- function varint(value) {
67771
- const out = [];
67772
- let v = value;
67773
- while (v >= 128) {
67774
- out.push(v % 128 | 128);
67775
- v = Math.floor(v / 128);
67668
+ function readComputerChannelToken(token) {
67669
+ if (token.length > MAX_TOKEN_CHARS) return null;
67670
+ const parts = token.split(".");
67671
+ if (parts.length !== 3 || parts[0] !== COMPUTER_CHANNEL_TOKEN_PREFIX) return null;
67672
+ try {
67673
+ const parsed = ComputerChannelTokenClaims.safeParse(JSON.parse(Buffer.from(parts[1], "base64url").toString()));
67674
+ return parsed.success ? parsed.data : null;
67675
+ } catch {
67676
+ return null;
67776
67677
  }
67777
- out.push(v);
67778
- return Buffer.from(out);
67779
67678
  }
67780
- function lengthPrefixed(data) {
67781
- return Buffer.concat([varint(data.length), data]);
67679
+ function verifyComputerChannelToken(token, opts) {
67680
+ const claims = readComputerChannelToken(token);
67681
+ if (!claims || claims.aud !== opts.aud || claims.cmp !== opts.computerId) return null;
67682
+ if (!(claims.exp > opts.now)) return null;
67683
+ const key = opts.key(claims.kid);
67684
+ if (!key) return null;
67685
+ const at = token.lastIndexOf(".");
67686
+ const presented = Buffer.from(token.slice(at + 1), "base64url");
67687
+ const expected = mac3(key, token.slice(0, at));
67688
+ if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) return null;
67689
+ return claims;
67782
67690
  }
67783
- function snappyDecompress(input2) {
67784
- const reader = new Reader(input2);
67785
- const length = reader.varint();
67786
- const out = Buffer.alloc(length);
67787
- let o = 0;
67788
- while (!reader.done) {
67789
- const tag = input2[reader.pos++];
67790
- const kind = tag & 3;
67791
- if (kind === 0) {
67792
- let len2 = tag >>> 2;
67793
- if (len2 >= 60) {
67794
- const extra = len2 - 59;
67795
- len2 = input2.readUIntLE(reader.pos, extra);
67796
- reader.pos += extra;
67797
- }
67798
- len2 += 1;
67799
- input2.copy(out, o, reader.pos, reader.pos + len2);
67800
- reader.pos += len2;
67801
- o += len2;
67802
- continue;
67803
- }
67804
- let len;
67805
- let offset;
67806
- if (kind === 1) {
67807
- len = (tag >>> 2 & 7) + 4;
67808
- offset = tag >>> 5 << 8 | input2[reader.pos++];
67809
- } else if (kind === 2) {
67810
- len = (tag >>> 2) + 1;
67811
- offset = input2.readUInt16LE(reader.pos);
67812
- reader.pos += 2;
67813
- } else {
67814
- len = (tag >>> 2) + 1;
67815
- offset = input2.readUInt32LE(reader.pos);
67816
- reader.pos += 4;
67817
- }
67818
- if (offset === 0 || offset > o) throw new Error("leveldb: bad snappy offset");
67819
- for (let i = 0; i < len; i++, o++) out[o] = out[o - offset];
67820
- }
67821
- if (o !== length) throw new Error("leveldb: snappy length mismatch");
67691
+
67692
+ // ../protocol/src/frames/computer-channel.ts
67693
+ var ComputerRelayEntry = external_exports.object({
67694
+ relayId: external_exports.string().uuid(),
67695
+ url: external_exports.string().min(1).max(2048)
67696
+ });
67697
+ var COMPUTER_RELAYS_MAX = 64;
67698
+ var COMPUTER_ADMIN_PROMPT_MODES = ["agent", "people", "approve", "deny"];
67699
+ var DEFAULT_COMPUTER_ADMIN_PROMPT_MODE = "people";
67700
+ var ComputerApprovalsSchema = external_exports.object({
67701
+ // Ask before a session's first click, drag, type, key or launch; an allow covers the rest of the session.
67702
+ firstInputPerSession: external_exports.boolean().default(true),
67703
+ // Windows only; absent means the default, so policies stored before it keep their meaning.
67704
+ adminPrompts: external_exports.enum(COMPUTER_ADMIN_PROMPT_MODES).optional()
67705
+ });
67706
+ var ComputerGrantApprovalsSchema = ComputerApprovalsSchema.extend({
67707
+ launchApp: external_exports.enum(["always", "session", "never-ask"]).optional(),
67708
+ submitLikeKeys: external_exports.boolean().optional()
67709
+ });
67710
+ var COMPUTER_CHANNEL_REFUSALS = ["denied", "unavailable"];
67711
+ var ComputerChannelGrantRequest = external_exports.object({
67712
+ computerId: external_exports.string().uuid(),
67713
+ agentId: external_exports.string().uuid(),
67714
+ sessionId: external_exports.string().min(1).max(256)
67715
+ });
67716
+ var ComputerChannelGrantResult = external_exports.discriminatedUnion("granted", [
67717
+ external_exports.object({
67718
+ granted: external_exports.literal(true),
67719
+ token: external_exports.string().min(1).max(2048),
67720
+ expiresAt: external_exports.string().datetime(),
67721
+ mode: external_exports.enum(COMPUTER_AGENT_MODES),
67722
+ relays: external_exports.array(ComputerRelayEntry).max(COMPUTER_RELAYS_MAX),
67723
+ // What the approval cards name and whom they also reach (§4.2); an older CP sends none, and every approval is asked.
67724
+ name: external_exports.string().min(1).max(200).optional(),
67725
+ ownerUserId: external_exports.string().min(1).max(128).optional(),
67726
+ approvals: ComputerGrantApprovalsSchema.optional(),
67727
+ // The console users who may answer its approvals: the Computer's allowed members; an older CP sends none.
67728
+ approvers: external_exports.array(external_exports.string().min(1).max(128)).max(500).optional(),
67729
+ // The command-line tier the token allows (§5.7); an older CP sends none, which allows none.
67730
+ shell: external_exports.enum(COMPUTER_SHELL_MODES).optional(),
67731
+ files: external_exports.enum(COMPUTER_FILES_MODES).optional()
67732
+ }),
67733
+ external_exports.object({
67734
+ granted: external_exports.literal(false),
67735
+ code: external_exports.enum(COMPUTER_CHANNEL_REFUSALS),
67736
+ message: external_exports.string().max(500)
67737
+ })
67738
+ ]);
67739
+
67740
+ // ../protocol/src/frames/computer-audit.ts
67741
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67742
+ var COMPUTER_AUDIT_FEATURE = "computer-audit-v1";
67743
+ var COMPUTER_APPROVAL_META_KEY = "md.agentconnect/approval";
67744
+ var COMPUTER_APPROVAL_RESULTS = ["not_required", "allowed", "allowed_session"];
67745
+ var COMPUTER_AUDIT_BATCH_MAX = 100;
67746
+ var COMPUTER_AUDIT_BATCH_BYTES = REPLY_BUDGET;
67747
+ var COMPUTER_AUDIT_ARGS_MAX_CHARS = 2048;
67748
+ var AUDIT_STRING_MAX = 256;
67749
+ var AUDIT_COMMAND_MAX = 1536;
67750
+ var AUDIT_DEPTH_MAX = 6;
67751
+ var TEXT_KEYS = /* @__PURE__ */ new Set(["text", "value", "content"]);
67752
+ var CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
67753
+ var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
67754
+ function computerAuditText(value) {
67755
+ return value.replace(CONTROL_CHARS, "").replace(LONE_SURROGATE, "\uFFFD");
67756
+ }
67757
+ function auditValue(value, depth) {
67758
+ if (typeof value === "string") return computerAuditText(value.slice(0, AUDIT_STRING_MAX));
67759
+ if (value === null || typeof value !== "object") return value;
67760
+ if (depth >= AUDIT_DEPTH_MAX) return "[nested]";
67761
+ if (Array.isArray(value)) return value.map((item) => auditValue(item, depth + 1));
67762
+ const out = {};
67763
+ for (const [key, item] of Object.entries(value))
67764
+ out[computerAuditText(key.slice(0, 64))] = auditValue(item, depth + 1);
67822
67765
  return out;
67823
67766
  }
67824
- function readLogRecords(data) {
67825
- const records = [];
67826
- let pending;
67827
- let pos = 0;
67828
- while (pos < data.length) {
67829
- const left = BLOCK_SIZE - pos % BLOCK_SIZE;
67830
- if (left < HEADER_SIZE) {
67831
- pos += left;
67832
- continue;
67833
- }
67834
- if (pos + HEADER_SIZE > data.length) break;
67835
- const length = data.readUInt16LE(pos + 4);
67836
- const type = data[pos + 6];
67837
- if (type === 0 && length === 0) {
67838
- pos += left;
67767
+ function computerAuditArgs(args) {
67768
+ let textLength;
67769
+ const out = {};
67770
+ for (const [key, value] of Object.entries(args)) {
67771
+ if (TEXT_KEYS.has(key) && typeof value === "string") {
67772
+ textLength = (textLength ?? 0) + [...value].length;
67839
67773
  continue;
67840
67774
  }
67841
- if (pos + HEADER_SIZE + length > data.length) break;
67842
- const payload = data.subarray(pos + HEADER_SIZE, pos + HEADER_SIZE + length);
67843
- pos += HEADER_SIZE + length;
67844
- if (type === FULL) {
67845
- records.push(Buffer.from(payload));
67846
- pending = void 0;
67847
- } else if (type === FIRST) pending = [payload];
67848
- else if (type === MIDDLE && pending) pending.push(payload);
67849
- else if (type === LAST && pending) {
67850
- pending.push(payload);
67851
- records.push(Buffer.concat(pending));
67852
- pending = void 0;
67853
- }
67854
- }
67855
- return records;
67856
- }
67857
- function writeLogRecords(records) {
67858
- const chunks = [];
67859
- let offset = 0;
67860
- const emit = (type, payload) => {
67861
- const header = Buffer.alloc(HEADER_SIZE);
67862
- header.writeUInt32LE(maskCrc(crc32c(payload, crc32c(Buffer.from([type])))), 0);
67863
- header.writeUInt16LE(payload.length, 4);
67864
- header[6] = type;
67865
- chunks.push(header, payload);
67866
- offset += HEADER_SIZE + payload.length;
67867
- };
67868
- for (const record2 of records) {
67869
- let pos = 0;
67870
- let first = true;
67871
- do {
67872
- let left = BLOCK_SIZE - offset % BLOCK_SIZE;
67873
- if (left < HEADER_SIZE) {
67874
- chunks.push(Buffer.alloc(left));
67875
- offset += left;
67876
- left = BLOCK_SIZE;
67877
- }
67878
- const take = Math.min(left - HEADER_SIZE, record2.length - pos);
67879
- const end = pos + take === record2.length;
67880
- emit(first && end ? FULL : first ? FIRST : end ? LAST : MIDDLE, record2.subarray(pos, pos + take));
67881
- pos += take;
67882
- first = false;
67883
- } while (pos < record2.length);
67775
+ out[computerAuditText(key.slice(0, 64))] = key === "command" && typeof value === "string" ? computerAuditText(value.slice(0, AUDIT_COMMAND_MAX)) : auditValue(value, 1);
67884
67776
  }
67885
- return Buffer.concat(chunks);
67777
+ const bounded = JSON.stringify(out).length <= COMPUTER_AUDIT_ARGS_MAX_CHARS ? out : { truncated: true };
67778
+ return { args: bounded, ...textLength !== void 0 ? { textLength } : {} };
67886
67779
  }
67887
- function apply(entries2, key, sequence, deleted, value) {
67888
- const id = key.toString("latin1");
67889
- const current = entries2.get(id);
67890
- if (!current || current.sequence < sequence) entries2.set(id, { sequence, deleted, value: Buffer.from(value) });
67891
- }
67892
- function applyBatch(entries2, batch) {
67893
- if (batch.length < 12) return;
67894
- let sequence = batch.readBigUInt64LE(0);
67895
- const count = batch.readUInt32LE(8);
67896
- const reader = new Reader(batch, 12);
67897
- for (let i = 0; i < count; i++, sequence++) {
67898
- const type = batch[reader.pos++];
67899
- if (type === TYPE_VALUE) {
67900
- const key = reader.slice();
67901
- apply(entries2, key, sequence, false, reader.slice());
67902
- } else if (type === TYPE_DELETION) apply(entries2, reader.slice(), sequence, true, Buffer.alloc(0));
67903
- else throw new Error("leveldb: unknown write batch record");
67904
- }
67780
+ var ComputerAuditEntry = external_exports.object({
67781
+ // Idempotency: a batch resent after a lost ack does not duplicate rows.
67782
+ id: external_exports.string().uuid(),
67783
+ at: external_exports.string().datetime(),
67784
+ tool: external_exports.string().min(1).max(128),
67785
+ // The lease holder name: `agentId/sessionId` for an agent session, else a local client or viewer name.
67786
+ client: external_exports.string().min(1).max(512),
67787
+ agentId: external_exports.string().uuid().optional(),
67788
+ sessionId: external_exports.string().min(1).max(256).optional(),
67789
+ outcome: external_exports.enum(["ok", "error"]),
67790
+ code: external_exports.string().min(1).max(64).optional(),
67791
+ approval: external_exports.enum(COMPUTER_APPROVAL_RESULTS).optional(),
67792
+ args: external_exports.record(external_exports.string().max(64), external_exports.unknown()).refine((args) => JSON.stringify(args).length <= COMPUTER_AUDIT_ARGS_MAX_CHARS, "audit args too large").optional(),
67793
+ textLength: external_exports.number().int().min(0).max(1e6).optional(),
67794
+ ms: external_exports.number().int().min(0),
67795
+ // The stored screenshot this call returned (§9), as `sha256:<hex>`.
67796
+ screenshotRef: external_exports.string().min(1).max(1024).optional(),
67797
+ // Behind `computer-desktops-v1`: the agent desktop that served it (§3.9); absent, the main desktop.
67798
+ desktop: ComputerDesktopId.optional()
67799
+ }).strict();
67800
+ var ComputerAuditReport = external_exports.object({
67801
+ entries: external_exports.array(ComputerAuditEntry).min(1).max(COMPUTER_AUDIT_BATCH_MAX)
67802
+ });
67803
+ var ComputerAuditAck = external_exports.object({ stored: external_exports.number().int().min(0) });
67804
+
67805
+ // ../protocol/src/frames/computer-screenshot.ts
67806
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67807
+ var COMPUTER_SCREENSHOT_FEATURE = "computer-screenshot-v1";
67808
+ var COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS = 3650;
67809
+ var COMPUTER_SCREENSHOT_MAX_BYTES = 32 * 1024 * 1024;
67810
+ var COMPUTER_SCREENSHOT_CONTENT_TYPES = ["image/png", "image/jpeg", "image/webp"];
67811
+ var REF_PREFIX = "sha256:";
67812
+ var SHA256_HEX_RE = /^[0-9a-f]{64}$/;
67813
+ var ComputerScreenshotSha256 = external_exports.string().regex(SHA256_HEX_RE, "expected a lower-case hex SHA-256");
67814
+ function computerScreenshotRef(sha2563) {
67815
+ return `${REF_PREFIX}${sha2563}`;
67905
67816
  }
67906
- function blockEntries(block, each) {
67907
- if (block.length < 4) return;
67908
- const restarts = block.readUInt32LE(block.length - 4);
67909
- const end = block.length - 4 - restarts * 4;
67910
- const reader = new Reader(block.subarray(0, end));
67911
- let last = Buffer.alloc(0);
67912
- while (!reader.done) {
67913
- const shared = reader.varint();
67914
- const unshared = reader.varint();
67915
- const valueLength = reader.varint();
67916
- const key = Buffer.concat([last.subarray(0, shared), reader.bytes(unshared)]);
67917
- each(key, reader.bytes(valueLength));
67918
- last = key;
67919
- }
67817
+ var ComputerScreenshotPut = external_exports.object({
67818
+ sessionId: external_exports.string().min(1).max(256),
67819
+ agentId: external_exports.string().uuid(),
67820
+ sha256: ComputerScreenshotSha256,
67821
+ bytes: external_exports.number().int().positive().max(COMPUTER_SCREENSHOT_MAX_BYTES),
67822
+ contentType: external_exports.enum(COMPUTER_SCREENSHOT_CONTENT_TYPES),
67823
+ takenAt: external_exports.string().datetime()
67824
+ }).strict();
67825
+ var ComputerScreenshotPutOk = external_exports.object({
67826
+ status: external_exports.enum(["upload", "stored", "skipped"]),
67827
+ url: external_exports.string().url().optional(),
67828
+ headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
67829
+ expiresAt: external_exports.string().datetime().optional(),
67830
+ reason: external_exports.string().max(200).optional()
67831
+ });
67832
+ var ComputerScreenshotCommit = external_exports.object({ sessionId: external_exports.string().min(1).max(256), sha256: ComputerScreenshotSha256 }).strict();
67833
+ var ComputerScreenshotCommitOk = external_exports.object({ stored: external_exports.boolean() });
67834
+
67835
+ // ../protocol/src/frames/relay-computer.ts
67836
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67837
+ var RELAY_COMPUTER_SUBPROTOCOL = "agentconnect.cr.v1";
67838
+ var RELAY_COMPUTER_WS_PATH = "/cr/ws";
67839
+ var RELAY_COMPUTER_MAX_BODY_BYTES = 8 * 1024 * 1024;
67840
+ var RELAY_COMPUTER_MAX_FRAME_BYTES = 12 * 1024 * 1024;
67841
+ var RELAY_DAEMON_PATH_SUFFIX = "/rd/ws";
67842
+ function relayUrlAt(relayUrl, path, scheme) {
67843
+ const url2 = new URL(relayUrl);
67844
+ const prefix = url2.pathname.endsWith(RELAY_DAEMON_PATH_SUFFIX) ? url2.pathname.slice(0, -RELAY_DAEMON_PATH_SUFFIX.length) : url2.pathname.replace(/\/+$/, "");
67845
+ for (const { from, to } of scheme) if (url2.protocol === from) url2.protocol = to;
67846
+ url2.pathname = `${prefix}${path}`;
67847
+ url2.search = "";
67848
+ url2.hash = "";
67849
+ return url2.toString();
67920
67850
  }
67921
- function readBlock(file2, handle) {
67922
- const offset = handle.varint();
67923
- const size = handle.varint();
67924
- const contents = file2.subarray(offset, offset + size);
67925
- const compression = file2[offset + size];
67926
- if (compression === 0) return contents;
67927
- if (compression === 1) return snappyDecompress(contents);
67928
- throw new Error(`leveldb: unsupported block compression ${compression}`);
67851
+ function relayComputerWsUrl(relayUrl) {
67852
+ return relayUrlAt(relayUrl, RELAY_COMPUTER_WS_PATH, [
67853
+ { from: "http:", to: "ws:" },
67854
+ { from: "https:", to: "wss:" }
67855
+ ]);
67929
67856
  }
67930
- function readTable(file2, entries2) {
67931
- if (file2.length < 48) throw new Error("leveldb: table too short");
67932
- const footer = file2.subarray(file2.length - 48);
67933
- if (footer.readBigUInt64LE(40) !== TABLE_MAGIC) throw new Error("leveldb: bad table magic");
67934
- const handles = new Reader(footer);
67935
- handles.varint();
67936
- handles.varint();
67937
- const index = readBlock(file2, handles);
67938
- blockEntries(index, (_key, handle) => {
67939
- blockEntries(readBlock(file2, new Reader(handle)), (internal, value) => {
67940
- const tag = internal.readBigUInt64LE(internal.length - 8);
67941
- apply(entries2, internal.subarray(0, internal.length - 8), tag >> 8n, Number(tag & 0xffn) === TYPE_DELETION, value);
67942
- });
67857
+ var Base64 = external_exports.string().regex(/^[A-Za-z0-9+/]*={0,2}$/);
67858
+ var Headers2 = external_exports.record(external_exports.string().min(1).max(256), external_exports.string().max(8192));
67859
+ var CrHello = external_exports.object({
67860
+ computerId: external_exports.string().uuid(),
67861
+ token: external_exports.string().min(1).max(2048),
67862
+ desktopDaemonVersion: external_exports.string().trim().min(1).max(64)
67863
+ }).strict();
67864
+ var CrHelloOk = external_exports.object({ relayId: external_exports.string().min(1).max(64) });
67865
+ var CrHttpRequest = external_exports.object({
67866
+ method: external_exports.enum(["GET", "POST", "DELETE"]),
67867
+ path: external_exports.string().min(1).max(2048),
67868
+ headers: Headers2,
67869
+ body: Base64.optional()
67870
+ });
67871
+ var CrHttpResponse = external_exports.object({
67872
+ status: external_exports.number().int().min(100).max(599),
67873
+ headers: Headers2,
67874
+ body: Base64.optional()
67875
+ });
67876
+ var RELAY_COMPUTER_SCHEMAS = {
67877
+ "cr/hello": CrHello,
67878
+ "cr/hello/ok": CrHelloOk,
67879
+ "cr/http": CrHttpRequest,
67880
+ "cr/http/result": CrHttpResponse,
67881
+ error: ErrorFrame
67882
+ };
67883
+ var RelayComputerFrame = external_exports.discriminatedUnion("type", [
67884
+ frameSchema("cr/hello", RELAY_COMPUTER_SCHEMAS["cr/hello"]),
67885
+ frameSchema("cr/hello/ok", RELAY_COMPUTER_SCHEMAS["cr/hello/ok"]),
67886
+ frameSchema("cr/http", RELAY_COMPUTER_SCHEMAS["cr/http"]),
67887
+ frameSchema("cr/http/result", RELAY_COMPUTER_SCHEMAS["cr/http/result"]),
67888
+ frameSchema("error", RELAY_COMPUTER_SCHEMAS["error"])
67889
+ ]);
67890
+ function decodeRelayComputerFrame(text) {
67891
+ return decodeEnvelopeWith(RELAY_COMPUTER_SCHEMAS, text, {
67892
+ maxBytes: RELAY_COMPUTER_MAX_FRAME_BYTES
67943
67893
  });
67944
67894
  }
67945
- function readManifest(data) {
67946
- const manifest = { logNumber: 0, prevLogNumber: 0, tables: /* @__PURE__ */ new Set() };
67947
- for (const record2 of readLogRecords(data)) {
67948
- const reader = new Reader(record2);
67949
- while (!reader.done) {
67950
- const tag = reader.varint();
67951
- if (tag === 1) reader.slice();
67952
- else if (tag === 2) manifest.logNumber = reader.varint();
67953
- else if (tag === 3) reader.varint();
67954
- else if (tag === 4) reader.varint();
67955
- else if (tag === 5) {
67956
- reader.varint();
67957
- reader.slice();
67958
- } else if (tag === 6) {
67959
- reader.varint();
67960
- manifest.tables.delete(reader.varint());
67961
- } else if (tag === 7) {
67962
- reader.varint();
67963
- manifest.tables.add(reader.varint());
67964
- reader.varint();
67965
- reader.slice();
67966
- reader.slice();
67967
- } else if (tag === 9) manifest.prevLogNumber = reader.varint();
67968
- else throw new Error(`leveldb: unknown manifest tag ${tag}`);
67969
- }
67970
- }
67971
- return manifest;
67972
- }
67973
- function readLevelDb(dir) {
67974
- const entries2 = /* @__PURE__ */ new Map();
67975
- if (!existsSync(join2(dir, "CURRENT"))) return /* @__PURE__ */ new Map();
67976
- const current = readFileSync2(join2(dir, "CURRENT"), "latin1").trim();
67977
- const manifest = readManifest(readFileSync2(join2(dir, current)));
67978
- const files = readdirSync(dir);
67979
- for (const number4 of manifest.tables) {
67980
- const name = [`${String(number4).padStart(6, "0")}.ldb`, `${String(number4).padStart(6, "0")}.sst`].find(
67981
- (n) => files.includes(n)
67982
- );
67983
- if (!name) throw new Error(`leveldb: table ${number4} is missing`);
67984
- readTable(readFileSync2(join2(dir, name)), entries2);
67985
- }
67986
- for (const name of files) {
67987
- const match = /^(\d+)\.log$/.exec(name);
67988
- if (!match) continue;
67989
- const number4 = Number(match[1]);
67990
- if (number4 < manifest.logNumber && number4 !== manifest.prevLogNumber) continue;
67991
- for (const batch of readLogRecords(readFileSync2(join2(dir, name)))) applyBatch(entries2, batch);
67992
- }
67993
- const out = /* @__PURE__ */ new Map();
67994
- for (const [key, entry] of entries2) if (!entry.deleted) out.set(key, entry.value);
67995
- return out;
67996
- }
67997
- function writeLevelDb(dir, data) {
67998
- rmSync(dir, { recursive: true, force: true });
67999
- mkdirSync2(dir, { recursive: true });
68000
- const batches = [];
68001
- let sequence = 1n;
68002
- let records = [];
68003
- let bytes = 0;
68004
- const flush = () => {
68005
- if (!records.length) return;
68006
- const head = Buffer.alloc(12);
68007
- head.writeBigUInt64LE(sequence, 0);
68008
- head.writeUInt32LE(records.length, 8);
68009
- batches.push(Buffer.concat([head, ...records]));
68010
- sequence += BigInt(records.length);
68011
- records = [];
68012
- bytes = 0;
68013
- };
68014
- for (const [key, value] of data) {
68015
- const record2 = Buffer.concat([
68016
- Buffer.from([TYPE_VALUE]),
68017
- lengthPrefixed(Buffer.from(key, "latin1")),
68018
- lengthPrefixed(value)
68019
- ]);
68020
- records.push(record2);
68021
- bytes += record2.length;
68022
- if (bytes >= BATCH_LIMIT_BYTES) flush();
68023
- }
68024
- flush();
68025
- const edit = Buffer.concat([
68026
- varint(1),
68027
- lengthPrefixed(Buffer.from("leveldb.BytewiseComparator", "latin1")),
68028
- varint(2),
68029
- varint(3),
68030
- varint(3),
68031
- varint(4),
68032
- varint(4),
68033
- varint(0)
68034
- ]);
68035
- writeFileSync(join2(dir, "000003.log"), writeLogRecords(batches));
68036
- writeFileSync(join2(dir, "MANIFEST-000002"), writeLogRecords([edit]));
68037
- writeFileSync(join2(dir, "CURRENT"), "MANIFEST-000002\n");
67895
+ function buildRelayComputerFrame(type, payload, opts = {}) {
67896
+ return buildEnvelopeRaw(type, payload, opts);
68038
67897
  }
68039
67898
 
68040
- // src/browser/profile-merge.ts
68041
- var BASELINE_FILE = "ac-fork-baseline.json";
68042
- var CHROME_EPOCH_OFFSET_US = 11644473600000000n;
68043
- var SNAPSHOT_TRIES = 6;
68044
- var SNAPSHOT_RETRY_MS = 300;
68045
- function cookiesPath(profile) {
68046
- const network = join3(profile, "Default", "Network", "Cookies");
68047
- return existsSync2(network) ? network : join3(profile, "Default", "Cookies");
68048
- }
68049
- var sqlite;
68050
- function openDb(path) {
68051
- if (!sqlite) {
68052
- const emit = process.emitWarning;
68053
- process.emitWarning = ((warning, ...rest) => {
68054
- if (!String(warning).includes("SQLite")) emit.call(process, warning, ...rest);
68055
- });
68056
- try {
68057
- sqlite = process.getBuiltinModule("node:sqlite");
68058
- } finally {
68059
- process.emitWarning = emit;
68060
- }
68061
- }
68062
- return new sqlite.DatabaseSync(path);
67899
+ // ../protocol/src/frames/computer-keys.ts
67900
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
67901
+ var COMPUTER_KEY_ALIASES = {
67902
+ enter: "return",
67903
+ esc: "escape",
67904
+ control: "ctrl",
67905
+ option: "alt"
67906
+ };
67907
+ function normalizeComputerKey(key) {
67908
+ const lowered = key.trim().toLowerCase();
67909
+ return COMPUTER_KEY_ALIASES[lowered] ?? lowered;
68063
67910
  }
68064
- var localStoragePath = (profile) => join3(profile, "Default", "Local Storage", "leveldb");
68065
- var indexedDbPath = (profile) => join3(profile, "Default", "IndexedDB");
68066
- async function forkMerge(target, sources, options = {}) {
68067
- const now = options.now ?? Date.now;
68068
- const sleep3 = options.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
68069
- const baselinePath = join3(target, BASELINE_FILE);
68070
- const baselines = loadBaselines(baselinePath);
68071
- const reports = [];
68072
- for (const source of sources) {
68073
- const key = realpathSync(source);
68074
- const previous = baselines.sources[key];
68075
- const work = mkdtempSync(join3(tmpdir(), "ac-fork-"));
68076
- try {
68077
- const snapshot = await takeSnapshot(source, work, sleep3);
68078
- const next = { cookies: {}, localStorage: {}, indexedDb: {} };
68079
- const report = {
68080
- source,
68081
- firstFork: previous === void 0,
68082
- cookies: { inserted: 0, updated: 0, kept: 0, expired: 0, deleted: 0 },
68083
- localStorage: { taken: [], kept: 0 },
68084
- indexedDb: { taken: [], kept: 0 }
68085
- };
68086
- if (snapshot.cookies) {
68087
- mergeCookies(snapshot.cookies, cookiesPath(target), previous?.cookies, next.cookies, report.cookies, now);
68088
- }
68089
- mergeLocalStorage(
68090
- snapshot.localStorage,
68091
- localStoragePath(target),
68092
- previous?.localStorage,
68093
- next.localStorage,
68094
- report.localStorage
68095
- );
68096
- if (snapshot.indexedDb) {
68097
- mergeIndexedDb(snapshot.indexedDb, indexedDbPath(target), previous?.indexedDb, next.indexedDb, report.indexedDb);
68098
- }
68099
- baselines.sources[key] = next;
68100
- reports.push(report);
68101
- } finally {
68102
- rmSync2(work, { recursive: true, force: true });
68103
- }
67911
+
67912
+ // ../protocol/src/frames/computer.ts
67913
+ var COMPUTER_CP_SUBPROTOCOL = "agentconnect.computer.v1";
67914
+ var COMPUTER_WS_PUBLIC_PATH = "/v1/computers/ws";
67915
+ var COMPUTER_REGISTER_PUBLIC_PATH = "/v1/computers/register";
67916
+ var COMPUTER_SESSIONS = ["aqua", "console", "rdp", "x11", "xvfb", "wayland-gnome"];
67917
+ var COMPUTER_LIVE_STATUSES = ["online", "locked", "paused", "human_in_control", "busy"];
67918
+ var HHMM = "(?:[01]\\d|2[0-3]):[0-5]\\d";
67919
+ var QUIET_RANGE_RE = new RegExp(`^${HHMM}-${HHMM}$`);
67920
+ function isTimeZone(tz) {
67921
+ try {
67922
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
67923
+ return true;
67924
+ } catch {
67925
+ return false;
68104
67926
  }
68105
- writeFileSync2(baselinePath, JSON.stringify(baselines));
68106
- return reports;
68107
67927
  }
68108
- function loadBaselines(path) {
67928
+ var AppId = external_exports.string().trim().min(1).max(256);
67929
+ var COMPUTER_ACCESS_AGENTS_MAX = 200;
67930
+ var COMPUTER_AGENT_ACCESS_MODES = ["none", "selected", "all"];
67931
+ var ComputerAgentAccess = external_exports.object({
67932
+ mode: external_exports.enum(COMPUTER_AGENT_ACCESS_MODES),
67933
+ agents: external_exports.array(external_exports.uuid()).max(COMPUTER_ACCESS_AGENTS_MAX).default([])
67934
+ });
67935
+ var ComputerPolicySchema = external_exports.object({
67936
+ allowedMembers: external_exports.array(external_exports.string().min(1).max(128)).max(500).default([]),
67937
+ agentMode: external_exports.enum(["view", "control"]).default("control"),
67938
+ approvals: ComputerApprovalsSchema.default({ firstInputPerSession: true }),
67939
+ appAllowlist: external_exports.array(AppId).max(200).optional(),
67940
+ redactApps: external_exports.array(AppId).max(200).default([]),
67941
+ exposeDriverTools: external_exports.boolean().default(false),
67942
+ quietHours: external_exports.object({
67943
+ tz: external_exports.string().min(1).max(64).refine(isTimeZone, "unknown IANA time zone"),
67944
+ ranges: external_exports.array(external_exports.string().regex(QUIET_RANGE_RE, "expected HH:MM-HH:MM")).min(1).max(24)
67945
+ }).optional(),
67946
+ leaseIdleSeconds: external_exports.number().int().min(10).max(3600).default(120),
67947
+ leaseMaxSeconds: external_exports.number().int().min(60).max(86400).default(1800),
67948
+ // Seconds an acquire waits in the FIFO lease queue before `computer_busy` (§4.4); 0 never waits.
67949
+ leaseWaitSeconds: external_exports.number().int().min(0).max(COMPUTER_LEASE_WAIT_MAX_SECONDS).default(45),
67950
+ // Days stored screenshots are kept (§9); 0 means never written, absent means the deployment's default.
67951
+ screenshotRetentionDays: external_exports.number().int().min(0).max(COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS).optional(),
67952
+ // Whether viewers may hole-punch peer to peer, which shows them the desktop's public IP (§7.2); absent means on only for owner-only viewing.
67953
+ viewerPeerToPeer: external_exports.boolean().optional(),
67954
+ // The command-line tier (§5.7); absent means the Computer's default, on for a managed one and off otherwise.
67955
+ shell: external_exports.enum(COMPUTER_SHELL_MODES).optional(),
67956
+ files: external_exports.enum(COMPUTER_FILES_MODES).optional(),
67957
+ // Prefixes the file tools may touch; absent means the user's home directory.
67958
+ fileRoots: external_exports.array(ComputerFileRoot).max(COMPUTER_FILE_ROOTS_MAX).optional(),
67959
+ // Per-agent desktops fork and merge the registrant's browser logins (§3.9); absent means on.
67960
+ shareBrowserLogins: external_exports.boolean().optional()
67961
+ }).refine((p) => p.leaseIdleSeconds <= p.leaseMaxSeconds, {
67962
+ message: "leaseIdleSeconds must not exceed leaseMaxSeconds",
67963
+ path: ["leaseIdleSeconds"]
67964
+ }).refine((p) => p.agentMode === "control" || p.shell === void 0 || p.shell === "off", {
67965
+ message: "a shell needs agentMode control",
67966
+ path: ["shell"]
67967
+ });
67968
+ var ComputerCapabilitiesSchema = external_exports.object({
67969
+ screenshot: external_exports.boolean().default(false),
67970
+ input: external_exports.boolean().default(false),
67971
+ textInput: external_exports.enum(["full", "keymap-only"]).default("full"),
67972
+ // Which human input pauses agents (§6); absent reads as pointer only, what older desktops detect.
67973
+ humanActivity: external_exports.enum(["pointer", "pointer+keyboard"]).optional(),
67974
+ backgroundInput: external_exports.boolean().default(false),
67975
+ accessibilityTree: external_exports.boolean().default(false),
67976
+ viewer: external_exports.boolean().default(false),
67977
+ // The viewer accepts a view token's `stun` claim; desktops before relay STUN refuse such a token.
67978
+ viewerStun: external_exports.boolean().optional(),
67979
+ // The browser's traffic leaves through the desktop's egress forwarder, which applies `computer/egress` (§15.4).
67980
+ egress: external_exports.boolean().optional(),
67981
+ // The command-line tier can run here (§5.7): computer_exec, and the file tools.
67982
+ exec: external_exports.boolean().optional(),
67983
+ files: external_exports.boolean().optional(),
67984
+ displays: external_exports.array(
67985
+ external_exports.object({
67986
+ id: external_exports.string().min(1).max(128),
67987
+ width: external_exports.number().int().positive().max(1e5),
67988
+ height: external_exports.number().int().positive().max(1e5),
67989
+ scale: external_exports.number().positive().max(16)
67990
+ })
67991
+ ).max(16).default([]),
67992
+ permissions: external_exports.object({
67993
+ accessibility: external_exports.boolean().optional(),
67994
+ screenRecording: external_exports.boolean().optional(),
67995
+ portal: external_exports.boolean().optional(),
67996
+ firewall: external_exports.boolean().optional()
67997
+ }).default({})
67998
+ });
67999
+ var ComputerDoctorCheck = external_exports.object({
68000
+ name: external_exports.string().min(1).max(64),
68001
+ status: external_exports.enum(["ok", "info", "warn", "fail"]),
68002
+ detail: external_exports.string().max(1e3),
68003
+ fix: external_exports.string().max(1e3).optional()
68004
+ });
68005
+ var ComputerDoctorReport = external_exports.object({
68006
+ checkedAt: external_exports.string().datetime(),
68007
+ checks: external_exports.array(ComputerDoctorCheck).max(64)
68008
+ });
68009
+ var ComputerChannelCredential = external_exports.object({
68010
+ keyId: external_exports.string().min(1).max(64),
68011
+ // 32 random-looking bytes, base64url without padding; secret material, never logged.
68012
+ key: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/),
68013
+ issuedAt: external_exports.string().datetime(),
68014
+ expiresAt: external_exports.string().datetime()
68015
+ });
68016
+ var ComputerEgressProxyUrl = external_exports.string().max(512).refine((raw) => {
68109
68017
  try {
68110
- const parsed = JSON.parse(readFileSync3(path, "utf8"));
68111
- if (parsed.version === 1 && parsed.sources && typeof parsed.sources === "object") return parsed;
68018
+ const u = new URL(raw);
68019
+ return (u.protocol === "http:" || u.protocol === "https:") && u.hostname !== "" && u.username === "" && u.password === "" && (u.pathname === "" || u.pathname === "/") && u.search === "" && u.hash === "";
68112
68020
  } catch {
68021
+ return false;
68113
68022
  }
68114
- return { version: 1, sources: {} };
68023
+ }, "expected http://host:port or https://host:port without credentials or a path");
68024
+ var ComputerEgress = external_exports.discriminatedUnion("mode", [
68025
+ external_exports.object({ mode: external_exports.literal("direct") }),
68026
+ external_exports.object({
68027
+ mode: external_exports.literal("proxy"),
68028
+ url: ComputerEgressProxyUrl,
68029
+ username: external_exports.string().min(1).max(256).optional(),
68030
+ password: external_exports.string().min(1).max(512).optional()
68031
+ })
68032
+ ]);
68033
+ var COMPUTER_EGRESS_FEATURE = "computer-egress-v1";
68034
+ var ComputerAuth = external_exports.object({
68035
+ apiKey: external_exports.string().min(1).max(256),
68036
+ desktopDaemonVersion: external_exports.string().trim().min(1).max(64)
68037
+ }).strict();
68038
+ var ComputerAuthOk = external_exports.object({
68039
+ computerId: external_exports.string().uuid(),
68040
+ orgId: external_exports.string().min(1).max(64),
68041
+ name: external_exports.string().min(1).max(200),
68042
+ heartbeatSec: external_exports.number().int().positive(),
68043
+ serverTime: external_exports.string().datetime(),
68044
+ credential: ComputerChannelCredential,
68045
+ policy: ComputerPolicySchema,
68046
+ // What this CP accepts on the channel beyond the base frames, such as `computer-audit-v1`.
68047
+ features: external_exports.array(external_exports.string().min(1).max(64)).max(32).optional(),
68048
+ // The retention in effect for this Computer's screenshots (§9); 0 or absent means none are stored.
68049
+ screenshotRetentionDays: external_exports.number().int().min(0).max(COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS).optional(),
68050
+ // A managed desktop's egress (§15.4); absent means direct unless `computer-egress-v1` is advertised. Secret, never logged.
68051
+ egress: ComputerEgress.optional(),
68052
+ // A managed desktop's arrangement (§3.9): per-agent desktops for a `manual` one agents share, else one; absent, the owner's switch decides.
68053
+ desktops: external_exports.enum(["per-agent", "shared"]).optional()
68054
+ });
68055
+ var COMPUTER_DESKTOPS_FEATURE = "computer-desktops-v1";
68056
+ var COMPUTER_DESKTOPS_MAX = 64;
68057
+ var ComputerDesktopReport = external_exports.object({
68058
+ id: ComputerDesktopId,
68059
+ agentId: external_exports.string().uuid(),
68060
+ status: external_exports.enum(COMPUTER_LIVE_STATUSES),
68061
+ lease: external_exports.object({
68062
+ holder: external_exports.string().min(1).max(512),
68063
+ idleMs: external_exports.number().int().min(0),
68064
+ heldMs: external_exports.number().int().min(0).optional()
68065
+ }).strict().optional()
68066
+ }).strict();
68067
+ var ComputerHeartbeat = external_exports.object({
68068
+ status: external_exports.enum(COMPUTER_LIVE_STATUSES),
68069
+ osVersion: external_exports.string().trim().min(1).max(120).optional(),
68070
+ session: external_exports.enum(COMPUTER_SESSIONS).optional(),
68071
+ desktopDaemonVersion: external_exports.string().trim().min(1).max(64).optional(),
68072
+ driverVersion: external_exports.string().trim().min(1).max(64).optional(),
68073
+ capabilities: ComputerCapabilitiesSchema.optional(),
68074
+ doctor: ComputerDoctorReport.optional(),
68075
+ // The local lease, how long since its last input, and how long it has been held without idling out.
68076
+ lease: external_exports.object({
68077
+ holder: external_exports.string().min(1).max(512),
68078
+ idleMs: external_exports.number().int().min(0),
68079
+ heldMs: external_exports.number().int().min(0).optional()
68080
+ }).strict().optional(),
68081
+ // Behind `computer-desktops-v1`: present (even empty) while each agent gets a desktop of its own; `status` is the main one's.
68082
+ desktops: external_exports.array(ComputerDesktopReport).max(COMPUTER_DESKTOPS_MAX).optional()
68083
+ }).strict();
68084
+ var ComputerCredentialRenewal = external_exports.object({ credential: ComputerChannelCredential });
68085
+ var ComputerPolicyPush = external_exports.object({
68086
+ policy: ComputerPolicySchema,
68087
+ screenshotRetentionDays: external_exports.number().int().min(0).max(COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS).optional()
68088
+ });
68089
+ var ComputerRevoke = external_exports.object({
68090
+ reason: external_exports.enum(["revoked", "deleted", "owner_removed"]),
68091
+ message: external_exports.string().max(500).optional()
68092
+ });
68093
+ var ComputerLeasePush = external_exports.object({
68094
+ lease: ComputerControlLease.nullable(),
68095
+ desktops: external_exports.array(ComputerControlLease).max(COMPUTER_DESKTOPS_MAX).optional()
68096
+ });
68097
+ var ComputerRelaysPush = external_exports.object({ relays: external_exports.array(ComputerRelayEntry).max(COMPUTER_RELAYS_MAX) });
68098
+ var ComputerStopPush = external_exports.object({ stop: external_exports.object({ at: external_exports.string().datetime() }).nullable() });
68099
+ var ComputerEgressPush = external_exports.object({ egress: ComputerEgress });
68100
+ var COMPUTER_ADMIN_PROMPTS_FEATURE = "computer-admin-prompts-v1";
68101
+ var ComputerAdminPromptsSet = external_exports.object({ mode: external_exports.enum(COMPUTER_ADMIN_PROMPT_MODES) }).strict();
68102
+ var ComputerAdminPromptsSetOk = external_exports.object({ mode: external_exports.enum(COMPUTER_ADMIN_PROMPT_MODES) });
68103
+ var COMPUTER_CP_SCHEMAS = {
68104
+ "computer/auth": ComputerAuth,
68105
+ "computer/auth/ok": ComputerAuthOk,
68106
+ "computer/heartbeat": ComputerHeartbeat,
68107
+ "computer/credential": ComputerCredentialRenewal,
68108
+ "computer/policy": ComputerPolicyPush,
68109
+ "computer/revoke": ComputerRevoke,
68110
+ "computer/lease": ComputerLeasePush,
68111
+ "computer/relays": ComputerRelaysPush,
68112
+ "computer/stop": ComputerStopPush,
68113
+ "computer/egress": ComputerEgressPush,
68114
+ "computer/admin-prompts": ComputerAdminPromptsSet,
68115
+ "computer/admin-prompts/ok": ComputerAdminPromptsSetOk,
68116
+ "computer/audit": ComputerAuditReport,
68117
+ "computer/audit/ok": ComputerAuditAck,
68118
+ "computer/screenshot/put": ComputerScreenshotPut,
68119
+ "computer/screenshot/put/ok": ComputerScreenshotPutOk,
68120
+ "computer/screenshot/commit": ComputerScreenshotCommit,
68121
+ "computer/screenshot/commit/ok": ComputerScreenshotCommitOk,
68122
+ error: ErrorFrame
68123
+ };
68124
+ var COMPUTER_CP_FRAME_TYPES = Object.keys(COMPUTER_CP_SCHEMAS);
68125
+ var ComputerCpFrame = external_exports.discriminatedUnion("type", [
68126
+ frameSchema("computer/auth", COMPUTER_CP_SCHEMAS["computer/auth"]),
68127
+ frameSchema("computer/auth/ok", COMPUTER_CP_SCHEMAS["computer/auth/ok"]),
68128
+ frameSchema("computer/heartbeat", COMPUTER_CP_SCHEMAS["computer/heartbeat"]),
68129
+ frameSchema("computer/credential", COMPUTER_CP_SCHEMAS["computer/credential"]),
68130
+ frameSchema("computer/policy", COMPUTER_CP_SCHEMAS["computer/policy"]),
68131
+ frameSchema("computer/revoke", COMPUTER_CP_SCHEMAS["computer/revoke"]),
68132
+ frameSchema("computer/lease", COMPUTER_CP_SCHEMAS["computer/lease"]),
68133
+ frameSchema("computer/relays", COMPUTER_CP_SCHEMAS["computer/relays"]),
68134
+ frameSchema("computer/stop", COMPUTER_CP_SCHEMAS["computer/stop"]),
68135
+ frameSchema("computer/egress", COMPUTER_CP_SCHEMAS["computer/egress"]),
68136
+ frameSchema("computer/admin-prompts", COMPUTER_CP_SCHEMAS["computer/admin-prompts"]),
68137
+ frameSchema("computer/admin-prompts/ok", COMPUTER_CP_SCHEMAS["computer/admin-prompts/ok"]),
68138
+ frameSchema("computer/audit", COMPUTER_CP_SCHEMAS["computer/audit"]),
68139
+ frameSchema("computer/audit/ok", COMPUTER_CP_SCHEMAS["computer/audit/ok"]),
68140
+ frameSchema("computer/screenshot/put", COMPUTER_CP_SCHEMAS["computer/screenshot/put"]),
68141
+ frameSchema("computer/screenshot/put/ok", COMPUTER_CP_SCHEMAS["computer/screenshot/put/ok"]),
68142
+ frameSchema("computer/screenshot/commit", COMPUTER_CP_SCHEMAS["computer/screenshot/commit"]),
68143
+ frameSchema("computer/screenshot/commit/ok", COMPUTER_CP_SCHEMAS["computer/screenshot/commit/ok"]),
68144
+ frameSchema("error", COMPUTER_CP_SCHEMAS["error"])
68145
+ ]);
68146
+ var TOLERANT_COMPUTER_CP_SCHEMAS = tolerantSchemas(COMPUTER_CP_SCHEMAS);
68147
+ function decodeComputerCpFrameTolerant(text) {
68148
+ return decodeEnvelopeWith(TOLERANT_COMPUTER_CP_SCHEMAS, text);
68115
68149
  }
68116
- async function takeSnapshot(source, work, sleep3) {
68117
- const snapshot = { localStorage: /* @__PURE__ */ new Map() };
68118
- const cookies = cookiesPath(source);
68119
- if (existsSync2(cookies)) {
68120
- snapshot.cookies = join3(work, "Cookies");
68121
- cpSync(cookies, snapshot.cookies);
68122
- for (const suffix of ["-journal", "-wal"]) {
68123
- if (existsSync2(cookies + suffix)) cpSync(cookies + suffix, snapshot.cookies + suffix);
68124
- }
68125
- }
68126
- const localStorage2 = localStoragePath(source);
68127
- if (existsSync2(localStorage2)) {
68128
- snapshot.localStorage = await retried(sleep3, () => {
68129
- const copy = join3(work, "ls");
68130
- rmSync2(copy, { recursive: true, force: true });
68131
- cpSync(localStorage2, copy, { recursive: true, filter: (path) => basename(path) !== "LOCK" });
68132
- return readLevelDb(copy);
68133
- });
68150
+ function buildComputerCpFrame(type, payload, opts = {}) {
68151
+ return buildEnvelopeRaw(type, payload, opts);
68152
+ }
68153
+
68154
+ // src/admin-prompts.ts
68155
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68156
+ import { spawn } from "node:child_process";
68157
+ import { createInterface } from "node:readline";
68158
+ var ANSWER_TIMEOUT_MS = 1e4;
68159
+ var RESTART_MS = 5e3;
68160
+ var str = (value) => typeof value === "string" && value !== "" ? value : void 0;
68161
+ var AdminPromptHelper = class _AdminPromptHelper {
68162
+ constructor(path, options) {
68163
+ this.path = path;
68164
+ this.options = options;
68134
68165
  }
68135
- const indexedDb = indexedDbPath(source);
68136
- if (existsSync2(indexedDb)) {
68137
- snapshot.indexedDb = join3(work, "idb");
68138
- await retried(sleep3, () => {
68139
- rmSync2(snapshot.indexedDb, { recursive: true, force: true });
68140
- cpSync(indexedDb, snapshot.indexedDb, {
68141
- recursive: true,
68142
- preserveTimestamps: true,
68143
- filter: (path) => basename(path) !== "LOCK"
68166
+ path;
68167
+ options;
68168
+ problem;
68169
+ current;
68170
+ child;
68171
+ closed = false;
68172
+ waiting = /* @__PURE__ */ new Map();
68173
+ static start(path, options) {
68174
+ const helper = new _AdminPromptHelper(path, options);
68175
+ helper.spawn();
68176
+ return helper;
68177
+ }
68178
+ pending() {
68179
+ return this.current;
68180
+ }
68181
+ answer(id, answer) {
68182
+ const child2 = this.child;
68183
+ if (!child2?.stdin || this.problem)
68184
+ return Promise.reject(new Error(this.problem ?? "the prompt helper is not running"));
68185
+ return new Promise((resolve5, reject) => {
68186
+ const timer = setTimeout(() => {
68187
+ this.waiting.delete(id);
68188
+ reject(new Error("the prompt helper did not answer in time"));
68189
+ }, ANSWER_TIMEOUT_MS);
68190
+ timer.unref();
68191
+ this.waiting.set(id, {
68192
+ resolve: () => (clearTimeout(timer), resolve5()),
68193
+ reject: (error63) => (clearTimeout(timer), reject(error63))
68144
68194
  });
68195
+ child2.stdin.write(`${JSON.stringify({ id, answer })}
68196
+ `);
68145
68197
  });
68146
68198
  }
68147
- return snapshot;
68148
- }
68149
- async function retried(sleep3, attempt) {
68150
- let last;
68151
- for (let i = 0; i < SNAPSHOT_TRIES; i++) {
68152
- try {
68153
- return attempt();
68154
- } catch (error63) {
68155
- last = error63;
68156
- await sleep3(SNAPSHOT_RETRY_MS);
68157
- }
68158
- }
68159
- throw new Error(`could not snapshot a running profile: ${last.message}`);
68160
- }
68161
- var scalar = (value) => typeof value === "bigint" ? value.toString() : value;
68162
- var bindable = (value) => value instanceof Uint8Array ? Buffer.from(value) : value;
68163
- function uniqueKey(db) {
68164
- for (const index of db.prepare("PRAGMA index_list(cookies)").all()) {
68165
- if (Number(index.unique) !== 1) continue;
68166
- const name = String(index.name).replaceAll("'", "''");
68167
- return db.prepare(`PRAGMA index_info('${name}')`).all().map((column) => String(column.name));
68199
+ close() {
68200
+ this.closed = true;
68201
+ this.child?.stdin?.end();
68168
68202
  }
68169
- throw new Error("the cookies table has no unique index");
68170
- }
68171
- function mergeCookies(snapshot, target, previous, next, counts, now) {
68172
- if (!existsSync2(target)) cpSync(snapshot, target);
68173
- const source = openDb(snapshot);
68174
- const db = openDb(target);
68175
- try {
68176
- const columns = db.prepare("PRAGMA table_info(cookies)").all().map((column) => String(column.name));
68177
- const sourceColumns = source.prepare("PRAGMA table_info(cookies)").all().map(
68178
- (column) => String(column.name)
68203
+ spawn() {
68204
+ const child2 = (this.options.spawnHelper ?? ((file2) => spawn(file2, [], { stdio: ["pipe", "pipe", "inherit"], windowsHide: true })))(this.path);
68205
+ this.child = child2;
68206
+ child2.stdin?.on("error", () => void 0);
68207
+ child2.on("error", (error63) => this.gone(`cannot start the administrator prompt helper: ${error63.message}`));
68208
+ child2.on(
68209
+ "exit",
68210
+ (code, signal) => this.gone(`the administrator prompt helper exited (${signal ?? `code ${code}`})`)
68179
68211
  );
68180
- if (columns.join() !== sourceColumns.join()) throw new Error("the cookie databases have different schemas");
68181
- const key = uniqueKey(db);
68182
- const stamp = columns.includes("last_update_utc") ? "last_update_utc" : "creation_utc";
68183
- const keyOf2 = (row) => JSON.stringify(key.map((column) => scalar(row[column])));
68184
- const list2 = (database, sql) => {
68185
- const statement = database.prepare(sql);
68186
- statement.setReadBigInts(true);
68187
- return statement.all();
68188
- };
68189
- const quoted = columns.map((column) => `"${column}"`).join(",");
68190
- const mine = /* @__PURE__ */ new Map();
68191
- for (const row of list2(db, `SELECT rowid AS ac_rowid, ${quoted} FROM cookies`)) {
68192
- mine.set(keyOf2(row), { rowid: row.ac_rowid, stamp: row[stamp] });
68193
- }
68194
- const insert = db.prepare(`INSERT OR REPLACE INTO cookies (${quoted}) VALUES (${columns.map(() => "?").join(",")})`);
68195
- const remove = db.prepare("DELETE FROM cookies WHERE rowid = ?");
68196
- const nowUs = BigInt(now()) * 1000n + CHROME_EPOCH_OFFSET_US;
68197
- db.exec("BEGIN");
68212
+ if (child2.stdout) createInterface({ input: child2.stdout }).on("line", (line) => this.received(line));
68213
+ }
68214
+ received(line) {
68215
+ let message;
68198
68216
  try {
68199
- for (const row of list2(source, `SELECT ${quoted} FROM cookies`)) {
68200
- const id = keyOf2(row);
68201
- const updated = row[stamp];
68202
- next[id] = updated.toString();
68203
- const expires = row.expires_utc;
68204
- if (Number(row.is_persistent) === 1 && expires > 0n && expires < nowUs) {
68205
- counts.expired++;
68206
- continue;
68207
- }
68208
- const current = mine.get(id);
68209
- const changed = previous === void 0 || previous[id] !== updated.toString();
68210
- if (!changed || current?.stamp === updated) {
68211
- counts.kept++;
68212
- continue;
68213
- }
68214
- insert.run(...columns.map((column) => bindable(row[column])));
68215
- counts[current ? "updated" : "inserted"]++;
68217
+ message = JSON.parse(line);
68218
+ } catch {
68219
+ return;
68220
+ }
68221
+ const id = str(message.id);
68222
+ switch (message.event) {
68223
+ case "prompt": {
68224
+ if (!id) return;
68225
+ this.current = {
68226
+ id,
68227
+ kind: message.kind === "credentials" ? "credentials" : "consent",
68228
+ ...str(message.app) ? { app: str(message.app) } : {},
68229
+ ...str(message.publisher) ? { publisher: str(message.publisher) } : {},
68230
+ ...str(message.command) ? { command: str(message.command) } : {},
68231
+ lines: Array.isArray(message.lines) ? message.lines.filter((l) => typeof l === "string") : []
68232
+ };
68233
+ this.options.log(`administrator prompt: ${this.current.app ?? "an app"} asks to run as administrator`);
68234
+ return this.options.onChange();
68216
68235
  }
68217
- if (previous) {
68218
- for (const id of Object.keys(previous)) {
68219
- if (id in next) continue;
68220
- const current = mine.get(id);
68221
- if (current) {
68222
- remove.run(current.rowid);
68223
- counts.deleted++;
68224
- }
68236
+ case "gone":
68237
+ if (id && this.current?.id === id) {
68238
+ this.current = void 0;
68239
+ this.options.onChange();
68225
68240
  }
68241
+ return;
68242
+ case "answered": {
68243
+ const waiter = id ? this.waiting.get(id) : void 0;
68244
+ if (!waiter || !id) return;
68245
+ this.waiting.delete(id);
68246
+ if (message.ok === true) waiter.resolve();
68247
+ else waiter.reject(new Error(str(message.error) ?? "the prompt could not be answered"));
68248
+ return;
68249
+ }
68250
+ case "problem": {
68251
+ const problem = str(message.message);
68252
+ if (problem === this.problem) return;
68253
+ this.problem = problem;
68254
+ if (problem) this.options.log(`administrator prompts: ${problem}`);
68255
+ return this.options.onChange();
68226
68256
  }
68227
- db.exec("COMMIT");
68228
- } catch (error63) {
68229
- db.exec("ROLLBACK");
68230
- throw error63;
68231
- }
68232
- } finally {
68233
- source.close();
68234
- db.close();
68235
- }
68236
- }
68237
- function lastModified(meta3) {
68238
- let pos = 0;
68239
- while (pos < meta3.length) {
68240
- const tag = meta3[pos++];
68241
- let value = 0n;
68242
- let shift = 0n;
68243
- for (; ; ) {
68244
- const byte = meta3[pos++];
68245
- if (byte === void 0) return value.toString();
68246
- value |= BigInt(byte & 127) << shift;
68247
- shift += 7n;
68248
- if (!(byte & 128)) break;
68249
68257
  }
68250
- if (tag === 8) return value.toString();
68251
- }
68252
- return "0";
68253
- }
68254
- function mergeLocalStorage(source, target, previous, next, report) {
68255
- const merged = readLevelDb(target);
68256
- let changed = false;
68257
- if (!merged.has("VERSION") && source.has("VERSION")) {
68258
- merged.set("VERSION", source.get("VERSION"));
68259
- changed = true;
68260
68258
  }
68261
- for (const [key, meta3] of source) {
68262
- if (!key.startsWith("META:")) continue;
68263
- const origin = key.slice("META:".length);
68264
- const modified = lastModified(meta3);
68265
- next[origin] = modified;
68266
- const mine = merged.get(key);
68267
- if (previous !== void 0 && previous[origin] === modified || mine && mine.equals(meta3)) {
68268
- report.kept++;
68269
- continue;
68270
- }
68271
- const prefix = `_${origin}\0`;
68272
- for (const existing of [...merged.keys()]) if (existing.startsWith(prefix)) merged.delete(existing);
68273
- for (const [entry, value] of source) if (entry.startsWith(prefix)) merged.set(entry, value);
68274
- merged.set(key, meta3);
68275
- const access = source.get(`METAACCESS:${origin}`);
68276
- if (access) merged.set(`METAACCESS:${origin}`, access);
68277
- report.taken.push(origin);
68278
- changed = true;
68259
+ gone(problem) {
68260
+ if (this.closed) return;
68261
+ this.problem = problem;
68262
+ this.current = void 0;
68263
+ for (const waiter of this.waiting.values()) waiter.reject(new Error(problem));
68264
+ this.waiting.clear();
68265
+ this.options.log(`administrator prompts: ${problem}; starting it again`);
68266
+ this.options.onChange();
68267
+ const child2 = this.child;
68268
+ this.child = void 0;
68269
+ if (child2)
68270
+ setTimeout(() => {
68271
+ if (this.closed) return;
68272
+ this.problem = void 0;
68273
+ this.spawn();
68274
+ }, this.options.restartMs ?? RESTART_MS).unref();
68279
68275
  }
68280
- if (changed) writeLevelDb(target, merged);
68276
+ };
68277
+
68278
+ // src/audit.ts
68279
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68280
+ import { AsyncLocalStorage } from "node:async_hooks";
68281
+ import { appendFileSync, mkdirSync } from "node:fs";
68282
+ import { dirname } from "node:path";
68283
+ var callContext = new AsyncLocalStorage();
68284
+ var withCallContext = (context, fn) => callContext.run(context, fn);
68285
+ var currentCallContext = () => callContext.getStore() ?? {};
68286
+ function auditSinks(...sinks) {
68287
+ return (record2) => {
68288
+ const full = { ...callContext.getStore(), ...record2 };
68289
+ for (const sink of sinks) sink(full);
68290
+ };
68281
68291
  }
68282
- function newestMtime(dir) {
68283
- let newest = 0;
68284
- for (const entry of readdirSync2(dir, { withFileTypes: true, recursive: true })) {
68285
- if (entry.isFile()) newest = Math.max(newest, statSync(join3(entry.parentPath, entry.name)).mtimeMs);
68292
+ function redactArgs(args) {
68293
+ const out = {};
68294
+ for (const [key, value] of Object.entries(args)) {
68295
+ out[key] = (key === "text" || key === "value" || key === "content") && typeof value === "string" ? `<${value.length} chars>` : value;
68286
68296
  }
68287
- return newest;
68297
+ return out;
68288
68298
  }
68289
- function mergeIndexedDb(snapshot, target, previous, next, report) {
68290
- for (const name of readdirSync2(snapshot)) {
68291
- if (!name.endsWith(".indexeddb.leveldb")) continue;
68292
- const origin = name.slice(0, -".indexeddb.leveldb".length);
68293
- const modified = newestMtime(join3(snapshot, name));
68294
- next[origin] = modified;
68295
- const mine = join3(target, name);
68296
- if (previous !== void 0 && previous[origin] === modified || existsSync2(mine) && newestMtime(mine) === modified) {
68297
- report.kept++;
68298
- continue;
68299
- }
68300
- for (const suffix of [".indexeddb.leveldb", ".indexeddb.blob"]) {
68301
- const to = join3(target, origin + suffix);
68302
- rmSync2(to, { recursive: true, force: true });
68303
- const from = join3(snapshot, origin + suffix);
68304
- if (existsSync2(from)) cpSync(from, to, { recursive: true, preserveTimestamps: true });
68299
+ function fileAuditSink(path) {
68300
+ mkdirSync(dirname(path), { recursive: true });
68301
+ return (record2) => {
68302
+ const line = JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record2, args: redactArgs(record2.args) });
68303
+ try {
68304
+ appendFileSync(path, `${line}
68305
+ `);
68306
+ } catch (error63) {
68307
+ console.error(`audit write failed: ${error63.message}`);
68305
68308
  }
68306
- report.taken.push(origin);
68307
- }
68309
+ };
68308
68310
  }
68309
68311
 
68310
- // src/browser/launcher.ts
68311
- var BROWSER_NAMES = ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"];
68312
- var BASE_FLAGS = ["--no-first-run", "--no-default-browser-check", "--hide-crash-restore-bubble"];
68313
- var LOCK_STALE_MS = 6e4;
68314
- var LOCK_WAIT_MS = 3e4;
68315
- var OWN_WAIT_MS = 2e4;
68316
- function profileOwner(profile, host = hostname4()) {
68317
- let target;
68318
- try {
68319
- target = readlinkSync(join4(profile, "SingletonLock"));
68320
- } catch {
68321
- return void 0;
68322
- }
68323
- const match = /^(.*)-(\d+)$/.exec(target);
68324
- if (!match || match[1] !== host) return void 0;
68325
- const pid = Number(match[2]);
68326
- try {
68327
- process.kill(pid, 0);
68328
- return pid;
68329
- } catch (error63) {
68330
- return error63.code === "EPERM" ? pid : void 0;
68331
- }
68332
- }
68333
- function seedable(path) {
68334
- const name = basename2(path);
68335
- return !(name.startsWith("Singleton") || /cache$/i.test(name) || name === "Crash Reports" || name === "Sessions" || name === "Session Storage" || name === BASELINE_FILE);
68336
- }
68337
- function seedProfile(master, profile) {
68338
- mkdirSync3(dirname2(profile), { recursive: true });
68339
- cpSync2(master, profile, { recursive: true, preserveTimestamps: true, filter: seedable });
68340
- }
68341
- function findBrowser(path = process.env.PATH ?? "", skip = []) {
68342
- const skipped = new Set(skip.map((dir) => resolve(dir)));
68343
- for (const name of BROWSER_NAMES) {
68344
- for (const dir of path.split(delimiter)) {
68345
- if (!dir || skipped.has(resolve(dir))) continue;
68346
- const candidate = join4(dir, name);
68347
- try {
68348
- accessSync(candidate, constants.X_OK);
68349
- if (statSync2(candidate).isFile()) return candidate;
68350
- } catch {
68351
- }
68352
- }
68353
- }
68354
- return void 0;
68312
+ // src/browser/command.ts
68313
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68314
+
68315
+ // src/browser/close.ts
68316
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68317
+
68318
+ // src/linux/x11.ts
68319
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68320
+ import { readFileSync } from "node:fs";
68321
+ import { createConnection } from "node:net";
68322
+ import { homedir, hostname as hostname3 } from "node:os";
68323
+ import { join } from "node:path";
68324
+ function parseDisplay(display) {
68325
+ const match = /^([^:]*):(\d+)(?:\.\d+)?$/.exec(display ?? "");
68326
+ if (!match) return void 0;
68327
+ const host = match[1] ?? "";
68328
+ const number4 = Number(match[2]);
68329
+ if (host === "" || host === "unix") return { path: `/tmp/.X11-unix/X${number4}`, number: number4 };
68330
+ return { host, port: 6e3 + number4, number: number4 };
68355
68331
  }
68356
- async function launchBrowser(options) {
68357
- const log40 = options.log ?? (() => void 0);
68358
- const release3 = await lockProfile(options.profile);
68332
+ var FAMILY_LOCAL = 256;
68333
+ var FAMILY_WILD = 65535;
68334
+ var COOKIE = "MIT-MAGIC-COOKIE-1";
68335
+ function xauthCookie(file2, number4, host = hostname3()) {
68336
+ let offset = 0;
68337
+ let fallback;
68338
+ const field = () => {
68339
+ const length = file2.readUInt16BE(offset);
68340
+ const value = file2.subarray(offset + 2, offset + 2 + length);
68341
+ offset += 2 + length;
68342
+ return value;
68343
+ };
68359
68344
  try {
68360
- if (profileOwner(options.profile) !== void 0) {
68361
- start(options).unref();
68362
- return { handedOff: true, reports: [] };
68363
- }
68364
- if (!existsSync3(options.profile)) {
68365
- if (options.master && existsSync3(options.master)) {
68366
- seedProfile(options.master, options.profile);
68367
- log40(`browser profile ${options.profile} created from ${options.master}`);
68368
- } else mkdirSync3(options.profile, { recursive: true });
68369
- }
68370
- for (const name of ["SingletonLock", "SingletonCookie", "SingletonSocket"]) {
68371
- rmSync3(join4(options.profile, name), { force: true });
68345
+ while (offset < file2.length) {
68346
+ const family = file2.readUInt16BE(offset);
68347
+ offset += 2;
68348
+ const address = field().toString("latin1");
68349
+ const display = field().toString("latin1");
68350
+ const name = field().toString("latin1");
68351
+ const data = field();
68352
+ if (name !== COOKIE || display !== "" && display !== String(number4)) continue;
68353
+ if (family === FAMILY_WILD || family === FAMILY_LOCAL && address === host) return Buffer.from(data);
68354
+ fallback ??= Buffer.from(data);
68372
68355
  }
68373
- const self2 = realpathSync2(options.profile);
68374
- const sources = options.sources.filter(
68375
- (source) => existsSync3(join4(source, "Default")) && realpathSync2(source) !== self2
68376
- );
68377
- const reports = await forkMerge(options.profile, sources);
68378
- for (const report of reports) log40(`browser fork-merge from ${report.source}: ${summarize(report)}`);
68379
- const child2 = start(options);
68380
- if (!await owned(options.profile, child2)) log40(`browser for ${options.profile} did not take its profile`);
68381
- return { handedOff: false, reports, ...child2.pid !== void 0 ? { pid: child2.pid } : {} };
68382
- } finally {
68383
- release3();
68356
+ } catch {
68384
68357
  }
68358
+ return fallback;
68385
68359
  }
68386
- function start(options) {
68387
- const child2 = spawn2(options.browser, [`--user-data-dir=${options.profile}`, ...BASE_FLAGS, ...options.args ?? []], {
68388
- detached: true,
68389
- stdio: "ignore",
68390
- env: options.env ?? process.env
68391
- });
68392
- child2.on("error", () => void 0);
68393
- return child2;
68394
- }
68395
- async function owned(profile, child2) {
68396
- let ended = false;
68397
- const end = () => void (ended = true);
68398
- child2.once("error", end).once("exit", end);
68399
- try {
68400
- const deadline = Date.now() + OWN_WAIT_MS;
68401
- for (; ; ) {
68402
- if (profileOwner(profile) !== void 0) return true;
68403
- if (ended || Date.now() > deadline) return false;
68404
- await new Promise((resolveWait) => setTimeout(resolveWait, 100));
68405
- }
68406
- } finally {
68407
- child2.off("error", end).off("exit", end);
68408
- child2.unref();
68360
+ var pad4 = (n) => (4 - n % 4) % 4;
68361
+ var X11Error = class extends Error {
68362
+ constructor(code, sequence) {
68363
+ super(`X11 error ${code} (request ${sequence})`);
68364
+ this.code = code;
68365
+ this.sequence = sequence;
68366
+ this.name = "X11Error";
68409
68367
  }
68410
- }
68411
- function summarize(report) {
68412
- const c = report.cookies;
68413
- return [
68414
- report.firstFork ? "first fork" : "since last fork",
68415
- `cookies +${c.inserted} ~${c.updated} -${c.deleted} (kept ${c.kept}, expired ${c.expired})`,
68416
- `localStorage ${report.localStorage.taken.length} origin(s)`,
68417
- `IndexedDB ${report.indexedDb.taken.length} origin(s)`
68418
- ].join(", ");
68419
- }
68420
- async function lockProfile(profile) {
68421
- const path = `${profile}.launch-lock`;
68422
- mkdirSync3(dirname2(path), { recursive: true });
68423
- const deadline = Date.now() + LOCK_WAIT_MS;
68424
- for (; ; ) {
68368
+ code;
68369
+ sequence;
68370
+ };
68371
+ var X11Connection = class _X11Connection {
68372
+ constructor(socket, setup2) {
68373
+ this.socket = socket;
68374
+ this.setup = setup2;
68375
+ socket.on("data", (chunk) => this.receive(chunk));
68376
+ socket.on("error", (error63) => this.close(error63));
68377
+ socket.on("close", () => this.close());
68378
+ }
68379
+ socket;
68380
+ setup;
68381
+ buffer = Buffer.alloc(0);
68382
+ sequence = 0;
68383
+ pending = /* @__PURE__ */ new Map();
68384
+ errors = /* @__PURE__ */ new Map();
68385
+ closed = false;
68386
+ onEvent = () => void 0;
68387
+ onClose = () => void 0;
68388
+ static async connect(options = {}) {
68389
+ const address = parseDisplay(options.display ?? process.env.DISPLAY);
68390
+ if (!address) throw new Error("DISPLAY is not set to an X11 display");
68391
+ const authFile = options.xauthority ?? process.env.XAUTHORITY ?? join(homedir(), ".Xauthority");
68392
+ let cookie;
68425
68393
  try {
68426
- closeSync(openSync(path, "wx"));
68427
- return () => rmSync3(path, { force: true });
68428
- } catch (error63) {
68429
- if (error63.code !== "EEXIST") throw error63;
68430
- try {
68431
- if (Date.now() - statSync2(path).mtimeMs > LOCK_STALE_MS) rmSync3(path, { force: true });
68432
- } catch {
68433
- }
68434
- if (Date.now() > deadline) throw new Error(`another browser launch for ${profile} is still running`);
68435
- await new Promise((resolveWait) => setTimeout(resolveWait, 200));
68394
+ cookie = xauthCookie(readFileSync(authFile), address.number);
68395
+ } catch {
68436
68396
  }
68437
- }
68438
- }
68439
-
68440
- // src/browser/close.ts
68441
- var OP_QUERY_TREE = 15;
68442
- var OP_INTERN_ATOM = 16;
68443
- var OP_GET_PROPERTY = 20;
68444
- var OP_SEND_EVENT = 25;
68445
- var CLIENT_MESSAGE = 33;
68446
- async function closeBrowser(options) {
68447
- const log40 = options.log ?? (() => void 0);
68448
- const pid = profileOwner(options.profile);
68449
- if (pid === void 0) return "not-running";
68450
- try {
68451
- const x = await X11Connection.connect({
68452
- display: options.display,
68453
- ...options.xauthority ? { xauthority: options.xauthority } : {}
68397
+ const socket = options.socketPath ? createConnection(options.socketPath) : "path" in address ? createConnection(address.path) : createConnection(address.port, address.host);
68398
+ socket.setNoDelay(true);
68399
+ const timeoutMs = options.timeoutMs ?? 5e3;
68400
+ const setup2 = await new Promise((resolve5, reject) => {
68401
+ let data = Buffer.alloc(0);
68402
+ const timer = setTimeout(() => fail(new Error("X11 connection setup timed out")), timeoutMs);
68403
+ const fail = (error63) => {
68404
+ clearTimeout(timer);
68405
+ socket.off("data", onData);
68406
+ socket.destroy();
68407
+ reject(error63);
68408
+ };
68409
+ const onData = (chunk) => {
68410
+ data = Buffer.concat([data, chunk]);
68411
+ if (data.length < 8) return;
68412
+ const total = 8 + data.readUInt16LE(6) * 4;
68413
+ if (data.length < total) return;
68414
+ clearTimeout(timer);
68415
+ socket.off("data", onData);
68416
+ socket.off("error", fail);
68417
+ if (data[0] !== 1) {
68418
+ const reason = data.subarray(8, 8 + (data[1] ?? 0)).toString("latin1");
68419
+ socket.destroy();
68420
+ return reject(new Error(`X11 server refused the connection: ${reason || "authorization required"}`));
68421
+ }
68422
+ try {
68423
+ resolve5({ setup: parseSetup(data.subarray(0, total)), rest: data.subarray(total) });
68424
+ } catch (error63) {
68425
+ fail(error63);
68426
+ }
68427
+ };
68428
+ socket.once("error", fail);
68429
+ socket.on("data", onData);
68430
+ socket.write(setupRequest(cookie));
68454
68431
  });
68455
- try {
68456
- const windows = await windowsOf(x, pid);
68457
- const protocols = await internAtom(x, "WM_PROTOCOLS");
68458
- const remove = await internAtom(x, "WM_DELETE_WINDOW");
68459
- for (const window2 of windows) await sendClientMessage(x, window2, protocols, [remove, 0, 0, 0, 0]);
68460
- log40(`asked ${windows.length} browser window(s) of ${options.profile} to close`);
68461
- } finally {
68462
- x.close();
68432
+ const connection = new _X11Connection(socket, setup2.setup);
68433
+ if (setup2.rest.length) connection.receive(setup2.rest);
68434
+ return connection;
68435
+ }
68436
+ listen(listener) {
68437
+ this.onEvent = listener;
68438
+ }
68439
+ whenClosed(listener) {
68440
+ this.onClose = listener;
68441
+ }
68442
+ /** Sends a request that has a reply and resolves with the whole reply. */
68443
+ request(body) {
68444
+ if (this.closed) return Promise.reject(new Error("X11 connection closed"));
68445
+ const sequence = this.send(body);
68446
+ return new Promise((resolve5, reject) => this.pending.set(sequence, { resolve: resolve5, reject }));
68447
+ }
68448
+ /** Sends a request without a reply; resolves once the server processed it, rejecting with its error. */
68449
+ async checked(body) {
68450
+ const sequence = this.send(body);
68451
+ await this.request(request(43, 0, Buffer.alloc(0)));
68452
+ const error63 = this.errors.get(sequence);
68453
+ this.errors.delete(sequence);
68454
+ if (error63) throw error63;
68455
+ }
68456
+ close(error63) {
68457
+ if (this.closed) return;
68458
+ this.closed = true;
68459
+ this.socket.destroy();
68460
+ for (const pending of this.pending.values()) pending.reject(error63 ?? new Error("X11 connection closed"));
68461
+ this.pending.clear();
68462
+ this.onClose(error63);
68463
+ }
68464
+ send(body) {
68465
+ this.sequence = this.sequence + 1 & 65535;
68466
+ this.socket.write(body);
68467
+ return this.sequence;
68468
+ }
68469
+ receive(chunk) {
68470
+ this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;
68471
+ while (this.buffer.length >= 32) {
68472
+ const kind = this.buffer[0] & 127;
68473
+ const total = kind === 1 || kind === 35 ? 32 + this.buffer.readUInt32LE(4) * 4 : 32;
68474
+ if (this.buffer.length < total) return;
68475
+ const message = this.buffer.subarray(0, total);
68476
+ this.buffer = this.buffer.subarray(total);
68477
+ this.dispatch(kind, message);
68463
68478
  }
68464
- } catch (error63) {
68465
- log40(`could not ask the browser of ${options.profile} to close: ${error63.message}`);
68466
68479
  }
68467
- if (await exited(pid, options.timeoutMs ?? 15e3)) return "closed";
68468
- log40(`browser ${pid} did not exit after its windows closed; sending SIGTERM (unflushed cookies may be lost)`);
68469
- process.kill(pid, "SIGTERM");
68470
- if (await exited(pid, 5e3)) return "terminated";
68471
- process.kill(pid, "SIGKILL");
68472
- return "killed";
68473
- }
68474
- async function waitForWindowManager(display, timeoutMs) {
68475
- const deadline = Date.now() + timeoutMs;
68476
- while (Date.now() < deadline) {
68477
- try {
68478
- const x = await X11Connection.connect({ display });
68479
- try {
68480
- const check2 = await internAtom(x, "_NET_SUPPORTING_WM_CHECK");
68481
- if (await cardinal(x, x.setup.root, check2, 33) !== void 0) return true;
68482
- } finally {
68483
- x.close();
68480
+ dispatch(kind, message) {
68481
+ const sequence = message.readUInt16LE(2);
68482
+ if (kind === 1 || kind === 0) {
68483
+ const pending = this.pending.get(sequence);
68484
+ if (pending) {
68485
+ this.pending.delete(sequence);
68486
+ if (kind === 1) pending.resolve(Buffer.from(message));
68487
+ else pending.reject(new X11Error(message[1], sequence));
68488
+ return;
68484
68489
  }
68485
- } catch {
68490
+ if (kind === 0) {
68491
+ this.errors.set(sequence, new X11Error(message[1], sequence));
68492
+ if (this.errors.size > 64) this.errors.delete(this.errors.keys().next().value);
68493
+ }
68494
+ return;
68486
68495
  }
68487
- await new Promise((resolve5) => setTimeout(resolve5, 200));
68496
+ this.onEvent(Buffer.from(message));
68488
68497
  }
68489
- return false;
68498
+ };
68499
+ function setupRequest(cookie) {
68500
+ const name = cookie ? Buffer.from(COOKIE, "latin1") : Buffer.alloc(0);
68501
+ const data = cookie ?? Buffer.alloc(0);
68502
+ const out = Buffer.alloc(12 + name.length + pad4(name.length) + data.length + pad4(data.length));
68503
+ out.write("l", 0, "latin1");
68504
+ out.writeUInt16LE(11, 2);
68505
+ out.writeUInt16LE(0, 4);
68506
+ out.writeUInt16LE(name.length, 6);
68507
+ out.writeUInt16LE(data.length, 8);
68508
+ name.copy(out, 12);
68509
+ data.copy(out, 12 + name.length + pad4(name.length));
68510
+ return out;
68490
68511
  }
68491
- async function exited(pid, timeoutMs) {
68492
- const deadline = Date.now() + timeoutMs;
68493
- for (; ; ) {
68494
- try {
68495
- process.kill(pid, 0);
68496
- } catch {
68497
- return true;
68498
- }
68499
- if (Date.now() > deadline) return false;
68500
- await new Promise((resolve5) => setTimeout(resolve5, 200));
68501
- }
68512
+ function parseSetup(reply2) {
68513
+ const vendorLength = reply2.readUInt16LE(24);
68514
+ const formats = reply2[29];
68515
+ const minKeycode = reply2[34];
68516
+ const maxKeycode = reply2[35];
68517
+ const screens = 40 + vendorLength + pad4(vendorLength) + formats * 8;
68518
+ if (reply2.length < screens + 4) throw new Error("X11 setup reply has no screen");
68519
+ return { root: reply2.readUInt32LE(screens), minKeycode, maxKeycode };
68502
68520
  }
68503
- async function windowsOf(x, pid) {
68504
- const pidAtom = await internAtom(x, "_NET_WM_PID");
68505
- const found = [];
68506
- for (const frame of await queryTree(x, x.setup.root)) {
68507
- for (const window2 of [frame, ...await queryTree(x, frame)]) {
68508
- const value = await cardinal(x, window2, pidAtom);
68509
- if (value === pid) found.push(window2);
68510
- }
68511
- }
68512
- return found;
68521
+ function request(opcode, minor, body) {
68522
+ const out = Buffer.alloc(4 + body.length + pad4(body.length));
68523
+ out[0] = opcode;
68524
+ out[1] = minor;
68525
+ out.writeUInt16LE(out.length / 4, 2);
68526
+ body.copy(out, 4);
68527
+ return out;
68513
68528
  }
68514
- async function internAtom(x, name) {
68529
+ var OP_GRAB_KEY = 33;
68530
+ var OP_UNGRAB_KEY = 34;
68531
+ var OP_QUERY_EXTENSION = 98;
68532
+ var OP_GET_KEYBOARD_MAPPING = 101;
68533
+ var OP_GET_MODIFIER_MAPPING = 119;
68534
+ async function queryExtension(x, name) {
68515
68535
  const bytes = Buffer.from(name, "latin1");
68516
68536
  const body = Buffer.alloc(4 + bytes.length);
68517
68537
  body.writeUInt16LE(bytes.length, 0);
68518
68538
  bytes.copy(body, 4);
68519
- return (await x.request(request(OP_INTERN_ATOM, 0, body))).readUInt32LE(8);
68520
- }
68521
- async function queryTree(x, window2) {
68522
- const body = Buffer.alloc(4);
68523
- body.writeUInt32LE(window2, 0);
68524
- const reply2 = await x.request(request(OP_QUERY_TREE, 0, body)).catch(() => void 0);
68525
- if (!reply2) return [];
68526
- const count = reply2.readUInt16LE(16);
68527
- return Array.from({ length: count }, (_, i) => reply2.readUInt32LE(32 + i * 4));
68528
- }
68529
- async function cardinal(x, window2, property, type = 0) {
68530
- const body = Buffer.alloc(20);
68531
- body.writeUInt32LE(window2, 0);
68532
- body.writeUInt32LE(property, 4);
68533
- body.writeUInt32LE(type, 8);
68534
- body.writeUInt32LE(0, 12);
68535
- body.writeUInt32LE(1, 16);
68536
- const reply2 = await x.request(request(OP_GET_PROPERTY, 0, body)).catch(() => void 0);
68537
- if (!reply2 || reply2[1] !== 32 || reply2.readUInt32LE(16) < 1) return void 0;
68538
- return reply2.readUInt32LE(32);
68539
- }
68540
- async function sendClientMessage(x, window2, type, data) {
68541
- const event = Buffer.alloc(32);
68542
- event[0] = CLIENT_MESSAGE;
68543
- event[1] = 32;
68544
- event.writeUInt32LE(window2, 4);
68545
- event.writeUInt32LE(type, 8);
68546
- data.forEach((value, i) => event.writeUInt32LE(value >>> 0, 12 + i * 4));
68547
- const body = Buffer.alloc(40);
68548
- body.writeUInt32LE(window2, 0);
68549
- body.writeUInt32LE(0, 4);
68550
- event.copy(body, 8);
68551
- await x.checked(request(OP_SEND_EVENT, 0, body));
68539
+ const reply2 = await x.request(request(OP_QUERY_EXTENSION, 0, body));
68540
+ return reply2[8] ? reply2[9] : void 0;
68552
68541
  }
68553
68542
 
68554
- // src/linux/desktops.ts
68555
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68556
- import { spawn as spawn5, spawnSync } from "node:child_process";
68557
- import { chmodSync, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
68558
- import { homedir as homedir2 } from "node:os";
68559
- import { join as join6 } from "node:path";
68560
-
68561
- // src/computer.ts
68562
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68563
- import { hostname as hostname5, release } from "node:os";
68564
-
68565
- // ../protocol/src/frames/computer.ts
68543
+ // src/browser/launcher.ts
68566
68544
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68545
+ import { spawn as spawn2 } from "node:child_process";
68546
+ import {
68547
+ accessSync,
68548
+ closeSync,
68549
+ constants,
68550
+ cpSync as cpSync2,
68551
+ existsSync as existsSync3,
68552
+ mkdirSync as mkdirSync3,
68553
+ openSync,
68554
+ readlinkSync,
68555
+ realpathSync as realpathSync2,
68556
+ rmSync as rmSync3,
68557
+ statSync as statSync2
68558
+ } from "node:fs";
68559
+ import { hostname as hostname4 } from "node:os";
68560
+ import { basename as basename2, delimiter, dirname as dirname2, join as join4, resolve } from "node:path";
68567
68561
 
68568
- // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/index.js
68562
+ // src/browser/profile-merge.ts
68569
68563
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68564
+ import {
68565
+ cpSync,
68566
+ existsSync as existsSync2,
68567
+ mkdtempSync,
68568
+ readFileSync as readFileSync3,
68569
+ readdirSync as readdirSync2,
68570
+ realpathSync,
68571
+ rmSync as rmSync2,
68572
+ statSync,
68573
+ writeFileSync as writeFileSync2
68574
+ } from "node:fs";
68575
+ import { tmpdir } from "node:os";
68576
+ import { basename, join as join3 } from "node:path";
68570
68577
 
68571
- // ../protocol/src/envelope.ts
68578
+ // src/browser/leveldb.ts
68572
68579
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68573
- var Envelope = external_exports.object({
68574
- v: external_exports.literal(1),
68575
- // protocol major; bump = breaking
68576
- id: external_exports.string().uuid(),
68577
- // unique per frame (sender-generated)
68578
- ts: external_exports.string().datetime(),
68579
- // RFC3339, sender clock (advisory only)
68580
- type: external_exports.string(),
68581
- // frame discriminator, e.g. "register"
68582
- corr: external_exports.string().uuid().optional(),
68583
- // correlation: set on a reply to the request's `id`
68584
- orgId: external_exports.string().min(1).max(64).optional(),
68585
- // tenant context on an install-wide daemon connection
68586
- payload: external_exports.unknown()
68587
- // validated by the per-type schema
68588
- });
68589
- var ControlExt = external_exports.object({
68590
- epoch: external_exports.number().int(),
68591
- // sessionEpoch this frame was issued under (§3.1 fencing)
68592
- agentId: external_exports.string().uuid().optional(),
68593
- // present on agent-scoped frames
68594
- launchId: external_exports.string().uuid().optional()
68595
- // per-launch fence, §4.4
68596
- });
68597
- var NIL_UUID = "00000000-0000-0000-0000-000000000000";
68598
- function frameSchema(type, payload) {
68599
- return external_exports.object({
68600
- v: external_exports.literal(1),
68601
- id: external_exports.string().uuid(),
68602
- ts: external_exports.string().datetime(),
68603
- type: external_exports.literal(type),
68604
- corr: external_exports.string().uuid().optional(),
68605
- orgId: external_exports.string().min(1).max(64).optional(),
68606
- payload
68607
- });
68580
+ import { existsSync, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
68581
+ import { join as join2 } from "node:path";
68582
+ var BLOCK_SIZE = 32 * 1024;
68583
+ var HEADER_SIZE = 7;
68584
+ var FULL = 1;
68585
+ var FIRST = 2;
68586
+ var MIDDLE = 3;
68587
+ var LAST = 4;
68588
+ var TYPE_DELETION = 0;
68589
+ var TYPE_VALUE = 1;
68590
+ var TABLE_MAGIC = 0xdb4775248b80fb57n;
68591
+ var BATCH_LIMIT_BYTES = 1024 * 1024;
68592
+ var CRC_TABLE = (() => {
68593
+ const table = new Uint32Array(256);
68594
+ for (let n = 0; n < 256; n++) {
68595
+ let c = n;
68596
+ for (let k = 0; k < 8; k++) c = c & 1 ? 2197175160 ^ c >>> 1 : c >>> 1;
68597
+ table[n] = c >>> 0;
68598
+ }
68599
+ return table;
68600
+ })();
68601
+ function crc32c(data, initial = 0) {
68602
+ let crc = ~initial >>> 0;
68603
+ for (const byte of data) crc = CRC_TABLE[(crc ^ byte) & 255] ^ crc >>> 8;
68604
+ return ~crc >>> 0;
68608
68605
  }
68609
-
68610
- // ../protocol/src/tolerant.ts
68611
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68612
- var memo3 = /* @__PURE__ */ new WeakMap();
68613
- function tolerantReader(schema) {
68614
- const hit = memo3.get(schema);
68615
- if (hit) return hit;
68616
- const built = rebuild(schema);
68617
- memo3.set(schema, built);
68618
- return built;
68606
+ function maskCrc(crc) {
68607
+ return (crc >>> 15 | crc << 17) + 2726488792 >>> 0;
68619
68608
  }
68620
- function tolerantSchemas(schemas) {
68621
- return Object.fromEntries(Object.entries(schemas).map(([type, schema]) => [type, tolerantReader(schema)]));
68609
+ var Reader = class {
68610
+ constructor(buf, pos = 0) {
68611
+ this.buf = buf;
68612
+ this.pos = pos;
68613
+ }
68614
+ buf;
68615
+ pos;
68616
+ get done() {
68617
+ return this.pos >= this.buf.length;
68618
+ }
68619
+ varint() {
68620
+ let result = 0;
68621
+ let shift = 0;
68622
+ for (; ; ) {
68623
+ if (this.pos >= this.buf.length) throw new Error("leveldb: truncated varint");
68624
+ const byte = this.buf[this.pos++];
68625
+ result += (byte & 127) * 2 ** shift;
68626
+ if (!(byte & 128)) return result;
68627
+ shift += 7;
68628
+ if (shift > 63) throw new Error("leveldb: varint too long");
68629
+ }
68630
+ }
68631
+ bytes(length) {
68632
+ if (this.pos + length > this.buf.length) throw new Error("leveldb: truncated slice");
68633
+ const out = this.buf.subarray(this.pos, this.pos + length);
68634
+ this.pos += length;
68635
+ return out;
68636
+ }
68637
+ slice() {
68638
+ return this.bytes(this.varint());
68639
+ }
68640
+ };
68641
+ function varint(value) {
68642
+ const out = [];
68643
+ let v = value;
68644
+ while (v >= 128) {
68645
+ out.push(v % 128 | 128);
68646
+ v = Math.floor(v / 128);
68647
+ }
68648
+ out.push(v);
68649
+ return Buffer.from(out);
68622
68650
  }
68623
- function isSchema(value) {
68624
- return typeof value === "object" && value !== null && "_zod" in value;
68651
+ function lengthPrefixed(data) {
68652
+ return Buffer.concat([varint(data.length), data]);
68625
68653
  }
68626
- function defOf(schema) {
68627
- return schema._zod.def;
68654
+ function snappyDecompress(input2) {
68655
+ const reader = new Reader(input2);
68656
+ const length = reader.varint();
68657
+ const out = Buffer.alloc(length);
68658
+ let o = 0;
68659
+ while (!reader.done) {
68660
+ const tag = input2[reader.pos++];
68661
+ const kind = tag & 3;
68662
+ if (kind === 0) {
68663
+ let len2 = tag >>> 2;
68664
+ if (len2 >= 60) {
68665
+ const extra = len2 - 59;
68666
+ len2 = input2.readUIntLE(reader.pos, extra);
68667
+ reader.pos += extra;
68668
+ }
68669
+ len2 += 1;
68670
+ input2.copy(out, o, reader.pos, reader.pos + len2);
68671
+ reader.pos += len2;
68672
+ o += len2;
68673
+ continue;
68674
+ }
68675
+ let len;
68676
+ let offset;
68677
+ if (kind === 1) {
68678
+ len = (tag >>> 2 & 7) + 4;
68679
+ offset = tag >>> 5 << 8 | input2[reader.pos++];
68680
+ } else if (kind === 2) {
68681
+ len = (tag >>> 2) + 1;
68682
+ offset = input2.readUInt16LE(reader.pos);
68683
+ reader.pos += 2;
68684
+ } else {
68685
+ len = (tag >>> 2) + 1;
68686
+ offset = input2.readUInt32LE(reader.pos);
68687
+ reader.pos += 4;
68688
+ }
68689
+ if (offset === 0 || offset > o) throw new Error("leveldb: bad snappy offset");
68690
+ for (let i = 0; i < len; i++, o++) out[o] = out[o - offset];
68691
+ }
68692
+ if (o !== length) throw new Error("leveldb: snappy length mismatch");
68693
+ return out;
68628
68694
  }
68629
- function child(value) {
68630
- return tolerantReader(value);
68695
+ function readLogRecords(data) {
68696
+ const records = [];
68697
+ let pending;
68698
+ let pos = 0;
68699
+ while (pos < data.length) {
68700
+ const left = BLOCK_SIZE - pos % BLOCK_SIZE;
68701
+ if (left < HEADER_SIZE) {
68702
+ pos += left;
68703
+ continue;
68704
+ }
68705
+ if (pos + HEADER_SIZE > data.length) break;
68706
+ const length = data.readUInt16LE(pos + 4);
68707
+ const type = data[pos + 6];
68708
+ if (type === 0 && length === 0) {
68709
+ pos += left;
68710
+ continue;
68711
+ }
68712
+ if (pos + HEADER_SIZE + length > data.length) break;
68713
+ const payload = data.subarray(pos + HEADER_SIZE, pos + HEADER_SIZE + length);
68714
+ pos += HEADER_SIZE + length;
68715
+ if (type === FULL) {
68716
+ records.push(Buffer.from(payload));
68717
+ pending = void 0;
68718
+ } else if (type === FIRST) pending = [payload];
68719
+ else if (type === MIDDLE && pending) pending.push(payload);
68720
+ else if (type === LAST && pending) {
68721
+ pending.push(payload);
68722
+ records.push(Buffer.concat(pending));
68723
+ pending = void 0;
68724
+ }
68725
+ }
68726
+ return records;
68631
68727
  }
68632
- function withDef(schema, def) {
68633
- return external_exports.clone(schema, def);
68728
+ function writeLogRecords(records) {
68729
+ const chunks = [];
68730
+ let offset = 0;
68731
+ const emit = (type, payload) => {
68732
+ const header = Buffer.alloc(HEADER_SIZE);
68733
+ header.writeUInt32LE(maskCrc(crc32c(payload, crc32c(Buffer.from([type])))), 0);
68734
+ header.writeUInt16LE(payload.length, 4);
68735
+ header[6] = type;
68736
+ chunks.push(header, payload);
68737
+ offset += HEADER_SIZE + payload.length;
68738
+ };
68739
+ for (const record2 of records) {
68740
+ let pos = 0;
68741
+ let first = true;
68742
+ do {
68743
+ let left = BLOCK_SIZE - offset % BLOCK_SIZE;
68744
+ if (left < HEADER_SIZE) {
68745
+ chunks.push(Buffer.alloc(left));
68746
+ offset += left;
68747
+ left = BLOCK_SIZE;
68748
+ }
68749
+ const take = Math.min(left - HEADER_SIZE, record2.length - pos);
68750
+ const end = pos + take === record2.length;
68751
+ emit(first && end ? FULL : first ? FIRST : end ? LAST : MIDDLE, record2.subarray(pos, pos + take));
68752
+ pos += take;
68753
+ first = false;
68754
+ } while (pos < record2.length);
68755
+ }
68756
+ return Buffer.concat(chunks);
68757
+ }
68758
+ function apply(entries2, key, sequence, deleted, value) {
68759
+ const id = key.toString("latin1");
68760
+ const current = entries2.get(id);
68761
+ if (!current || current.sequence < sequence) entries2.set(id, { sequence, deleted, value: Buffer.from(value) });
68762
+ }
68763
+ function applyBatch(entries2, batch) {
68764
+ if (batch.length < 12) return;
68765
+ let sequence = batch.readBigUInt64LE(0);
68766
+ const count = batch.readUInt32LE(8);
68767
+ const reader = new Reader(batch, 12);
68768
+ for (let i = 0; i < count; i++, sequence++) {
68769
+ const type = batch[reader.pos++];
68770
+ if (type === TYPE_VALUE) {
68771
+ const key = reader.slice();
68772
+ apply(entries2, key, sequence, false, reader.slice());
68773
+ } else if (type === TYPE_DELETION) apply(entries2, reader.slice(), sequence, true, Buffer.alloc(0));
68774
+ else throw new Error("leveldb: unknown write batch record");
68775
+ }
68776
+ }
68777
+ function blockEntries(block, each) {
68778
+ if (block.length < 4) return;
68779
+ const restarts = block.readUInt32LE(block.length - 4);
68780
+ const end = block.length - 4 - restarts * 4;
68781
+ const reader = new Reader(block.subarray(0, end));
68782
+ let last = Buffer.alloc(0);
68783
+ while (!reader.done) {
68784
+ const shared = reader.varint();
68785
+ const unshared = reader.varint();
68786
+ const valueLength = reader.varint();
68787
+ const key = Buffer.concat([last.subarray(0, shared), reader.bytes(unshared)]);
68788
+ each(key, reader.bytes(valueLength));
68789
+ last = key;
68790
+ }
68791
+ }
68792
+ function readBlock(file2, handle) {
68793
+ const offset = handle.varint();
68794
+ const size = handle.varint();
68795
+ const contents = file2.subarray(offset, offset + size);
68796
+ const compression = file2[offset + size];
68797
+ if (compression === 0) return contents;
68798
+ if (compression === 1) return snappyDecompress(contents);
68799
+ throw new Error(`leveldb: unsupported block compression ${compression}`);
68800
+ }
68801
+ function readTable(file2, entries2) {
68802
+ if (file2.length < 48) throw new Error("leveldb: table too short");
68803
+ const footer = file2.subarray(file2.length - 48);
68804
+ if (footer.readBigUInt64LE(40) !== TABLE_MAGIC) throw new Error("leveldb: bad table magic");
68805
+ const handles = new Reader(footer);
68806
+ handles.varint();
68807
+ handles.varint();
68808
+ const index = readBlock(file2, handles);
68809
+ blockEntries(index, (_key, handle) => {
68810
+ blockEntries(readBlock(file2, new Reader(handle)), (internal, value) => {
68811
+ const tag = internal.readBigUInt64LE(internal.length - 8);
68812
+ apply(entries2, internal.subarray(0, internal.length - 8), tag >> 8n, Number(tag & 0xffn) === TYPE_DELETION, value);
68813
+ });
68814
+ });
68634
68815
  }
68635
- function rebuild(schema) {
68636
- const def = defOf(schema);
68637
- switch (def.type) {
68638
- case "object": {
68639
- const shape = Object.fromEntries(
68640
- Object.entries(def.shape).map(([key, value]) => [key, child(value)])
68641
- );
68642
- const catchall = isNeverSchema(def.catchall) ? void 0 : def.catchall ? child(def.catchall) : void 0;
68643
- return withDef(schema, { ...def, shape, catchall });
68816
+ function readManifest(data) {
68817
+ const manifest = { logNumber: 0, prevLogNumber: 0, tables: /* @__PURE__ */ new Set() };
68818
+ for (const record2 of readLogRecords(data)) {
68819
+ const reader = new Reader(record2);
68820
+ while (!reader.done) {
68821
+ const tag = reader.varint();
68822
+ if (tag === 1) reader.slice();
68823
+ else if (tag === 2) manifest.logNumber = reader.varint();
68824
+ else if (tag === 3) reader.varint();
68825
+ else if (tag === 4) reader.varint();
68826
+ else if (tag === 5) {
68827
+ reader.varint();
68828
+ reader.slice();
68829
+ } else if (tag === 6) {
68830
+ reader.varint();
68831
+ manifest.tables.delete(reader.varint());
68832
+ } else if (tag === 7) {
68833
+ reader.varint();
68834
+ manifest.tables.add(reader.varint());
68835
+ reader.varint();
68836
+ reader.slice();
68837
+ reader.slice();
68838
+ } else if (tag === 9) manifest.prevLogNumber = reader.varint();
68839
+ else throw new Error(`leveldb: unknown manifest tag ${tag}`);
68644
68840
  }
68645
- case "array":
68646
- return withDef(schema, { ...def, element: child(def.element) });
68647
- // Both plain and discriminated unions; the discriminator rides along in the spread def.
68648
- case "union":
68649
- return withDef(schema, { ...def, options: def.options.map(child) });
68650
- case "intersection":
68651
- return withDef(schema, { ...def, left: child(def.left), right: child(def.right) });
68652
- case "tuple":
68653
- return withDef(schema, {
68654
- ...def,
68655
- items: def.items.map(child),
68656
- ...isSchema(def.rest) ? { rest: child(def.rest) } : {}
68657
- });
68658
- case "record":
68659
- case "map":
68660
- return withDef(schema, { ...def, keyType: child(def.keyType), valueType: child(def.valueType) });
68661
- case "set":
68662
- return withDef(schema, { ...def, valueType: child(def.valueType) });
68663
- case "optional":
68664
- case "nullable":
68665
- case "nonoptional":
68666
- case "default":
68667
- case "prefault":
68668
- case "catch":
68669
- case "readonly":
68670
- case "promise":
68671
- return withDef(schema, { ...def, innerType: child(def.innerType) });
68672
- case "pipe":
68673
- return withDef(schema, { ...def, in: child(def.in), out: child(def.out) });
68674
- case "lazy":
68675
- return external_exports.lazy(() => child(def.getter()));
68676
- default:
68677
- return schema;
68678
68841
  }
68842
+ return manifest;
68679
68843
  }
68680
- function isNeverSchema(value) {
68681
- return isSchema(value) && defOf(value).type === "never";
68844
+ function readLevelDb(dir) {
68845
+ const entries2 = /* @__PURE__ */ new Map();
68846
+ if (!existsSync(join2(dir, "CURRENT"))) return /* @__PURE__ */ new Map();
68847
+ const current = readFileSync2(join2(dir, "CURRENT"), "latin1").trim();
68848
+ const manifest = readManifest(readFileSync2(join2(dir, current)));
68849
+ const files = readdirSync(dir);
68850
+ for (const number4 of manifest.tables) {
68851
+ const name = [`${String(number4).padStart(6, "0")}.ldb`, `${String(number4).padStart(6, "0")}.sst`].find(
68852
+ (n) => files.includes(n)
68853
+ );
68854
+ if (!name) throw new Error(`leveldb: table ${number4} is missing`);
68855
+ readTable(readFileSync2(join2(dir, name)), entries2);
68856
+ }
68857
+ for (const name of files) {
68858
+ const match = /^(\d+)\.log$/.exec(name);
68859
+ if (!match) continue;
68860
+ const number4 = Number(match[1]);
68861
+ if (number4 < manifest.logNumber && number4 !== manifest.prevLogNumber) continue;
68862
+ for (const batch of readLogRecords(readFileSync2(join2(dir, name)))) applyBatch(entries2, batch);
68863
+ }
68864
+ const out = /* @__PURE__ */ new Map();
68865
+ for (const [key, entry] of entries2) if (!entry.deleted) out.set(key, entry.value);
68866
+ return out;
68867
+ }
68868
+ function writeLevelDb(dir, data) {
68869
+ rmSync(dir, { recursive: true, force: true });
68870
+ mkdirSync2(dir, { recursive: true });
68871
+ const batches = [];
68872
+ let sequence = 1n;
68873
+ let records = [];
68874
+ let bytes = 0;
68875
+ const flush = () => {
68876
+ if (!records.length) return;
68877
+ const head = Buffer.alloc(12);
68878
+ head.writeBigUInt64LE(sequence, 0);
68879
+ head.writeUInt32LE(records.length, 8);
68880
+ batches.push(Buffer.concat([head, ...records]));
68881
+ sequence += BigInt(records.length);
68882
+ records = [];
68883
+ bytes = 0;
68884
+ };
68885
+ for (const [key, value] of data) {
68886
+ const record2 = Buffer.concat([
68887
+ Buffer.from([TYPE_VALUE]),
68888
+ lengthPrefixed(Buffer.from(key, "latin1")),
68889
+ lengthPrefixed(value)
68890
+ ]);
68891
+ records.push(record2);
68892
+ bytes += record2.length;
68893
+ if (bytes >= BATCH_LIMIT_BYTES) flush();
68894
+ }
68895
+ flush();
68896
+ const edit = Buffer.concat([
68897
+ varint(1),
68898
+ lengthPrefixed(Buffer.from("leveldb.BytewiseComparator", "latin1")),
68899
+ varint(2),
68900
+ varint(3),
68901
+ varint(3),
68902
+ varint(4),
68903
+ varint(4),
68904
+ varint(0)
68905
+ ]);
68906
+ writeFileSync(join2(dir, "000003.log"), writeLogRecords(batches));
68907
+ writeFileSync(join2(dir, "MANIFEST-000002"), writeLogRecords([edit]));
68908
+ writeFileSync(join2(dir, "CURRENT"), "MANIFEST-000002\n");
68682
68909
  }
68683
68910
 
68684
- // ../protocol/src/wire.ts
68685
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68686
- import { randomUUID } from "node:crypto";
68687
- var MAX_FRAME_BYTES = 256 * 1024;
68688
- var REPLY_BUDGET = MAX_FRAME_BYTES - 4096;
68689
- var textEncoder = new TextEncoder();
68690
- function byteLength(text) {
68691
- return textEncoder.encode(text).length;
68911
+ // src/browser/profile-merge.ts
68912
+ var BASELINE_FILE = "ac-fork-baseline.json";
68913
+ var CHROME_EPOCH_OFFSET_US = 11644473600000000n;
68914
+ var SNAPSHOT_TRIES = 6;
68915
+ var SNAPSHOT_RETRY_MS = 300;
68916
+ function cookiesPath(profile) {
68917
+ const network = join3(profile, "Default", "Network", "Cookies");
68918
+ return existsSync2(network) ? network : join3(profile, "Default", "Cookies");
68692
68919
  }
68693
- function extractControlExt(json5) {
68694
- if (typeof json5 !== "object" || json5 === null) return void 0;
68695
- const o = json5;
68696
- const ext = {};
68697
- if (typeof o.epoch === "number") ext.epoch = o.epoch;
68698
- if (typeof o.agentId === "string") ext.agentId = o.agentId;
68699
- if (typeof o.launchId === "string") ext.launchId = o.launchId;
68700
- return Object.keys(ext).length > 0 ? ext : void 0;
68920
+ var sqlite;
68921
+ function openDb(path) {
68922
+ if (!sqlite) {
68923
+ const emit = process.emitWarning;
68924
+ process.emitWarning = ((warning, ...rest) => {
68925
+ if (!String(warning).includes("SQLite")) emit.call(process, warning, ...rest);
68926
+ });
68927
+ try {
68928
+ sqlite = process.getBuiltinModule("node:sqlite");
68929
+ } finally {
68930
+ process.emitWarning = emit;
68931
+ }
68932
+ }
68933
+ return new sqlite.DatabaseSync(path);
68701
68934
  }
68702
- function decodeEnvelopeWith(schemas, text, opts = {}) {
68703
- if (byteLength(text) > (opts.maxBytes ?? MAX_FRAME_BYTES)) {
68704
- return { ok: false, id: NIL_UUID, msg: "FRAME_TOO_LARGE" };
68935
+ var localStoragePath = (profile) => join3(profile, "Default", "Local Storage", "leveldb");
68936
+ var indexedDbPath = (profile) => join3(profile, "Default", "IndexedDB");
68937
+ async function forkMerge(target, sources, options = {}) {
68938
+ const now = options.now ?? Date.now;
68939
+ const sleep3 = options.sleep ?? ((ms) => new Promise((resolve5) => setTimeout(resolve5, ms)));
68940
+ const baselinePath = join3(target, BASELINE_FILE);
68941
+ const baselines = loadBaselines(baselinePath);
68942
+ const reports = [];
68943
+ for (const source of sources) {
68944
+ const key = realpathSync(source);
68945
+ const previous = baselines.sources[key];
68946
+ const work = mkdtempSync(join3(tmpdir(), "ac-fork-"));
68947
+ try {
68948
+ const snapshot = await takeSnapshot(source, work, sleep3);
68949
+ const next = { cookies: {}, localStorage: {}, indexedDb: {} };
68950
+ const report = {
68951
+ source,
68952
+ firstFork: previous === void 0,
68953
+ cookies: { inserted: 0, updated: 0, kept: 0, expired: 0, deleted: 0 },
68954
+ localStorage: { taken: [], kept: 0 },
68955
+ indexedDb: { taken: [], kept: 0 }
68956
+ };
68957
+ if (snapshot.cookies) {
68958
+ mergeCookies(snapshot.cookies, cookiesPath(target), previous?.cookies, next.cookies, report.cookies, now);
68959
+ }
68960
+ mergeLocalStorage(
68961
+ snapshot.localStorage,
68962
+ localStoragePath(target),
68963
+ previous?.localStorage,
68964
+ next.localStorage,
68965
+ report.localStorage
68966
+ );
68967
+ if (snapshot.indexedDb) {
68968
+ mergeIndexedDb(snapshot.indexedDb, indexedDbPath(target), previous?.indexedDb, next.indexedDb, report.indexedDb);
68969
+ }
68970
+ baselines.sources[key] = next;
68971
+ reports.push(report);
68972
+ } finally {
68973
+ rmSync2(work, { recursive: true, force: true });
68974
+ }
68705
68975
  }
68706
- let json5;
68976
+ writeFileSync2(baselinePath, JSON.stringify(baselines));
68977
+ return reports;
68978
+ }
68979
+ function loadBaselines(path) {
68707
68980
  try {
68708
- json5 = JSON.parse(text);
68981
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
68982
+ if (parsed.version === 1 && parsed.sources && typeof parsed.sources === "object") return parsed;
68709
68983
  } catch {
68710
- return { ok: false, id: NIL_UUID, msg: "invalid json" };
68711
68984
  }
68712
- const env = Envelope.safeParse(json5);
68713
- if (!env.success) {
68714
- const id = typeof json5 === "object" && json5 !== null && typeof json5.id === "string" ? json5.id : NIL_UUID;
68715
- return { ok: false, id, msg: env.error.message };
68985
+ return { version: 1, sources: {} };
68986
+ }
68987
+ async function takeSnapshot(source, work, sleep3) {
68988
+ const snapshot = { localStorage: /* @__PURE__ */ new Map() };
68989
+ const cookies = cookiesPath(source);
68990
+ if (existsSync2(cookies)) {
68991
+ snapshot.cookies = join3(work, "Cookies");
68992
+ cpSync(cookies, snapshot.cookies);
68993
+ for (const suffix of ["-journal", "-wal"]) {
68994
+ if (existsSync2(cookies + suffix)) cpSync(cookies + suffix, snapshot.cookies + suffix);
68995
+ }
68716
68996
  }
68717
- const schema = Object.hasOwn(schemas, env.data.type) ? schemas[env.data.type] : void 0;
68718
- if (!schema) {
68719
- return {
68720
- ok: false,
68721
- id: env.data.id,
68722
- msg: "UNKNOWN_FRAME",
68723
- ...env.data.corr ? { corr: env.data.corr } : {}
68724
- };
68997
+ const localStorage2 = localStoragePath(source);
68998
+ if (existsSync2(localStorage2)) {
68999
+ snapshot.localStorage = await retried(sleep3, () => {
69000
+ const copy = join3(work, "ls");
69001
+ rmSync2(copy, { recursive: true, force: true });
69002
+ cpSync(localStorage2, copy, { recursive: true, filter: (path) => basename(path) !== "LOCK" });
69003
+ return readLevelDb(copy);
69004
+ });
68725
69005
  }
68726
- const payload = schema.safeParse(env.data.payload);
68727
- if (!payload.success) {
68728
- return {
68729
- ok: false,
68730
- id: env.data.id,
68731
- msg: payload.error.message,
68732
- ...env.data.corr ? { corr: env.data.corr } : {}
68733
- };
69006
+ const indexedDb = indexedDbPath(source);
69007
+ if (existsSync2(indexedDb)) {
69008
+ snapshot.indexedDb = join3(work, "idb");
69009
+ await retried(sleep3, () => {
69010
+ rmSync2(snapshot.indexedDb, { recursive: true, force: true });
69011
+ cpSync(indexedDb, snapshot.indexedDb, {
69012
+ recursive: true,
69013
+ preserveTimestamps: true,
69014
+ filter: (path) => basename(path) !== "LOCK"
69015
+ });
69016
+ });
68734
69017
  }
68735
- const ext = extractControlExt(json5);
68736
- return {
68737
- ok: true,
68738
- frame: { ...env.data, payload: payload.data },
68739
- ...ext ? { ext } : {}
68740
- };
68741
- }
68742
- function buildEnvelopeRaw(type, payload, opts = {}) {
68743
- return {
68744
- v: 1,
68745
- id: opts.id ?? randomUUID(),
68746
- ts: opts.ts ?? (/* @__PURE__ */ new Date()).toISOString(),
68747
- type,
68748
- payload,
68749
- ...opts.corr ? { corr: opts.corr } : {},
68750
- ...opts.orgId ? { orgId: opts.orgId } : {},
68751
- ...opts.ext ?? {}
68752
- };
69018
+ return snapshot;
68753
69019
  }
68754
-
68755
- // ../protocol/src/frames/error.ts
68756
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68757
- var ErrorCode = external_exports.enum([
68758
- // protocol / framing
68759
- "UNKNOWN_FRAME",
68760
- "FRAME_TOO_LARGE",
68761
- "PROTOCOL_STATE",
68762
- "BAD_PAYLOAD",
68763
- // auth / identity
68764
- "AUTH_FAILED",
68765
- "ATTESTATION_INVALID",
68766
- // fencing / ordering
68767
- "STALE_EPOCH",
68768
- "STALE_LAUNCH",
68769
- // delivery
68770
- "NO_SESSION",
68771
- "SCOPE_DENIED",
68772
- // delegated MCP authority / invocation binding
68773
- "DELEGATION_DENIED",
68774
- "INVOCATION_CONFLICT",
68775
- // secrets
68776
- "LEASE_EXPIRED",
68777
- "LEASE_DENIED",
68778
- // generic
68779
- "RATE_LIMITED",
68780
- "CONFLICT",
68781
- "INTERNAL"
68782
- ]);
68783
- var ErrorFrame = external_exports.object({
68784
- code: ErrorCode,
68785
- message: external_exports.string(),
68786
- // human-readable, redacted of secrets
68787
- retryable: external_exports.boolean(),
68788
- details: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
68789
- });
68790
-
68791
- // ../protocol/src/frames/computer-lease.ts
68792
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68793
- var COMPUTER_LEASE_AGENT_NAME_MAX = 200;
68794
- var ComputerLeaseHolder = external_exports.object({
68795
- sessionId: external_exports.string().min(1).max(256),
68796
- agentId: external_exports.string().uuid(),
68797
- agentName: external_exports.string().min(1).max(COMPUTER_LEASE_AGENT_NAME_MAX).optional()
68798
- });
68799
- var computerLeaseHolderName = (holder) => `${holder.agentId}/${holder.sessionId}`;
68800
- var ComputerControlLease = external_exports.object({
68801
- leaseId: external_exports.string().uuid(),
68802
- computerId: external_exports.string().uuid(),
68803
- holder: ComputerLeaseHolder,
68804
- acquiredAt: external_exports.string().datetime(),
68805
- expiresAt: external_exports.string().datetime()
68806
- });
68807
- var COMPUTER_LEASE_REFUSALS = ["computer_busy", "human_in_control", "unavailable", "denied"];
68808
- var COMPUTER_LEASE_POLL_MAX_MS = 1e4;
68809
- var COMPUTER_LEASE_WAIT_MAX_SECONDS = 600;
68810
- var ComputerLeaseAcquire = external_exports.object({
68811
- computerId: external_exports.string().uuid(),
68812
- agentId: external_exports.string().uuid(),
68813
- sessionId: external_exports.string().min(1).max(256),
68814
- // The daemon-clock time of the request, compared with the `event/session` turn end on the same clock.
68815
- requestedAt: external_exports.string().datetime(),
68816
- // Behind COMPUTER_LEASE_QUEUE_FEATURE: wait in the Computer's FIFO queue, holding the reply up to this long.
68817
- waitMs: external_exports.number().int().min(0).max(COMPUTER_LEASE_POLL_MAX_MS).optional()
68818
- });
68819
- var ComputerLeaseQueued = external_exports.object({
68820
- position: external_exports.number().int().min(1),
68821
- waitedMs: external_exports.number().int().min(0),
68822
- // Time left before the wait ends in `computer_busy`.
68823
- leftMs: external_exports.number().int().min(0)
68824
- });
68825
- var ComputerLeaseAcquireResult = external_exports.discriminatedUnion("granted", [
68826
- external_exports.object({ granted: external_exports.literal(true), lease: ComputerControlLease }),
68827
- external_exports.object({
68828
- granted: external_exports.literal(false),
68829
- code: external_exports.enum(COMPUTER_LEASE_REFUSALS),
68830
- message: external_exports.string().max(500),
68831
- holder: ComputerLeaseHolder.optional(),
68832
- queued: ComputerLeaseQueued.optional()
68833
- })
68834
- ]);
68835
- var ComputerLeaseRelease = external_exports.object({
68836
- computerId: external_exports.string().uuid(),
68837
- agentId: external_exports.string().uuid(),
68838
- sessionId: external_exports.string().min(1).max(256)
68839
- });
68840
-
68841
- // ../protocol/src/frames/computer-channel.ts
68842
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68843
-
68844
- // ../protocol/src/computer-channel-token.ts
68845
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68846
- import { createHmac, timingSafeEqual } from "node:crypto";
68847
-
68848
- // ../protocol/src/computer-viewer.ts
68849
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68850
- var COMPUTER_VIEWER_API_PREFIX = "/view/api/";
68851
- var COMPUTER_VIEWER_MAX_REQUEST_BYTES = 64 * 1024;
68852
- var COMPUTER_VIEWER_TRANSPORTS = ["direct", "stun", "turn"];
68853
- var ComputerIceServer = external_exports.object({
68854
- urls: external_exports.array(
68855
- external_exports.string().regex(/^turns?:/).max(256)
68856
- ).min(1).max(4),
68857
- username: external_exports.string().min(1).max(256),
68858
- credential: external_exports.string().min(1).max(256)
68859
- }).strict();
68860
- var COMPUTER_ICE_SERVERS_MAX = 2;
68861
- var ComputerStunUrl = external_exports.string().max(256).regex(/^stun:(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+)(:\d{1,5})?$/, "expected stun:<host>[:<port>]");
68862
- var ComputerTurnUrl = external_exports.string().max(256).regex(
68863
- /^turns?:(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+)(:\d{1,5})?(\?transport=(udp|tcp))?$/,
68864
- "expected turn:<host>[:<port>][?transport=udp|tcp] or turns:"
68865
- );
68866
- var COMPUTER_STUN_URLS_MAX = 2;
68867
- var ComputerViewerCandidate = external_exports.object({
68868
- id: external_exports.string().min(1).max(64),
68869
- candidate: external_exports.object({
68870
- candidate: external_exports.string().max(1024),
68871
- sdpMid: external_exports.string().max(64).nullish(),
68872
- sdpMLineIndex: external_exports.number().int().min(0).max(64).nullish()
68873
- }).nullable()
68874
- });
68875
- var ComputerViewerCandidatesRequest = external_exports.object({
68876
- id: external_exports.string().min(1).max(64),
68877
- after: external_exports.number().int().min(0).max(1e3).default(0)
68878
- });
68879
- var ComputerViewerOfferRequest = external_exports.object({ transport: external_exports.enum(COMPUTER_VIEWER_TRANSPORTS).optional() });
68880
- var ComputerViewerRenewal = external_exports.object({ type: external_exports.literal("auth"), token: external_exports.string().min(1).max(4096) });
68881
-
68882
- // ../protocol/src/computer-command-line.ts
68883
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
68884
- var COMPUTER_SHELL_MODES = ["off", "ask", "on"];
68885
- var COMPUTER_FILES_MODES = ["off", "read", "read-write"];
68886
- var COMPUTER_FILE_ROOTS_MAX = 32;
68887
- var ComputerFileRoot = external_exports.string().trim().min(1).max(1024).refine((p) => /^(\/|~(\/|$)|[A-Za-z]:[\\/])/.test(p) && !p.includes("\0"), "expected an absolute path");
68888
- var COMPUTER_EXEC_TIMEOUT_DEFAULT_MS = 3e4;
68889
- var COMPUTER_EXEC_TIMEOUT_MAX_MS = 9e4;
68890
- var COMPUTER_EXEC_COMMAND_MAX_CHARS = 16384;
68891
- var COMPUTER_EXEC_OUTPUT_TAIL_BYTES = 32 * 1024;
68892
- var COMPUTER_EXEC_PER_SESSION_MAX = 4;
68893
- var COMPUTER_EXEC_TOTAL_MAX = 8;
68894
- var COMPUTER_READ_TEXT_MAX_BYTES = 256 * 1024;
68895
- var COMPUTER_READ_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
68896
- var COMPUTER_WRITE_MAX_BYTES = 1024 * 1024;
68897
- var COMPUTER_LIST_DIR_MAX = 1e3;
68898
- var SHELL_RANK = { off: 0, ask: 1, on: 2 };
68899
- var FILES_RANK = { off: 0, read: 1, "read-write": 2 };
68900
- var narrowerShell = (a, b) => SHELL_RANK[a] <= SHELL_RANK[b] ? a : b;
68901
- var narrowerFiles = (a, b) => FILES_RANK[a] <= FILES_RANK[b] ? a : b;
68902
-
68903
- // ../protocol/src/computer-channel-token.ts
68904
- var COMPUTER_CHANNEL_TOKEN_PREFIX = "actk1";
68905
- var COMPUTER_CHANNEL_TOKEN_AUDIENCES = ["mcp", "relay", "view"];
68906
- var COMPUTER_CHANNEL_TOKEN_MAX_TTL_MS = 5 * 6e4;
68907
- var COMPUTER_AGENT_MODES = ["view", "control"];
68908
- var ComputerChannelTokenClaims = external_exports.object({
68909
- aud: external_exports.enum(COMPUTER_CHANNEL_TOKEN_AUDIENCES),
68910
- // The Computer the token is for, and the id of the channel key that signed it.
68911
- cmp: external_exports.string().uuid(),
68912
- kid: external_exports.string().min(1).max(64),
68913
- // Issue and expiry times, epoch milliseconds on the issuer's clock.
68914
- iat: external_exports.number().int().nonnegative(),
68915
- exp: external_exports.number().int().positive(),
68916
- // `mcp` only: the agent session the calls belong to, its agent and daemon, and what the policy lets it do.
68917
- ses: external_exports.string().min(1).max(256).optional(),
68918
- agt: external_exports.string().uuid().optional(),
68919
- dmn: external_exports.string().uuid().optional(),
68920
- mode: external_exports.enum(COMPUTER_AGENT_MODES).optional(),
68921
- // `mcp` only: the command-line tier the policy allows (§5.7); absent, as from an older CP, means none.
68922
- sh: external_exports.enum(COMPUTER_SHELL_MODES).optional(),
68923
- fs: external_exports.enum(COMPUTER_FILES_MODES).optional(),
68924
- // `view` only: the member watching, the TURN servers the desktop may relay media through, and the STUN servers it may punch with.
68925
- usr: external_exports.string().min(1).max(128).optional(),
68926
- ice: external_exports.array(ComputerIceServer).max(COMPUTER_ICE_SERVERS_MAX).optional(),
68927
- stun: external_exports.array(ComputerStunUrl).max(COMPUTER_STUN_URLS_MAX).optional()
68928
- }).strip().refine((c) => c.aud !== "mcp" || c.ses !== void 0 && c.agt !== void 0 && c.mode !== void 0, {
68929
- message: "an mcp token names its session, agent and mode"
68930
- }).refine((c) => c.aud !== "view" || c.usr !== void 0 && c.mode !== void 0, {
68931
- message: "a view token names its member and mode"
68932
- }).refine((c) => c.exp > c.iat && c.exp - c.iat <= COMPUTER_CHANNEL_TOKEN_MAX_TTL_MS, {
68933
- message: "token lifetime out of range"
68934
- });
68935
- var MAC_DOMAIN = "agentconnect/computer-channel-token/v1\n";
68936
- var MAX_TOKEN_CHARS = 4096;
68937
- function mac3(key, signed) {
68938
- return createHmac("sha256", key).update(MAC_DOMAIN + signed).digest();
69020
+ async function retried(sleep3, attempt) {
69021
+ let last;
69022
+ for (let i = 0; i < SNAPSHOT_TRIES; i++) {
69023
+ try {
69024
+ return attempt();
69025
+ } catch (error63) {
69026
+ last = error63;
69027
+ await sleep3(SNAPSHOT_RETRY_MS);
69028
+ }
69029
+ }
69030
+ throw new Error(`could not snapshot a running profile: ${last.message}`);
68939
69031
  }
68940
- function signComputerChannelToken(claims, key) {
68941
- const parsed = ComputerChannelTokenClaims.parse(claims);
68942
- const signed = `${COMPUTER_CHANNEL_TOKEN_PREFIX}.${Buffer.from(JSON.stringify(parsed)).toString("base64url")}`;
68943
- return `${signed}.${mac3(key, signed).toString("base64url")}`;
69032
+ var scalar = (value) => typeof value === "bigint" ? value.toString() : value;
69033
+ var bindable = (value) => value instanceof Uint8Array ? Buffer.from(value) : value;
69034
+ function uniqueKey(db) {
69035
+ for (const index of db.prepare("PRAGMA index_list(cookies)").all()) {
69036
+ if (Number(index.unique) !== 1) continue;
69037
+ const name = String(index.name).replaceAll("'", "''");
69038
+ return db.prepare(`PRAGMA index_info('${name}')`).all().map((column) => String(column.name));
69039
+ }
69040
+ throw new Error("the cookies table has no unique index");
68944
69041
  }
68945
- function readComputerChannelToken(token) {
68946
- if (token.length > MAX_TOKEN_CHARS) return null;
68947
- const parts = token.split(".");
68948
- if (parts.length !== 3 || parts[0] !== COMPUTER_CHANNEL_TOKEN_PREFIX) return null;
69042
+ function mergeCookies(snapshot, target, previous, next, counts, now) {
69043
+ if (!existsSync2(target)) cpSync(snapshot, target);
69044
+ const source = openDb(snapshot);
69045
+ const db = openDb(target);
68949
69046
  try {
68950
- const parsed = ComputerChannelTokenClaims.safeParse(JSON.parse(Buffer.from(parts[1], "base64url").toString()));
68951
- return parsed.success ? parsed.data : null;
68952
- } catch {
68953
- return null;
69047
+ const columns = db.prepare("PRAGMA table_info(cookies)").all().map((column) => String(column.name));
69048
+ const sourceColumns = source.prepare("PRAGMA table_info(cookies)").all().map(
69049
+ (column) => String(column.name)
69050
+ );
69051
+ if (columns.join() !== sourceColumns.join()) throw new Error("the cookie databases have different schemas");
69052
+ const key = uniqueKey(db);
69053
+ const stamp = columns.includes("last_update_utc") ? "last_update_utc" : "creation_utc";
69054
+ const keyOf2 = (row) => JSON.stringify(key.map((column) => scalar(row[column])));
69055
+ const list2 = (database, sql) => {
69056
+ const statement = database.prepare(sql);
69057
+ statement.setReadBigInts(true);
69058
+ return statement.all();
69059
+ };
69060
+ const quoted = columns.map((column) => `"${column}"`).join(",");
69061
+ const mine = /* @__PURE__ */ new Map();
69062
+ for (const row of list2(db, `SELECT rowid AS ac_rowid, ${quoted} FROM cookies`)) {
69063
+ mine.set(keyOf2(row), { rowid: row.ac_rowid, stamp: row[stamp] });
69064
+ }
69065
+ const insert = db.prepare(`INSERT OR REPLACE INTO cookies (${quoted}) VALUES (${columns.map(() => "?").join(",")})`);
69066
+ const remove = db.prepare("DELETE FROM cookies WHERE rowid = ?");
69067
+ const nowUs = BigInt(now()) * 1000n + CHROME_EPOCH_OFFSET_US;
69068
+ db.exec("BEGIN");
69069
+ try {
69070
+ for (const row of list2(source, `SELECT ${quoted} FROM cookies`)) {
69071
+ const id = keyOf2(row);
69072
+ const updated = row[stamp];
69073
+ next[id] = updated.toString();
69074
+ const expires = row.expires_utc;
69075
+ if (Number(row.is_persistent) === 1 && expires > 0n && expires < nowUs) {
69076
+ counts.expired++;
69077
+ continue;
69078
+ }
69079
+ const current = mine.get(id);
69080
+ const changed = previous === void 0 || previous[id] !== updated.toString();
69081
+ if (!changed || current?.stamp === updated) {
69082
+ counts.kept++;
69083
+ continue;
69084
+ }
69085
+ insert.run(...columns.map((column) => bindable(row[column])));
69086
+ counts[current ? "updated" : "inserted"]++;
69087
+ }
69088
+ if (previous) {
69089
+ for (const id of Object.keys(previous)) {
69090
+ if (id in next) continue;
69091
+ const current = mine.get(id);
69092
+ if (current) {
69093
+ remove.run(current.rowid);
69094
+ counts.deleted++;
69095
+ }
69096
+ }
69097
+ }
69098
+ db.exec("COMMIT");
69099
+ } catch (error63) {
69100
+ db.exec("ROLLBACK");
69101
+ throw error63;
69102
+ }
69103
+ } finally {
69104
+ source.close();
69105
+ db.close();
68954
69106
  }
68955
69107
  }
68956
- function verifyComputerChannelToken(token, opts) {
68957
- const claims = readComputerChannelToken(token);
68958
- if (!claims || claims.aud !== opts.aud || claims.cmp !== opts.computerId) return null;
68959
- if (!(claims.exp > opts.now)) return null;
68960
- const key = opts.key(claims.kid);
68961
- if (!key) return null;
68962
- const at = token.lastIndexOf(".");
68963
- const presented = Buffer.from(token.slice(at + 1), "base64url");
68964
- const expected = mac3(key, token.slice(0, at));
68965
- if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) return null;
68966
- return claims;
69108
+ function lastModified(meta3) {
69109
+ let pos = 0;
69110
+ while (pos < meta3.length) {
69111
+ const tag = meta3[pos++];
69112
+ let value = 0n;
69113
+ let shift = 0n;
69114
+ for (; ; ) {
69115
+ const byte = meta3[pos++];
69116
+ if (byte === void 0) return value.toString();
69117
+ value |= BigInt(byte & 127) << shift;
69118
+ shift += 7n;
69119
+ if (!(byte & 128)) break;
69120
+ }
69121
+ if (tag === 8) return value.toString();
69122
+ }
69123
+ return "0";
68967
69124
  }
68968
-
68969
- // ../protocol/src/frames/computer-channel.ts
68970
- var ComputerRelayEntry = external_exports.object({
68971
- relayId: external_exports.string().uuid(),
68972
- url: external_exports.string().min(1).max(2048)
68973
- });
68974
- var COMPUTER_RELAYS_MAX = 64;
68975
- var COMPUTER_ADMIN_PROMPT_MODES = ["agent", "people", "approve", "deny"];
68976
- var DEFAULT_COMPUTER_ADMIN_PROMPT_MODE = "people";
68977
- var ComputerApprovalsSchema = external_exports.object({
68978
- // Ask before a session's first click, drag, type, key or launch; an allow covers the rest of the session.
68979
- firstInputPerSession: external_exports.boolean().default(true),
68980
- // Windows only; absent means the default, so policies stored before it keep their meaning.
68981
- adminPrompts: external_exports.enum(COMPUTER_ADMIN_PROMPT_MODES).optional()
68982
- });
68983
- var ComputerGrantApprovalsSchema = ComputerApprovalsSchema.extend({
68984
- launchApp: external_exports.enum(["always", "session", "never-ask"]).optional(),
68985
- submitLikeKeys: external_exports.boolean().optional()
68986
- });
68987
- var COMPUTER_CHANNEL_REFUSALS = ["denied", "unavailable"];
68988
- var ComputerChannelGrantRequest = external_exports.object({
68989
- computerId: external_exports.string().uuid(),
68990
- agentId: external_exports.string().uuid(),
68991
- sessionId: external_exports.string().min(1).max(256)
68992
- });
68993
- var ComputerChannelGrantResult = external_exports.discriminatedUnion("granted", [
68994
- external_exports.object({
68995
- granted: external_exports.literal(true),
68996
- token: external_exports.string().min(1).max(2048),
68997
- expiresAt: external_exports.string().datetime(),
68998
- mode: external_exports.enum(COMPUTER_AGENT_MODES),
68999
- relays: external_exports.array(ComputerRelayEntry).max(COMPUTER_RELAYS_MAX),
69000
- // What the approval cards name and whom they also reach (§4.2); an older CP sends none, and every approval is asked.
69001
- name: external_exports.string().min(1).max(200).optional(),
69002
- ownerUserId: external_exports.string().min(1).max(128).optional(),
69003
- approvals: ComputerGrantApprovalsSchema.optional(),
69004
- // The console users who may answer its approvals: the Computer's allowed members; an older CP sends none.
69005
- approvers: external_exports.array(external_exports.string().min(1).max(128)).max(500).optional(),
69006
- // The command-line tier the token allows (§5.7); an older CP sends none, which allows none.
69007
- shell: external_exports.enum(COMPUTER_SHELL_MODES).optional(),
69008
- files: external_exports.enum(COMPUTER_FILES_MODES).optional()
69009
- }),
69010
- external_exports.object({
69011
- granted: external_exports.literal(false),
69012
- code: external_exports.enum(COMPUTER_CHANNEL_REFUSALS),
69013
- message: external_exports.string().max(500)
69014
- })
69015
- ]);
69016
-
69017
- // ../protocol/src/frames/computer-audit.ts
69018
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
69019
- var COMPUTER_AUDIT_FEATURE = "computer-audit-v1";
69020
- var COMPUTER_APPROVAL_META_KEY = "md.agentconnect/approval";
69021
- var COMPUTER_APPROVAL_RESULTS = ["not_required", "allowed", "allowed_session"];
69022
- var COMPUTER_AUDIT_BATCH_MAX = 100;
69023
- var COMPUTER_AUDIT_BATCH_BYTES = REPLY_BUDGET;
69024
- var COMPUTER_AUDIT_ARGS_MAX_CHARS = 2048;
69025
- var AUDIT_STRING_MAX = 256;
69026
- var AUDIT_COMMAND_MAX = 1536;
69027
- var AUDIT_DEPTH_MAX = 6;
69028
- var TEXT_KEYS = /* @__PURE__ */ new Set(["text", "value", "content"]);
69029
- var CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
69030
- var LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
69031
- function computerAuditText(value) {
69032
- return value.replace(CONTROL_CHARS, "").replace(LONE_SURROGATE, "\uFFFD");
69125
+ function mergeLocalStorage(source, target, previous, next, report) {
69126
+ const merged = readLevelDb(target);
69127
+ let changed = false;
69128
+ if (!merged.has("VERSION") && source.has("VERSION")) {
69129
+ merged.set("VERSION", source.get("VERSION"));
69130
+ changed = true;
69131
+ }
69132
+ for (const [key, meta3] of source) {
69133
+ if (!key.startsWith("META:")) continue;
69134
+ const origin = key.slice("META:".length);
69135
+ const modified = lastModified(meta3);
69136
+ next[origin] = modified;
69137
+ const mine = merged.get(key);
69138
+ if (previous !== void 0 && previous[origin] === modified || mine && mine.equals(meta3)) {
69139
+ report.kept++;
69140
+ continue;
69141
+ }
69142
+ const prefix = `_${origin}\0`;
69143
+ for (const existing of [...merged.keys()]) if (existing.startsWith(prefix)) merged.delete(existing);
69144
+ for (const [entry, value] of source) if (entry.startsWith(prefix)) merged.set(entry, value);
69145
+ merged.set(key, meta3);
69146
+ const access = source.get(`METAACCESS:${origin}`);
69147
+ if (access) merged.set(`METAACCESS:${origin}`, access);
69148
+ report.taken.push(origin);
69149
+ changed = true;
69150
+ }
69151
+ if (changed) writeLevelDb(target, merged);
69033
69152
  }
69034
- function auditValue(value, depth) {
69035
- if (typeof value === "string") return computerAuditText(value.slice(0, AUDIT_STRING_MAX));
69036
- if (value === null || typeof value !== "object") return value;
69037
- if (depth >= AUDIT_DEPTH_MAX) return "[nested]";
69038
- if (Array.isArray(value)) return value.map((item) => auditValue(item, depth + 1));
69039
- const out = {};
69040
- for (const [key, item] of Object.entries(value))
69041
- out[computerAuditText(key.slice(0, 64))] = auditValue(item, depth + 1);
69042
- return out;
69153
+ function newestMtime(dir) {
69154
+ let newest = 0;
69155
+ for (const entry of readdirSync2(dir, { withFileTypes: true, recursive: true })) {
69156
+ if (entry.isFile()) newest = Math.max(newest, statSync(join3(entry.parentPath, entry.name)).mtimeMs);
69157
+ }
69158
+ return newest;
69043
69159
  }
69044
- function computerAuditArgs(args) {
69045
- let textLength;
69046
- const out = {};
69047
- for (const [key, value] of Object.entries(args)) {
69048
- if (TEXT_KEYS.has(key) && typeof value === "string") {
69049
- textLength = (textLength ?? 0) + [...value].length;
69160
+ function mergeIndexedDb(snapshot, target, previous, next, report) {
69161
+ for (const name of readdirSync2(snapshot)) {
69162
+ if (!name.endsWith(".indexeddb.leveldb")) continue;
69163
+ const origin = name.slice(0, -".indexeddb.leveldb".length);
69164
+ const modified = newestMtime(join3(snapshot, name));
69165
+ next[origin] = modified;
69166
+ const mine = join3(target, name);
69167
+ if (previous !== void 0 && previous[origin] === modified || existsSync2(mine) && newestMtime(mine) === modified) {
69168
+ report.kept++;
69050
69169
  continue;
69051
69170
  }
69052
- out[computerAuditText(key.slice(0, 64))] = key === "command" && typeof value === "string" ? computerAuditText(value.slice(0, AUDIT_COMMAND_MAX)) : auditValue(value, 1);
69171
+ for (const suffix of [".indexeddb.leveldb", ".indexeddb.blob"]) {
69172
+ const to = join3(target, origin + suffix);
69173
+ rmSync2(to, { recursive: true, force: true });
69174
+ const from = join3(snapshot, origin + suffix);
69175
+ if (existsSync2(from)) cpSync(from, to, { recursive: true, preserveTimestamps: true });
69176
+ }
69177
+ report.taken.push(origin);
69053
69178
  }
69054
- const bounded = JSON.stringify(out).length <= COMPUTER_AUDIT_ARGS_MAX_CHARS ? out : { truncated: true };
69055
- return { args: bounded, ...textLength !== void 0 ? { textLength } : {} };
69056
69179
  }
69057
- var ComputerAuditEntry = external_exports.object({
69058
- // Idempotency: a batch resent after a lost ack does not duplicate rows.
69059
- id: external_exports.string().uuid(),
69060
- at: external_exports.string().datetime(),
69061
- tool: external_exports.string().min(1).max(128),
69062
- // The lease holder name: `agentId/sessionId` for an agent session, else a local client or viewer name.
69063
- client: external_exports.string().min(1).max(512),
69064
- agentId: external_exports.string().uuid().optional(),
69065
- sessionId: external_exports.string().min(1).max(256).optional(),
69066
- outcome: external_exports.enum(["ok", "error"]),
69067
- code: external_exports.string().min(1).max(64).optional(),
69068
- approval: external_exports.enum(COMPUTER_APPROVAL_RESULTS).optional(),
69069
- args: external_exports.record(external_exports.string().max(64), external_exports.unknown()).refine((args) => JSON.stringify(args).length <= COMPUTER_AUDIT_ARGS_MAX_CHARS, "audit args too large").optional(),
69070
- textLength: external_exports.number().int().min(0).max(1e6).optional(),
69071
- ms: external_exports.number().int().min(0),
69072
- // The stored screenshot this call returned (§9), as `sha256:<hex>`.
69073
- screenshotRef: external_exports.string().min(1).max(1024).optional()
69074
- }).strict();
69075
- var ComputerAuditReport = external_exports.object({
69076
- entries: external_exports.array(ComputerAuditEntry).min(1).max(COMPUTER_AUDIT_BATCH_MAX)
69077
- });
69078
- var ComputerAuditAck = external_exports.object({ stored: external_exports.number().int().min(0) });
69079
69180
 
69080
- // ../protocol/src/frames/computer-screenshot.ts
69081
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
69082
- var COMPUTER_SCREENSHOT_FEATURE = "computer-screenshot-v1";
69083
- var COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS = 3650;
69084
- var COMPUTER_SCREENSHOT_MAX_BYTES = 32 * 1024 * 1024;
69085
- var COMPUTER_SCREENSHOT_CONTENT_TYPES = ["image/png", "image/jpeg", "image/webp"];
69086
- var REF_PREFIX = "sha256:";
69087
- var SHA256_HEX_RE = /^[0-9a-f]{64}$/;
69088
- var ComputerScreenshotSha256 = external_exports.string().regex(SHA256_HEX_RE, "expected a lower-case hex SHA-256");
69089
- function computerScreenshotRef(sha2563) {
69090
- return `${REF_PREFIX}${sha2563}`;
69181
+ // src/browser/launcher.ts
69182
+ var BROWSER_NAMES = ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"];
69183
+ var BASE_FLAGS = ["--no-first-run", "--no-default-browser-check", "--hide-crash-restore-bubble"];
69184
+ var LOCK_STALE_MS = 6e4;
69185
+ var LOCK_WAIT_MS = 3e4;
69186
+ var OWN_WAIT_MS = 2e4;
69187
+ function profileOwner(profile, host = hostname4()) {
69188
+ let target;
69189
+ try {
69190
+ target = readlinkSync(join4(profile, "SingletonLock"));
69191
+ } catch {
69192
+ return void 0;
69193
+ }
69194
+ const match = /^(.*)-(\d+)$/.exec(target);
69195
+ if (!match || match[1] !== host) return void 0;
69196
+ const pid = Number(match[2]);
69197
+ try {
69198
+ process.kill(pid, 0);
69199
+ return pid;
69200
+ } catch (error63) {
69201
+ return error63.code === "EPERM" ? pid : void 0;
69202
+ }
69091
69203
  }
69092
- var ComputerScreenshotPut = external_exports.object({
69093
- sessionId: external_exports.string().min(1).max(256),
69094
- agentId: external_exports.string().uuid(),
69095
- sha256: ComputerScreenshotSha256,
69096
- bytes: external_exports.number().int().positive().max(COMPUTER_SCREENSHOT_MAX_BYTES),
69097
- contentType: external_exports.enum(COMPUTER_SCREENSHOT_CONTENT_TYPES),
69098
- takenAt: external_exports.string().datetime()
69099
- }).strict();
69100
- var ComputerScreenshotPutOk = external_exports.object({
69101
- status: external_exports.enum(["upload", "stored", "skipped"]),
69102
- url: external_exports.string().url().optional(),
69103
- headers: external_exports.record(external_exports.string(), external_exports.string()).optional(),
69104
- expiresAt: external_exports.string().datetime().optional(),
69105
- reason: external_exports.string().max(200).optional()
69106
- });
69107
- var ComputerScreenshotCommit = external_exports.object({ sessionId: external_exports.string().min(1).max(256), sha256: ComputerScreenshotSha256 }).strict();
69108
- var ComputerScreenshotCommitOk = external_exports.object({ stored: external_exports.boolean() });
69109
-
69110
- // ../protocol/src/frames/relay-computer.ts
69111
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
69112
- var RELAY_COMPUTER_SUBPROTOCOL = "agentconnect.cr.v1";
69113
- var RELAY_COMPUTER_WS_PATH = "/cr/ws";
69114
- var RELAY_COMPUTER_MAX_BODY_BYTES = 8 * 1024 * 1024;
69115
- var RELAY_COMPUTER_MAX_FRAME_BYTES = 12 * 1024 * 1024;
69116
- var RELAY_DAEMON_PATH_SUFFIX = "/rd/ws";
69117
- function relayUrlAt(relayUrl, path, scheme) {
69118
- const url2 = new URL(relayUrl);
69119
- const prefix = url2.pathname.endsWith(RELAY_DAEMON_PATH_SUFFIX) ? url2.pathname.slice(0, -RELAY_DAEMON_PATH_SUFFIX.length) : url2.pathname.replace(/\/+$/, "");
69120
- for (const { from, to } of scheme) if (url2.protocol === from) url2.protocol = to;
69121
- url2.pathname = `${prefix}${path}`;
69122
- url2.search = "";
69123
- url2.hash = "";
69124
- return url2.toString();
69204
+ function seedable(path) {
69205
+ const name = basename2(path);
69206
+ return !(name.startsWith("Singleton") || /cache$/i.test(name) || name === "Crash Reports" || name === "Sessions" || name === "Session Storage" || name === BASELINE_FILE);
69125
69207
  }
69126
- function relayComputerWsUrl(relayUrl) {
69127
- return relayUrlAt(relayUrl, RELAY_COMPUTER_WS_PATH, [
69128
- { from: "http:", to: "ws:" },
69129
- { from: "https:", to: "wss:" }
69130
- ]);
69208
+ function seedProfile(master, profile) {
69209
+ mkdirSync3(dirname2(profile), { recursive: true });
69210
+ cpSync2(master, profile, { recursive: true, preserveTimestamps: true, filter: seedable });
69131
69211
  }
69132
- var Base64 = external_exports.string().regex(/^[A-Za-z0-9+/]*={0,2}$/);
69133
- var Headers2 = external_exports.record(external_exports.string().min(1).max(256), external_exports.string().max(8192));
69134
- var CrHello = external_exports.object({
69135
- computerId: external_exports.string().uuid(),
69136
- token: external_exports.string().min(1).max(2048),
69137
- desktopDaemonVersion: external_exports.string().trim().min(1).max(64)
69138
- }).strict();
69139
- var CrHelloOk = external_exports.object({ relayId: external_exports.string().min(1).max(64) });
69140
- var CrHttpRequest = external_exports.object({
69141
- method: external_exports.enum(["GET", "POST", "DELETE"]),
69142
- path: external_exports.string().min(1).max(2048),
69143
- headers: Headers2,
69144
- body: Base64.optional()
69145
- });
69146
- var CrHttpResponse = external_exports.object({
69147
- status: external_exports.number().int().min(100).max(599),
69148
- headers: Headers2,
69149
- body: Base64.optional()
69150
- });
69151
- var RELAY_COMPUTER_SCHEMAS = {
69152
- "cr/hello": CrHello,
69153
- "cr/hello/ok": CrHelloOk,
69154
- "cr/http": CrHttpRequest,
69155
- "cr/http/result": CrHttpResponse,
69156
- error: ErrorFrame
69157
- };
69158
- var RelayComputerFrame = external_exports.discriminatedUnion("type", [
69159
- frameSchema("cr/hello", RELAY_COMPUTER_SCHEMAS["cr/hello"]),
69160
- frameSchema("cr/hello/ok", RELAY_COMPUTER_SCHEMAS["cr/hello/ok"]),
69161
- frameSchema("cr/http", RELAY_COMPUTER_SCHEMAS["cr/http"]),
69162
- frameSchema("cr/http/result", RELAY_COMPUTER_SCHEMAS["cr/http/result"]),
69163
- frameSchema("error", RELAY_COMPUTER_SCHEMAS["error"])
69164
- ]);
69165
- function decodeRelayComputerFrame(text) {
69166
- return decodeEnvelopeWith(RELAY_COMPUTER_SCHEMAS, text, {
69167
- maxBytes: RELAY_COMPUTER_MAX_FRAME_BYTES
69212
+ function findBrowser(path = process.env.PATH ?? "", skip = []) {
69213
+ const skipped = new Set(skip.map((dir) => resolve(dir)));
69214
+ for (const name of BROWSER_NAMES) {
69215
+ for (const dir of path.split(delimiter)) {
69216
+ if (!dir || skipped.has(resolve(dir))) continue;
69217
+ const candidate = join4(dir, name);
69218
+ try {
69219
+ accessSync(candidate, constants.X_OK);
69220
+ if (statSync2(candidate).isFile()) return candidate;
69221
+ } catch {
69222
+ }
69223
+ }
69224
+ }
69225
+ return void 0;
69226
+ }
69227
+ async function launchBrowser(options) {
69228
+ const log40 = options.log ?? (() => void 0);
69229
+ const release3 = await lockProfile(options.profile);
69230
+ try {
69231
+ if (profileOwner(options.profile) !== void 0) {
69232
+ start(options).unref();
69233
+ return { handedOff: true, reports: [] };
69234
+ }
69235
+ if (!existsSync3(options.profile)) {
69236
+ if (options.master && existsSync3(options.master)) {
69237
+ seedProfile(options.master, options.profile);
69238
+ log40(`browser profile ${options.profile} created from ${options.master}`);
69239
+ } else mkdirSync3(options.profile, { recursive: true });
69240
+ }
69241
+ for (const name of ["SingletonLock", "SingletonCookie", "SingletonSocket"]) {
69242
+ rmSync3(join4(options.profile, name), { force: true });
69243
+ }
69244
+ const self2 = realpathSync2(options.profile);
69245
+ const sources = options.sources.filter(
69246
+ (source) => existsSync3(join4(source, "Default")) && realpathSync2(source) !== self2
69247
+ );
69248
+ const reports = await forkMerge(options.profile, sources);
69249
+ for (const report of reports) log40(`browser fork-merge from ${report.source}: ${summarize(report)}`);
69250
+ const child2 = start(options);
69251
+ if (!await owned(options.profile, child2)) log40(`browser for ${options.profile} did not take its profile`);
69252
+ return { handedOff: false, reports, ...child2.pid !== void 0 ? { pid: child2.pid } : {} };
69253
+ } finally {
69254
+ release3();
69255
+ }
69256
+ }
69257
+ function start(options) {
69258
+ const child2 = spawn2(options.browser, [`--user-data-dir=${options.profile}`, ...BASE_FLAGS, ...options.args ?? []], {
69259
+ detached: true,
69260
+ stdio: "ignore",
69261
+ env: options.env ?? process.env
69168
69262
  });
69263
+ child2.on("error", () => void 0);
69264
+ return child2;
69169
69265
  }
69170
- function buildRelayComputerFrame(type, payload, opts = {}) {
69171
- return buildEnvelopeRaw(type, payload, opts);
69266
+ async function owned(profile, child2) {
69267
+ let ended = false;
69268
+ const end = () => void (ended = true);
69269
+ child2.once("error", end).once("exit", end);
69270
+ try {
69271
+ const deadline = Date.now() + OWN_WAIT_MS;
69272
+ for (; ; ) {
69273
+ if (profileOwner(profile) !== void 0) return true;
69274
+ if (ended || Date.now() > deadline) return false;
69275
+ await new Promise((resolveWait) => setTimeout(resolveWait, 100));
69276
+ }
69277
+ } finally {
69278
+ child2.off("error", end).off("exit", end);
69279
+ child2.unref();
69280
+ }
69281
+ }
69282
+ function summarize(report) {
69283
+ const c = report.cookies;
69284
+ return [
69285
+ report.firstFork ? "first fork" : "since last fork",
69286
+ `cookies +${c.inserted} ~${c.updated} -${c.deleted} (kept ${c.kept}, expired ${c.expired})`,
69287
+ `localStorage ${report.localStorage.taken.length} origin(s)`,
69288
+ `IndexedDB ${report.indexedDb.taken.length} origin(s)`
69289
+ ].join(", ");
69290
+ }
69291
+ async function lockProfile(profile) {
69292
+ const path = `${profile}.launch-lock`;
69293
+ mkdirSync3(dirname2(path), { recursive: true });
69294
+ const deadline = Date.now() + LOCK_WAIT_MS;
69295
+ for (; ; ) {
69296
+ try {
69297
+ closeSync(openSync(path, "wx"));
69298
+ return () => rmSync3(path, { force: true });
69299
+ } catch (error63) {
69300
+ if (error63.code !== "EEXIST") throw error63;
69301
+ try {
69302
+ if (Date.now() - statSync2(path).mtimeMs > LOCK_STALE_MS) rmSync3(path, { force: true });
69303
+ } catch {
69304
+ }
69305
+ if (Date.now() > deadline) throw new Error(`another browser launch for ${profile} is still running`);
69306
+ await new Promise((resolveWait) => setTimeout(resolveWait, 200));
69307
+ }
69308
+ }
69172
69309
  }
69173
69310
 
69174
- // ../protocol/src/frames/computer-keys.ts
69175
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
69176
- var COMPUTER_KEY_ALIASES = {
69177
- enter: "return",
69178
- esc: "escape",
69179
- control: "ctrl",
69180
- option: "alt"
69181
- };
69182
- function normalizeComputerKey(key) {
69183
- const lowered = key.trim().toLowerCase();
69184
- return COMPUTER_KEY_ALIASES[lowered] ?? lowered;
69311
+ // src/browser/close.ts
69312
+ var OP_QUERY_TREE = 15;
69313
+ var OP_INTERN_ATOM = 16;
69314
+ var OP_GET_PROPERTY = 20;
69315
+ var OP_SEND_EVENT = 25;
69316
+ var CLIENT_MESSAGE = 33;
69317
+ async function closeBrowser(options) {
69318
+ const log40 = options.log ?? (() => void 0);
69319
+ const pid = profileOwner(options.profile);
69320
+ if (pid === void 0) return "not-running";
69321
+ try {
69322
+ const x = await X11Connection.connect({
69323
+ display: options.display,
69324
+ ...options.xauthority ? { xauthority: options.xauthority } : {}
69325
+ });
69326
+ try {
69327
+ const windows = await windowsOf(x, pid);
69328
+ const protocols = await internAtom(x, "WM_PROTOCOLS");
69329
+ const remove = await internAtom(x, "WM_DELETE_WINDOW");
69330
+ for (const window2 of windows) await sendClientMessage(x, window2, protocols, [remove, 0, 0, 0, 0]);
69331
+ log40(`asked ${windows.length} browser window(s) of ${options.profile} to close`);
69332
+ } finally {
69333
+ x.close();
69334
+ }
69335
+ } catch (error63) {
69336
+ log40(`could not ask the browser of ${options.profile} to close: ${error63.message}`);
69337
+ }
69338
+ if (await exited(pid, options.timeoutMs ?? 15e3)) return "closed";
69339
+ log40(`browser ${pid} did not exit after its windows closed; sending SIGTERM (unflushed cookies may be lost)`);
69340
+ process.kill(pid, "SIGTERM");
69341
+ if (await exited(pid, 5e3)) return "terminated";
69342
+ process.kill(pid, "SIGKILL");
69343
+ return "killed";
69344
+ }
69345
+ async function waitForWindowManager(display, timeoutMs) {
69346
+ const deadline = Date.now() + timeoutMs;
69347
+ while (Date.now() < deadline) {
69348
+ try {
69349
+ const x = await X11Connection.connect({ display });
69350
+ try {
69351
+ const check2 = await internAtom(x, "_NET_SUPPORTING_WM_CHECK");
69352
+ if (await cardinal(x, x.setup.root, check2, 33) !== void 0) return true;
69353
+ } finally {
69354
+ x.close();
69355
+ }
69356
+ } catch {
69357
+ }
69358
+ await new Promise((resolve5) => setTimeout(resolve5, 200));
69359
+ }
69360
+ return false;
69185
69361
  }
69186
-
69187
- // ../protocol/src/frames/computer.ts
69188
- var COMPUTER_CP_SUBPROTOCOL = "agentconnect.computer.v1";
69189
- var COMPUTER_WS_PUBLIC_PATH = "/v1/computers/ws";
69190
- var COMPUTER_REGISTER_PUBLIC_PATH = "/v1/computers/register";
69191
- var COMPUTER_SESSIONS = ["aqua", "console", "rdp", "x11", "xvfb", "wayland-gnome"];
69192
- var COMPUTER_LIVE_STATUSES = ["online", "locked", "paused", "human_in_control", "busy"];
69193
- var HHMM = "(?:[01]\\d|2[0-3]):[0-5]\\d";
69194
- var QUIET_RANGE_RE = new RegExp(`^${HHMM}-${HHMM}$`);
69195
- function isTimeZone(tz) {
69196
- try {
69197
- new Intl.DateTimeFormat("en-US", { timeZone: tz });
69198
- return true;
69199
- } catch {
69200
- return false;
69362
+ async function exited(pid, timeoutMs) {
69363
+ const deadline = Date.now() + timeoutMs;
69364
+ for (; ; ) {
69365
+ try {
69366
+ process.kill(pid, 0);
69367
+ } catch {
69368
+ return true;
69369
+ }
69370
+ if (Date.now() > deadline) return false;
69371
+ await new Promise((resolve5) => setTimeout(resolve5, 200));
69201
69372
  }
69202
69373
  }
69203
- var AppId = external_exports.string().trim().min(1).max(256);
69204
- var COMPUTER_ACCESS_AGENTS_MAX = 200;
69205
- var COMPUTER_AGENT_ACCESS_MODES = ["none", "selected", "all"];
69206
- var ComputerAgentAccess = external_exports.object({
69207
- mode: external_exports.enum(COMPUTER_AGENT_ACCESS_MODES),
69208
- agents: external_exports.array(external_exports.uuid()).max(COMPUTER_ACCESS_AGENTS_MAX).default([])
69209
- });
69210
- var ComputerPolicySchema = external_exports.object({
69211
- allowedMembers: external_exports.array(external_exports.string().min(1).max(128)).max(500).default([]),
69212
- agentMode: external_exports.enum(["view", "control"]).default("control"),
69213
- approvals: ComputerApprovalsSchema.default({ firstInputPerSession: true }),
69214
- appAllowlist: external_exports.array(AppId).max(200).optional(),
69215
- redactApps: external_exports.array(AppId).max(200).default([]),
69216
- exposeDriverTools: external_exports.boolean().default(false),
69217
- quietHours: external_exports.object({
69218
- tz: external_exports.string().min(1).max(64).refine(isTimeZone, "unknown IANA time zone"),
69219
- ranges: external_exports.array(external_exports.string().regex(QUIET_RANGE_RE, "expected HH:MM-HH:MM")).min(1).max(24)
69220
- }).optional(),
69221
- leaseIdleSeconds: external_exports.number().int().min(10).max(3600).default(120),
69222
- leaseMaxSeconds: external_exports.number().int().min(60).max(86400).default(1800),
69223
- // Seconds an acquire waits in the FIFO lease queue before `computer_busy` (§4.4); 0 never waits.
69224
- leaseWaitSeconds: external_exports.number().int().min(0).max(COMPUTER_LEASE_WAIT_MAX_SECONDS).default(45),
69225
- // Days stored screenshots are kept (§9); 0 means never written, absent means the deployment's default.
69226
- screenshotRetentionDays: external_exports.number().int().min(0).max(COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS).optional(),
69227
- // Whether viewers may hole-punch peer to peer, which shows them the desktop's public IP (§7.2); absent means on only for owner-only viewing.
69228
- viewerPeerToPeer: external_exports.boolean().optional(),
69229
- // The command-line tier (§5.7); absent means the Computer's default, on for a managed one and off otherwise.
69230
- shell: external_exports.enum(COMPUTER_SHELL_MODES).optional(),
69231
- files: external_exports.enum(COMPUTER_FILES_MODES).optional(),
69232
- // Prefixes the file tools may touch; absent means the user's home directory.
69233
- fileRoots: external_exports.array(ComputerFileRoot).max(COMPUTER_FILE_ROOTS_MAX).optional()
69234
- }).refine((p) => p.leaseIdleSeconds <= p.leaseMaxSeconds, {
69235
- message: "leaseIdleSeconds must not exceed leaseMaxSeconds",
69236
- path: ["leaseIdleSeconds"]
69237
- }).refine((p) => p.agentMode === "control" || p.shell === void 0 || p.shell === "off", {
69238
- message: "a shell needs agentMode control",
69239
- path: ["shell"]
69240
- });
69241
- var ComputerCapabilitiesSchema = external_exports.object({
69242
- screenshot: external_exports.boolean().default(false),
69243
- input: external_exports.boolean().default(false),
69244
- textInput: external_exports.enum(["full", "keymap-only"]).default("full"),
69245
- // Which human input pauses agents (§6); absent reads as pointer only, what older desktops detect.
69246
- humanActivity: external_exports.enum(["pointer", "pointer+keyboard"]).optional(),
69247
- backgroundInput: external_exports.boolean().default(false),
69248
- accessibilityTree: external_exports.boolean().default(false),
69249
- viewer: external_exports.boolean().default(false),
69250
- // The viewer accepts a view token's `stun` claim; desktops before relay STUN refuse such a token.
69251
- viewerStun: external_exports.boolean().optional(),
69252
- // The browser's traffic leaves through the desktop's egress forwarder, which applies `computer/egress` (§15.4).
69253
- egress: external_exports.boolean().optional(),
69254
- // The command-line tier can run here (§5.7): computer_exec, and the file tools.
69255
- exec: external_exports.boolean().optional(),
69256
- files: external_exports.boolean().optional(),
69257
- displays: external_exports.array(
69258
- external_exports.object({
69259
- id: external_exports.string().min(1).max(128),
69260
- width: external_exports.number().int().positive().max(1e5),
69261
- height: external_exports.number().int().positive().max(1e5),
69262
- scale: external_exports.number().positive().max(16)
69263
- })
69264
- ).max(16).default([]),
69265
- permissions: external_exports.object({
69266
- accessibility: external_exports.boolean().optional(),
69267
- screenRecording: external_exports.boolean().optional(),
69268
- portal: external_exports.boolean().optional(),
69269
- firewall: external_exports.boolean().optional()
69270
- }).default({})
69271
- });
69272
- var ComputerDoctorCheck = external_exports.object({
69273
- name: external_exports.string().min(1).max(64),
69274
- status: external_exports.enum(["ok", "info", "warn", "fail"]),
69275
- detail: external_exports.string().max(1e3),
69276
- fix: external_exports.string().max(1e3).optional()
69277
- });
69278
- var ComputerDoctorReport = external_exports.object({
69279
- checkedAt: external_exports.string().datetime(),
69280
- checks: external_exports.array(ComputerDoctorCheck).max(64)
69281
- });
69282
- var ComputerChannelCredential = external_exports.object({
69283
- keyId: external_exports.string().min(1).max(64),
69284
- // 32 random-looking bytes, base64url without padding; secret material, never logged.
69285
- key: external_exports.string().regex(/^[A-Za-z0-9_-]{43}$/),
69286
- issuedAt: external_exports.string().datetime(),
69287
- expiresAt: external_exports.string().datetime()
69288
- });
69289
- var ComputerEgressProxyUrl = external_exports.string().max(512).refine((raw) => {
69290
- try {
69291
- const u = new URL(raw);
69292
- return (u.protocol === "http:" || u.protocol === "https:") && u.hostname !== "" && u.username === "" && u.password === "" && (u.pathname === "" || u.pathname === "/") && u.search === "" && u.hash === "";
69293
- } catch {
69294
- return false;
69374
+ async function windowsOf(x, pid) {
69375
+ const pidAtom = await internAtom(x, "_NET_WM_PID");
69376
+ const found = [];
69377
+ for (const frame of await queryTree(x, x.setup.root)) {
69378
+ for (const window2 of [frame, ...await queryTree(x, frame)]) {
69379
+ const value = await cardinal(x, window2, pidAtom);
69380
+ if (value === pid) found.push(window2);
69381
+ }
69295
69382
  }
69296
- }, "expected http://host:port or https://host:port without credentials or a path");
69297
- var ComputerEgress = external_exports.discriminatedUnion("mode", [
69298
- external_exports.object({ mode: external_exports.literal("direct") }),
69299
- external_exports.object({
69300
- mode: external_exports.literal("proxy"),
69301
- url: ComputerEgressProxyUrl,
69302
- username: external_exports.string().min(1).max(256).optional(),
69303
- password: external_exports.string().min(1).max(512).optional()
69304
- })
69305
- ]);
69306
- var COMPUTER_EGRESS_FEATURE = "computer-egress-v1";
69307
- var ComputerAuth = external_exports.object({
69308
- apiKey: external_exports.string().min(1).max(256),
69309
- desktopDaemonVersion: external_exports.string().trim().min(1).max(64)
69310
- }).strict();
69311
- var ComputerAuthOk = external_exports.object({
69312
- computerId: external_exports.string().uuid(),
69313
- orgId: external_exports.string().min(1).max(64),
69314
- name: external_exports.string().min(1).max(200),
69315
- heartbeatSec: external_exports.number().int().positive(),
69316
- serverTime: external_exports.string().datetime(),
69317
- credential: ComputerChannelCredential,
69318
- policy: ComputerPolicySchema,
69319
- // What this CP accepts on the channel beyond the base frames, such as `computer-audit-v1`.
69320
- features: external_exports.array(external_exports.string().min(1).max(64)).max(32).optional(),
69321
- // The retention in effect for this Computer's screenshots (§9); 0 or absent means none are stored.
69322
- screenshotRetentionDays: external_exports.number().int().min(0).max(COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS).optional(),
69323
- // A managed desktop's egress (§15.4); absent means direct unless `computer-egress-v1` is advertised. Secret, never logged.
69324
- egress: ComputerEgress.optional()
69325
- });
69326
- var ComputerHeartbeat = external_exports.object({
69327
- status: external_exports.enum(COMPUTER_LIVE_STATUSES),
69328
- osVersion: external_exports.string().trim().min(1).max(120).optional(),
69329
- session: external_exports.enum(COMPUTER_SESSIONS).optional(),
69330
- desktopDaemonVersion: external_exports.string().trim().min(1).max(64).optional(),
69331
- driverVersion: external_exports.string().trim().min(1).max(64).optional(),
69332
- capabilities: ComputerCapabilitiesSchema.optional(),
69333
- doctor: ComputerDoctorReport.optional(),
69334
- // The local lease, how long since its last input, and how long it has been held without idling out.
69335
- lease: external_exports.object({
69336
- holder: external_exports.string().min(1).max(512),
69337
- idleMs: external_exports.number().int().min(0),
69338
- heldMs: external_exports.number().int().min(0).optional()
69339
- }).strict().optional()
69340
- }).strict();
69341
- var ComputerCredentialRenewal = external_exports.object({ credential: ComputerChannelCredential });
69342
- var ComputerPolicyPush = external_exports.object({
69343
- policy: ComputerPolicySchema,
69344
- screenshotRetentionDays: external_exports.number().int().min(0).max(COMPUTER_SCREENSHOT_RETENTION_MAX_DAYS).optional()
69345
- });
69346
- var ComputerRevoke = external_exports.object({
69347
- reason: external_exports.enum(["revoked", "deleted", "owner_removed"]),
69348
- message: external_exports.string().max(500).optional()
69349
- });
69350
- var ComputerLeasePush = external_exports.object({ lease: ComputerControlLease.nullable() });
69351
- var ComputerRelaysPush = external_exports.object({ relays: external_exports.array(ComputerRelayEntry).max(COMPUTER_RELAYS_MAX) });
69352
- var ComputerStopPush = external_exports.object({ stop: external_exports.object({ at: external_exports.string().datetime() }).nullable() });
69353
- var ComputerEgressPush = external_exports.object({ egress: ComputerEgress });
69354
- var COMPUTER_ADMIN_PROMPTS_FEATURE = "computer-admin-prompts-v1";
69355
- var ComputerAdminPromptsSet = external_exports.object({ mode: external_exports.enum(COMPUTER_ADMIN_PROMPT_MODES) }).strict();
69356
- var ComputerAdminPromptsSetOk = external_exports.object({ mode: external_exports.enum(COMPUTER_ADMIN_PROMPT_MODES) });
69357
- var COMPUTER_CP_SCHEMAS = {
69358
- "computer/auth": ComputerAuth,
69359
- "computer/auth/ok": ComputerAuthOk,
69360
- "computer/heartbeat": ComputerHeartbeat,
69361
- "computer/credential": ComputerCredentialRenewal,
69362
- "computer/policy": ComputerPolicyPush,
69363
- "computer/revoke": ComputerRevoke,
69364
- "computer/lease": ComputerLeasePush,
69365
- "computer/relays": ComputerRelaysPush,
69366
- "computer/stop": ComputerStopPush,
69367
- "computer/egress": ComputerEgressPush,
69368
- "computer/admin-prompts": ComputerAdminPromptsSet,
69369
- "computer/admin-prompts/ok": ComputerAdminPromptsSetOk,
69370
- "computer/audit": ComputerAuditReport,
69371
- "computer/audit/ok": ComputerAuditAck,
69372
- "computer/screenshot/put": ComputerScreenshotPut,
69373
- "computer/screenshot/put/ok": ComputerScreenshotPutOk,
69374
- "computer/screenshot/commit": ComputerScreenshotCommit,
69375
- "computer/screenshot/commit/ok": ComputerScreenshotCommitOk,
69376
- error: ErrorFrame
69377
- };
69378
- var COMPUTER_CP_FRAME_TYPES = Object.keys(COMPUTER_CP_SCHEMAS);
69379
- var ComputerCpFrame = external_exports.discriminatedUnion("type", [
69380
- frameSchema("computer/auth", COMPUTER_CP_SCHEMAS["computer/auth"]),
69381
- frameSchema("computer/auth/ok", COMPUTER_CP_SCHEMAS["computer/auth/ok"]),
69382
- frameSchema("computer/heartbeat", COMPUTER_CP_SCHEMAS["computer/heartbeat"]),
69383
- frameSchema("computer/credential", COMPUTER_CP_SCHEMAS["computer/credential"]),
69384
- frameSchema("computer/policy", COMPUTER_CP_SCHEMAS["computer/policy"]),
69385
- frameSchema("computer/revoke", COMPUTER_CP_SCHEMAS["computer/revoke"]),
69386
- frameSchema("computer/lease", COMPUTER_CP_SCHEMAS["computer/lease"]),
69387
- frameSchema("computer/relays", COMPUTER_CP_SCHEMAS["computer/relays"]),
69388
- frameSchema("computer/stop", COMPUTER_CP_SCHEMAS["computer/stop"]),
69389
- frameSchema("computer/egress", COMPUTER_CP_SCHEMAS["computer/egress"]),
69390
- frameSchema("computer/admin-prompts", COMPUTER_CP_SCHEMAS["computer/admin-prompts"]),
69391
- frameSchema("computer/admin-prompts/ok", COMPUTER_CP_SCHEMAS["computer/admin-prompts/ok"]),
69392
- frameSchema("computer/audit", COMPUTER_CP_SCHEMAS["computer/audit"]),
69393
- frameSchema("computer/audit/ok", COMPUTER_CP_SCHEMAS["computer/audit/ok"]),
69394
- frameSchema("computer/screenshot/put", COMPUTER_CP_SCHEMAS["computer/screenshot/put"]),
69395
- frameSchema("computer/screenshot/put/ok", COMPUTER_CP_SCHEMAS["computer/screenshot/put/ok"]),
69396
- frameSchema("computer/screenshot/commit", COMPUTER_CP_SCHEMAS["computer/screenshot/commit"]),
69397
- frameSchema("computer/screenshot/commit/ok", COMPUTER_CP_SCHEMAS["computer/screenshot/commit/ok"]),
69398
- frameSchema("error", COMPUTER_CP_SCHEMAS["error"])
69399
- ]);
69400
- var TOLERANT_COMPUTER_CP_SCHEMAS = tolerantSchemas(COMPUTER_CP_SCHEMAS);
69401
- function decodeComputerCpFrameTolerant(text) {
69402
- return decodeEnvelopeWith(TOLERANT_COMPUTER_CP_SCHEMAS, text);
69383
+ return found;
69403
69384
  }
69404
- function buildComputerCpFrame(type, payload, opts = {}) {
69405
- return buildEnvelopeRaw(type, payload, opts);
69385
+ async function internAtom(x, name) {
69386
+ const bytes = Buffer.from(name, "latin1");
69387
+ const body = Buffer.alloc(4 + bytes.length);
69388
+ body.writeUInt16LE(bytes.length, 0);
69389
+ bytes.copy(body, 4);
69390
+ return (await x.request(request(OP_INTERN_ATOM, 0, body))).readUInt32LE(8);
69391
+ }
69392
+ async function queryTree(x, window2) {
69393
+ const body = Buffer.alloc(4);
69394
+ body.writeUInt32LE(window2, 0);
69395
+ const reply2 = await x.request(request(OP_QUERY_TREE, 0, body)).catch(() => void 0);
69396
+ if (!reply2) return [];
69397
+ const count = reply2.readUInt16LE(16);
69398
+ return Array.from({ length: count }, (_, i) => reply2.readUInt32LE(32 + i * 4));
69399
+ }
69400
+ async function cardinal(x, window2, property, type = 0) {
69401
+ const body = Buffer.alloc(20);
69402
+ body.writeUInt32LE(window2, 0);
69403
+ body.writeUInt32LE(property, 4);
69404
+ body.writeUInt32LE(type, 8);
69405
+ body.writeUInt32LE(0, 12);
69406
+ body.writeUInt32LE(1, 16);
69407
+ const reply2 = await x.request(request(OP_GET_PROPERTY, 0, body)).catch(() => void 0);
69408
+ if (!reply2 || reply2[1] !== 32 || reply2.readUInt32LE(16) < 1) return void 0;
69409
+ return reply2.readUInt32LE(32);
69410
+ }
69411
+ async function sendClientMessage(x, window2, type, data) {
69412
+ const event = Buffer.alloc(32);
69413
+ event[0] = CLIENT_MESSAGE;
69414
+ event[1] = 32;
69415
+ event.writeUInt32LE(window2, 4);
69416
+ event.writeUInt32LE(type, 8);
69417
+ data.forEach((value, i) => event.writeUInt32LE(value >>> 0, 12 + i * 4));
69418
+ const body = Buffer.alloc(40);
69419
+ body.writeUInt32LE(window2, 0);
69420
+ body.writeUInt32LE(0, 4);
69421
+ event.copy(body, 8);
69422
+ await x.checked(request(OP_SEND_EVENT, 0, body));
69406
69423
  }
69407
69424
 
69425
+ // src/linux/desktops.ts
69426
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
69427
+ import { spawn as spawn5, spawnSync } from "node:child_process";
69428
+ import { chmodSync, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
69429
+ import { homedir as homedir2 } from "node:os";
69430
+ import { join as join6 } from "node:path";
69431
+
69432
+ // src/computer.ts
69433
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
69434
+ import { hostname as hostname5, release } from "node:os";
69435
+
69408
69436
  // src/driver/client.ts
69409
69437
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
69410
69438
 
@@ -85345,6 +85373,14 @@ function describeDesktops(switchedOn, support) {
85345
85373
  if (!switchedOn) return "off (switched off): agents take turns on this desktop";
85346
85374
  return `on: each agent gets its own desktop (Xvfb + ${support.session === "xfce" ? "Xfce" : "xfwm4"})`;
85347
85375
  }
85376
+ function desktopsNotice(command) {
85377
+ return [
85378
+ "Per-agent desktops are on: each agent works on a desktop of its own, not on this screen; watch it in the console",
85379
+ "or the viewer. Agents' browsers start with a copy of this desktop's Chromium logins (the console policy",
85380
+ `"Share browser logins" turns that off). Turn per-agent desktops off with the tray's "Separate desktop for each`,
85381
+ `agent" or: ${command} desktops off`
85382
+ ].join("\n");
85383
+ }
85348
85384
  function desktopsCheck(switchedOn, support, command, install) {
85349
85385
  const detail = describeDesktops(switchedOn, support);
85350
85386
  const browserNote = support.browser ? "" : "; no Chromium found, so agents get no shared browser logins";
@@ -85390,10 +85426,11 @@ function desktopBrowserPlan(dataDir2, id) {
85390
85426
  const state = loadDesktopState(dataDir2);
85391
85427
  const ids = Object.values(state.desktops).map((record2) => record2.id);
85392
85428
  if (!ids.includes(id)) throw new Error(`no desktop ${id}`);
85429
+ const share = state.shareBrowserLogins !== false;
85393
85430
  return {
85394
85431
  profile: desktopProfile(dataDir2, id),
85395
- master: state.master,
85396
- sources: [state.master, ...ids.filter((other) => other !== id).map((other) => desktopProfile(dataDir2, other))],
85432
+ ...share ? { master: state.master } : {},
85433
+ sources: share ? [state.master, ...ids.filter((other) => other !== id).map((other) => desktopProfile(dataDir2, other))] : [],
85397
85434
  skip: ids.map((other) => wrapperDir(dataDir2, other)),
85398
85435
  ...state.mainBus ? { mainBus: state.mainBus } : {}
85399
85436
  };
@@ -85419,13 +85456,21 @@ exec ${self2.map(quote).join(" ")} browser --desktop ${quote(id)} -- "$@" >>${qu
85419
85456
  writeFileSync3(join6(apps, file2), entry);
85420
85457
  }
85421
85458
  }
85422
- function memoryGiB() {
85459
+ function memoryGiB(read = (path) => readFileSync4(path, "utf8")) {
85460
+ const GiB = 1024 * 1024 * 1024;
85461
+ const free = [];
85462
+ try {
85463
+ const match = /^MemAvailable:\s+(\d+) kB/m.exec(read("/proc/meminfo"));
85464
+ if (match) free.push(Number(match[1]) * 1024);
85465
+ } catch {
85466
+ }
85423
85467
  try {
85424
- const match = /^MemAvailable:\s+(\d+) kB/m.exec(readFileSync4("/proc/meminfo", "utf8"));
85425
- if (match) return Math.max(1, Math.floor(Number(match[1]) / (1024 * 1024)));
85468
+ const limit = read("/sys/fs/cgroup/memory.max").trim();
85469
+ if (limit !== "max") free.push(Number(limit) - Number(read("/sys/fs/cgroup/memory.current").trim()));
85426
85470
  } catch {
85427
85471
  }
85428
- return 1;
85472
+ const least = free.filter((bytes) => Number.isFinite(bytes)).reduce((a, b) => Math.min(a, b), Infinity);
85473
+ return least === Infinity ? 1 : Math.max(0, Math.floor(least / GiB));
85429
85474
  }
85430
85475
  var DesktopManager = class {
85431
85476
  constructor(deps) {
@@ -85451,12 +85496,19 @@ var DesktopManager = class {
85451
85496
  closed = false;
85452
85497
  // The owner's pause, applied to every desktop, including ones started while it stands.
85453
85498
  paused;
85499
+ /** The registrant's `shareBrowserLogins` (§3.9), kept with the state the browser wrappers read. */
85500
+ setShareBrowserLogins(on) {
85501
+ if (this.state.shareBrowserLogins !== false === on) return;
85502
+ this.state.shareBrowserLogins = on;
85503
+ saveDesktopState(this.deps.dataDir, this.state);
85504
+ this.deps.log(`per-agent desktops: browser logins ${on ? "shared between desktops" : "kept apart per desktop"}`);
85505
+ }
85454
85506
  /** On when the owner's switch is on and the machine supports it. */
85455
85507
  enabled() {
85456
85508
  return this.deps.config.perAgentDesktops && this.deps.support().supported;
85457
85509
  }
85458
85510
  max() {
85459
- return this.deps.config.maxDesktops ?? memoryGiB();
85511
+ return this.deps.config.maxDesktops ?? Math.max(1, this.running.size + memoryGiB());
85460
85512
  }
85461
85513
  /** A desktop by id for a person in the viewer, started if it is not running; undefined for an unknown id. */
85462
85514
  async byId(id) {
@@ -85577,6 +85629,7 @@ var DesktopManager = class {
85577
85629
  XFCE_SHELL.forEach(run4);
85578
85630
  const { driver, computer } = this.deps.build({
85579
85631
  id: record2.id,
85632
+ key: record2.key,
85580
85633
  label: record2.label,
85581
85634
  env,
85582
85635
  launchBrowser: (app) => isBrowserName(app) ? async () => {
@@ -85749,7 +85802,7 @@ async function desktopBrowser(id, args, log40, dataDir2) {
85749
85802
  if (plan.mainBus) env.DBUS_SESSION_BUS_ADDRESS = plan.mainBus;
85750
85803
  const result = await launchBrowser({
85751
85804
  profile: plan.profile,
85752
- master: plan.master,
85805
+ ...plan.master ? { master: plan.master } : {},
85753
85806
  sources: plan.sources,
85754
85807
  browser,
85755
85808
  // The desktop's tabs come back after its browser was closed for idleness (computer-use.md §3.10).
@@ -86264,7 +86317,8 @@ function auditEntry(record2, at, id = randomUUID2()) {
86264
86317
  args: summary.args,
86265
86318
  ...summary.textLength !== void 0 ? { textLength: summary.textLength } : {},
86266
86319
  ms: Math.max(0, Math.round(record2.ms)),
86267
- ...record2.screenshotRef ? { screenshotRef: record2.screenshotRef } : {}
86320
+ ...record2.screenshotRef ? { screenshotRef: record2.screenshotRef } : {},
86321
+ ...record2.desktop ? { desktop: record2.desktop } : {}
86268
86322
  };
86269
86323
  }
86270
86324
  var AuditReporter = class {
@@ -86798,8 +86852,8 @@ var DaemonConfig = external_exports.object({
86798
86852
  webrtc: external_exports.boolean().default(true),
86799
86853
  // Hold the display awake while running: a sleeping display cannot be captured or controlled.
86800
86854
  keepAwake: external_exports.boolean().default(true),
86801
- // Linux: each agent gets its own desktop where the machine supports it (computer-use.md §3.9); off until it ships whole.
86802
- perAgentDesktops: external_exports.boolean().default(false),
86855
+ // Linux: each agent gets its own desktop where the machine supports it (computer-use.md §3.9); false shares this one.
86856
+ perAgentDesktops: external_exports.boolean().default(true),
86803
86857
  // An agent desktop's screen, and how long one with no lease or viewer keeps its browser, then itself, running.
86804
86858
  desktopSize: external_exports.string().regex(/^\d{3,4}x\d{3,4}$/).default("1280x800"),
86805
86859
  browserIdleMinutes: external_exports.number().int().min(1).max(1440).default(10),
@@ -90295,7 +90349,7 @@ var serviceEntry = () => managedEntry() ?? resolve3(process.argv[1]);
90295
90349
 
90296
90350
  // src/version.ts
90297
90351
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
90298
- var COMPUTER_DAEMON_VERSION = true ? "2.12.0-rc.13" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
90352
+ var COMPUTER_DAEMON_VERSION = true ? "2.12.0-rc.18" : JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
90299
90353
 
90300
90354
  // src/http-server.ts
90301
90355
  var CONTROL_HEADER = "x-agentconnect-computer";
@@ -114380,6 +114434,112 @@ function createViewer(options) {
114380
114434
 
114381
114435
  // src/viewer-router.ts
114382
114436
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
114437
+
114438
+ // src/mcp-access.ts
114439
+ init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
114440
+ var bearer = (authorization) => /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1];
114441
+ function channelPrincipal(authorization, authority, computerId) {
114442
+ const token = bearer(authorization);
114443
+ const id = computerId();
114444
+ if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
114445
+ const claims = authority.verify(token, "mcp", id);
114446
+ if (!claims?.ses || !claims.agt) return void 0;
114447
+ return {
114448
+ client: computerLeaseHolderName({ agentId: claims.agt, sessionId: claims.ses }),
114449
+ viewOnly: claims.mode === "view",
114450
+ agent: { agentId: claims.agt, sessionId: claims.ses },
114451
+ ...claims.sh || claims.fs ? { commandLineGrant: { shell: claims.sh ?? "off", files: claims.fs ?? "off" } } : {}
114452
+ };
114453
+ }
114454
+ var RESPONSE_HEADERS = ["allow", "content-type", "mcp-protocol-version", "mcp-session-id", "www-authenticate"];
114455
+ function reply(status, body, headers = {}) {
114456
+ return {
114457
+ status,
114458
+ headers: { "content-type": "application/json", ...headers },
114459
+ body: Buffer.from(JSON.stringify(body)).toString("base64")
114460
+ };
114461
+ }
114462
+ function viewerPrincipal(authorization, authority, computerId) {
114463
+ const token = bearer(authorization);
114464
+ const id = computerId();
114465
+ if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
114466
+ const claims = authority.verify(token, "view", id);
114467
+ if (!claims?.usr) return void 0;
114468
+ return {
114469
+ client: `console:${claims.usr}`,
114470
+ control: claims.mode === "control",
114471
+ iceServers: claims.ice ?? [],
114472
+ stunUrls: claims.stun ?? [],
114473
+ desktop: claims.dsk ?? "main",
114474
+ valid: () => authority.verify(token, "view", id) !== void 0
114475
+ };
114476
+ }
114477
+ var mayWatch = (principal, desktop) => desktop === null || principal.desktop === void 0 || principal.desktop === desktop;
114478
+ function viewerAuthenticator(member, localClient, desktop = "main") {
114479
+ return (authorization, via) => {
114480
+ const principal = member(authorization);
114481
+ if (principal) return mayWatch(principal, desktop) ? principal : void 0;
114482
+ if (via !== "local") return void 0;
114483
+ const client = localClient(authorization);
114484
+ return client ? { client, control: true } : void 0;
114485
+ };
114486
+ }
114487
+ function createRelayedMcpHandler(deps) {
114488
+ return async (request2) => {
114489
+ const pathname = new URL(request2.path, "http://desktop.invalid").pathname;
114490
+ if (deps.viewer && pathname.startsWith(COMPUTER_VIEWER_API_PREFIX)) {
114491
+ const out = await deps.viewer({
114492
+ method: request2.method,
114493
+ path: pathname,
114494
+ authorization: request2.headers.authorization,
114495
+ via: "relay",
114496
+ ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
114497
+ });
114498
+ if (out.body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
114499
+ return {
114500
+ status: out.status,
114501
+ headers: out.headers,
114502
+ ...out.body.length > 0 ? { body: out.body.toString("base64") } : {}
114503
+ };
114504
+ }
114505
+ if (pathname !== "/mcp") return reply(404, { error: "not found" });
114506
+ const principal = deps.authenticate(request2.headers.authorization);
114507
+ if (!principal) return reply(401, { error: "unauthorized" }, { "www-authenticate": "Bearer" });
114508
+ if (request2.method !== "POST" && request2.method !== "DELETE") {
114509
+ return reply(405, { error: "method not allowed" }, { allow: "POST, DELETE" });
114510
+ }
114511
+ const mcp = deps.createMcpServer(principal);
114512
+ const transport = new WebStandardStreamableHTTPServerTransport({
114513
+ sessionIdGenerator: void 0,
114514
+ enableJsonResponse: true
114515
+ });
114516
+ try {
114517
+ await mcp.connect(transport);
114518
+ const response = await transport.handleRequest(
114519
+ new Request("http://desktop.invalid/mcp", {
114520
+ method: request2.method,
114521
+ headers: request2.headers,
114522
+ ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
114523
+ })
114524
+ );
114525
+ const body = Buffer.from(await response.arrayBuffer());
114526
+ if (body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
114527
+ const headers = {};
114528
+ for (const name of RESPONSE_HEADERS) {
114529
+ const value = response.headers.get(name);
114530
+ if (value !== null) headers[name] = value;
114531
+ }
114532
+ return { status: response.status, headers, ...body.length > 0 ? { body: body.toString("base64") } : {} };
114533
+ } catch (error63) {
114534
+ deps.log(`relayed request failed: ${error63.message}`);
114535
+ return reply(500, { error: "failed" });
114536
+ } finally {
114537
+ void mcp.close().catch(() => void 0);
114538
+ }
114539
+ };
114540
+ }
114541
+
114542
+ // src/viewer-router.ts
114383
114543
  var DESKTOP_PATH = /^\/view\/api\/d\/([A-Za-z0-9_-]{1,32})(\/.*)$/;
114384
114544
  var MAX_BODY_BYTES2 = 64 * 1024;
114385
114545
  var json4 = (status, body) => ({
@@ -114425,10 +114585,11 @@ function createViewerRouter(options) {
114425
114585
  if (!match || match[1] === "main") {
114426
114586
  return options.main.api(match ? { ...request2, path: `/view/api${match[2]}` } : request2);
114427
114587
  }
114428
- if (!options.authenticate(request2.authorization, request2.via)) return json4(401, { error: "unauthorized" });
114588
+ const id = match[1];
114589
+ const principal = options.authenticate(request2.authorization, request2.via);
114590
+ if (!principal || !mayWatch(principal, id)) return json4(401, { error: "unauthorized" });
114429
114591
  const manager = options.desktops();
114430
114592
  if (!manager?.enabled()) return json4(404, { error: "not_found", message: "per-agent desktops are off" });
114431
- const id = match[1];
114432
114593
  let desktop;
114433
114594
  try {
114434
114595
  desktop = await manager.byId(id);
@@ -115047,6 +115208,7 @@ var ComputerCpClient = class {
115047
115208
  const payload = {
115048
115209
  status: report.status,
115049
115210
  ...report.lease ? { lease: report.lease } : {},
115211
+ ...report.desktops && this.features.has(COMPUTER_DESKTOPS_FEATURE) ? { desktops: report.desktops } : {},
115050
115212
  ...fresh ? report.facts : {}
115051
115213
  };
115052
115214
  try {
@@ -115060,9 +115222,10 @@ var ComputerCpClient = class {
115060
115222
  async reportAudit(entries2) {
115061
115223
  const transport = this.transport;
115062
115224
  if (this.state !== "READY" || !transport || !this.features.has(COMPUTER_AUDIT_FEATURE)) return "retry";
115225
+ const sent = this.features.has(COMPUTER_DESKTOPS_FEATURE) ? entries2 : entries2.map(({ desktop: _desktop, ...entry }) => entry);
115063
115226
  try {
115064
115227
  const reply2 = await this.correlator.request(
115065
- buildComputerCpFrame("computer/audit", { entries: entries2 }),
115228
+ buildComputerCpFrame("computer/audit", { entries: sent }),
115066
115229
  (encoded2) => transport.send(encoded2)
115067
115230
  );
115068
115231
  return reply2.type === "computer/audit/ok" ? "stored" : "retry";
@@ -115071,6 +115234,10 @@ var ComputerCpClient = class {
115071
115234
  return error63 instanceof WireError && !error63.retryable ? "rejected" : "retry";
115072
115235
  }
115073
115236
  }
115237
+ /** Whether the CP keys leases, status and audit per agent desktop (computer-use.md §3.9). */
115238
+ desktopsSupported() {
115239
+ return this.state === "READY" && this.features.has(COMPUTER_DESKTOPS_FEATURE);
115240
+ }
115074
115241
  /** Whether the CP stores the administrator-prompt mode the menu sets (computer-use.md §4.2.1). */
115075
115242
  servesAdminPrompts() {
115076
115243
  return this.state === "READY" && this.features.has(COMPUTER_ADMIN_PROMPTS_FEATURE);
@@ -115197,7 +115364,7 @@ var ComputerCpClient = class {
115197
115364
  this.deps.onPolicy?.(frame.payload.policy);
115198
115365
  return;
115199
115366
  case "computer/lease":
115200
- this.deps.onLease?.(frame.payload.lease);
115367
+ this.deps.onLease?.(frame.payload.lease, frame.payload.desktops);
115201
115368
  return;
115202
115369
  case "computer/relays":
115203
115370
  this.deps.onRelays?.(frame.payload.relays);
@@ -116743,108 +116910,6 @@ var RelayLinks = class {
116743
116910
  }
116744
116911
  };
116745
116912
 
116746
- // src/mcp-access.ts
116747
- init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
116748
- var bearer = (authorization) => /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1];
116749
- function channelPrincipal(authorization, authority, computerId) {
116750
- const token = bearer(authorization);
116751
- const id = computerId();
116752
- if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
116753
- const claims = authority.verify(token, "mcp", id);
116754
- if (!claims?.ses || !claims.agt) return void 0;
116755
- return {
116756
- client: computerLeaseHolderName({ agentId: claims.agt, sessionId: claims.ses }),
116757
- viewOnly: claims.mode === "view",
116758
- agent: { agentId: claims.agt, sessionId: claims.ses },
116759
- ...claims.sh || claims.fs ? { commandLineGrant: { shell: claims.sh ?? "off", files: claims.fs ?? "off" } } : {}
116760
- };
116761
- }
116762
- var RESPONSE_HEADERS = ["allow", "content-type", "mcp-protocol-version", "mcp-session-id", "www-authenticate"];
116763
- function reply(status, body, headers = {}) {
116764
- return {
116765
- status,
116766
- headers: { "content-type": "application/json", ...headers },
116767
- body: Buffer.from(JSON.stringify(body)).toString("base64")
116768
- };
116769
- }
116770
- function viewerPrincipal(authorization, authority, computerId) {
116771
- const token = bearer(authorization);
116772
- const id = computerId();
116773
- if (!token?.startsWith(`${COMPUTER_CHANNEL_TOKEN_PREFIX}.`) || !id) return void 0;
116774
- const claims = authority.verify(token, "view", id);
116775
- if (!claims?.usr) return void 0;
116776
- return {
116777
- client: `console:${claims.usr}`,
116778
- control: claims.mode === "control",
116779
- iceServers: claims.ice ?? [],
116780
- stunUrls: claims.stun ?? [],
116781
- valid: () => authority.verify(token, "view", id) !== void 0
116782
- };
116783
- }
116784
- function viewerAuthenticator(member, localClient) {
116785
- return (authorization, via) => {
116786
- const principal = member(authorization);
116787
- if (principal) return principal;
116788
- if (via !== "local") return void 0;
116789
- const client = localClient(authorization);
116790
- return client ? { client, control: true } : void 0;
116791
- };
116792
- }
116793
- function createRelayedMcpHandler(deps) {
116794
- return async (request2) => {
116795
- const pathname = new URL(request2.path, "http://desktop.invalid").pathname;
116796
- if (deps.viewer && pathname.startsWith(COMPUTER_VIEWER_API_PREFIX)) {
116797
- const out = await deps.viewer({
116798
- method: request2.method,
116799
- path: pathname,
116800
- authorization: request2.headers.authorization,
116801
- via: "relay",
116802
- ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
116803
- });
116804
- if (out.body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
116805
- return {
116806
- status: out.status,
116807
- headers: out.headers,
116808
- ...out.body.length > 0 ? { body: out.body.toString("base64") } : {}
116809
- };
116810
- }
116811
- if (pathname !== "/mcp") return reply(404, { error: "not found" });
116812
- const principal = deps.authenticate(request2.headers.authorization);
116813
- if (!principal) return reply(401, { error: "unauthorized" }, { "www-authenticate": "Bearer" });
116814
- if (request2.method !== "POST" && request2.method !== "DELETE") {
116815
- return reply(405, { error: "method not allowed" }, { allow: "POST, DELETE" });
116816
- }
116817
- const mcp = deps.createMcpServer(principal);
116818
- const transport = new WebStandardStreamableHTTPServerTransport({
116819
- sessionIdGenerator: void 0,
116820
- enableJsonResponse: true
116821
- });
116822
- try {
116823
- await mcp.connect(transport);
116824
- const response = await transport.handleRequest(
116825
- new Request("http://desktop.invalid/mcp", {
116826
- method: request2.method,
116827
- headers: request2.headers,
116828
- ...request2.body ? { body: Buffer.from(request2.body, "base64") } : {}
116829
- })
116830
- );
116831
- const body = Buffer.from(await response.arrayBuffer());
116832
- if (body.length > RELAY_COMPUTER_MAX_BODY_BYTES) return reply(500, { error: "response too large" });
116833
- const headers = {};
116834
- for (const name of RESPONSE_HEADERS) {
116835
- const value = response.headers.get(name);
116836
- if (value !== null) headers[name] = value;
116837
- }
116838
- return { status: response.status, headers, ...body.length > 0 ? { body: body.toString("base64") } : {} };
116839
- } catch (error63) {
116840
- deps.log(`relayed request failed: ${error63.message}`);
116841
- return reply(500, { error: "failed" });
116842
- } finally {
116843
- void mcp.close().catch(() => void 0);
116844
- }
116845
- };
116846
- }
116847
-
116848
116913
  // src/cp/report.ts
116849
116914
  init_define_AGENTCONNECT_COMPUTER_WINDOWS_SOURCES();
116850
116915
  import { spawnSync as spawnSync11 } from "node:child_process";
@@ -117571,8 +117636,8 @@ Commands:
117571
117636
  start a desktop's Chromium on its own profile, first merging the
117572
117637
  logins of the other profiles into it (or hand ARGS to the running one)
117573
117638
  browser-close --profile DIR [--display :N] close that browser the way a person would, so it saves its cookies
117574
- desktops [on | off | status] Linux: give each agent its own desktop (where the machine can:
117575
- Xvfb, D-Bus and Xfce), or let agents share this one (the default)
117639
+ desktops [on | off | status] Linux: give each agent its own desktop (the default where the
117640
+ machine can: Xvfb, D-Bus and Xfce), or let agents share this one
117576
117641
  service install | uninstall [--purge] | start | stop | restart | status
117577
117642
  background service: macOS .app LaunchAgent (the app holds
117578
117643
  the permissions), Linux systemd user unit (graphical session),
@@ -117851,6 +117916,19 @@ async function registerComputer(dir, token, cpUrl, name) {
117851
117916
  return registration;
117852
117917
  }
117853
117918
  var DOCTOR_INTERVAL_MS = 30 * 6e4;
117919
+ function desktopReports(manager) {
117920
+ if (!manager?.enabled()) return void 0;
117921
+ return manager.runningDesktops().filter((desktop) => UUID.test(desktop.record.key)).slice(0, COMPUTER_DESKTOPS_MAX).map((desktop) => {
117922
+ const lease = desktop.computer.leaseActivity();
117923
+ return {
117924
+ id: desktop.record.id,
117925
+ agentId: desktop.record.key,
117926
+ status: desktop.computer.liveStatus(),
117927
+ ...lease ? { lease } : {}
117928
+ };
117929
+ });
117930
+ }
117931
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
117854
117932
  function startCpChannel(options) {
117855
117933
  const { dir, config: config2, registration, authority, computer, driver, screenSize } = options;
117856
117934
  const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
@@ -117887,9 +117965,11 @@ function startCpChannel(options) {
117887
117965
  const display = computer.info().display;
117888
117966
  const lease = computer.leaseActivity();
117889
117967
  const local = options.local();
117968
+ const desktops = desktopReports(options.desktops?.());
117890
117969
  return {
117891
117970
  status: computer.liveStatus(),
117892
117971
  ...lease ? { lease } : {},
117972
+ ...desktops ? { desktops } : {},
117893
117973
  facts: {
117894
117974
  ...profile,
117895
117975
  driverVersion: driver.version ?? CUA_DRIVER_VERSION,
@@ -117912,8 +117992,14 @@ function startCpChannel(options) {
117912
117992
  config2.leaseMaxSeconds = policy.leaseMaxSeconds;
117913
117993
  options.onPolicy?.(policy);
117914
117994
  },
117915
- onLease: (lease) => computer.applyControlLease(lease),
117916
- onReady: (ok) => computer.rename(ok.name),
117995
+ onLease: (lease, desktops) => {
117996
+ computer.applyControlLease(lease);
117997
+ options.onDesktopLeases?.(desktops ?? []);
117998
+ },
117999
+ onReady: (ok) => {
118000
+ computer.rename(ok.name);
118001
+ if (ok.desktops) options.onArrangement?.(ok.desktops === "per-agent");
118002
+ },
117917
118003
  onRelays: (relays) => relayLinks.converge(relays),
117918
118004
  onStop: (stop) => applyConsoleStop(stop),
117919
118005
  onEgress: (egress) => options.egress?.apply(egress),
@@ -117949,7 +118035,7 @@ function startCpChannel(options) {
117949
118035
  }
117950
118036
  };
117951
118037
  }
117952
- function buildViewer(dir, config2, computer, refusal, consoleViewer, advertiseAddress, onFfmpegInstalled, display) {
118038
+ function buildViewer(dir, config2, computer, refusal, consoleViewer, advertiseAddress, onFfmpegInstalled, display, desktopId = "main") {
117953
118039
  const ffmpeg = () => resolveFfmpegPath(dir, config2.ffmpegPath);
117954
118040
  let ffmpegState = "missing";
117955
118041
  if (config2.webrtc) {
@@ -117981,7 +118067,10 @@ function buildViewer(dir, config2, computer, refusal, consoleViewer, advertiseAd
117981
118067
  stream,
117982
118068
  log: log39,
117983
118069
  onMessage: (principal, message) => viewer.channelMessage(principal, message),
117984
- reauthorize: (token) => consoleViewer?.(`Bearer ${token}`),
118070
+ reauthorize: (token) => {
118071
+ const principal = consoleViewer?.(`Bearer ${token}`);
118072
+ return principal && mayWatch(principal, desktopId) ? principal : void 0;
118073
+ },
117985
118074
  ...advertiseAddress ? { advertiseAddress } : {},
117986
118075
  ...config2.rtcPortRange ? { portRange: config2.rtcPortRange } : {}
117987
118076
  }) : void 0;
@@ -117989,7 +118078,8 @@ function buildViewer(dir, config2, computer, refusal, consoleViewer, advertiseAd
117989
118078
  computer,
117990
118079
  authenticate: viewerAuthenticator(
117991
118080
  (header) => consoleViewer?.(header),
117992
- (header) => authenticate(config2, header)
118081
+ (header) => authenticate(config2, header),
118082
+ desktopId
117993
118083
  ),
117994
118084
  log: log39,
117995
118085
  ...rtc ? { rtc } : {},
@@ -118137,7 +118227,11 @@ async function run3(dir, initial, clientName) {
118137
118227
  config: config2,
118138
118228
  support: () => desktopSupport.current,
118139
118229
  self: [process.execPath, resolve4(process.argv[1])],
118140
- build: ({ id, label, env, launchBrowser: launchBrowser2 }) => {
118230
+ build: ({ id, key, label, env, launchBrowser: launchBrowser2 }) => {
118231
+ const desktopAudit = auditSinks(
118232
+ fileAuditSink(join21(dir, "audit.log")),
118233
+ ...auditReport ? [auditReport.sink] : []
118234
+ );
118141
118235
  const prefixed = (line) => log39(`desktop ${id}: ${line}`);
118142
118236
  const desktopDriver = new CuaDriver({
118143
118237
  command: resolveDriverPath(dir, config2.driverPath),
@@ -118148,7 +118242,8 @@ async function run3(dir, initial, clientName) {
118148
118242
  const desktop = new Computer({
118149
118243
  driver: desktopDriver,
118150
118244
  config: config2,
118151
- audit: auditSinks(fileAuditSink(join21(dir, "audit.log")), ...auditReport ? [auditReport.sink] : []),
118245
+ // Each entry names the desktop that served it (§3.9).
118246
+ audit: (record2) => desktopAudit({ ...record2, desktop: id }),
118152
118247
  log: prefixed,
118153
118248
  onStatus: () => live2.local?.update(),
118154
118249
  refusal: () => authority.refusal(),
@@ -118161,6 +118256,7 @@ async function run3(dir, initial, clientName) {
118161
118256
  isolation: isolationKind()
118162
118257
  }
118163
118258
  });
118259
+ desktop.applyControlLease(live2.desktopLeases?.get(key) ?? null);
118164
118260
  return { driver: desktopDriver, computer: desktop };
118165
118261
  },
118166
118262
  log: log39,
@@ -118220,11 +118316,13 @@ async function run3(dir, initial, clientName) {
118220
118316
  consoleViewer,
118221
118317
  advertiseAddress,
118222
118318
  void 0,
118223
- desktop.display
118319
+ desktop.display,
118320
+ desktop.record.id
118224
118321
  ),
118225
118322
  authenticate: viewerAuthenticator(
118226
118323
  (header) => consoleViewer?.(header),
118227
- (header) => authenticate(config2, header)
118324
+ (header) => authenticate(config2, header),
118325
+ null
118228
118326
  ),
118229
118327
  mainInfo: () => ({
118230
118328
  name: String(computer.info().name),
@@ -118405,6 +118503,23 @@ async function run3(dir, initial, clientName) {
118405
118503
  onPolicy: (policy) => {
118406
118504
  live2.policy = policy;
118407
118505
  keepAdminPrompts(policy.approvals.adminPrompts);
118506
+ live2.desktops?.setShareBrowserLogins(policy.shareBrowserLogins !== false);
118507
+ },
118508
+ desktops: () => live2.desktops,
118509
+ // Not saved: the Control Plane says it again on every connect, and the allocation never changes.
118510
+ onArrangement: (on) => {
118511
+ if (config2.perAgentDesktops === on) return;
118512
+ config2.perAgentDesktops = on;
118513
+ log39(
118514
+ `per-agent desktops ${on ? "on" : "off"}: this managed computer ${on ? "is shared by agents" : "serves one agent"}`
118515
+ );
118516
+ live2.local?.update();
118517
+ if (!on) void live2.desktops?.stopAll("this managed computer serves one agent");
118518
+ },
118519
+ onDesktopLeases: (leases) => {
118520
+ live2.desktopLeases = new Map(leases.flatMap((lease) => lease.desktop ? [[lease.desktop, lease]] : []));
118521
+ for (const desktop of live2.desktops?.runningDesktops() ?? [])
118522
+ desktop.computer.applyControlLease(live2.desktopLeases.get(desktop.record.key) ?? null);
118408
118523
  }
118409
118524
  });
118410
118525
  const publicBase = publicBaseUrl(config2);
@@ -118671,6 +118786,7 @@ async function setup(dir, initial, clientName, withService) {
118671
118786
  }
118672
118787
  if (process.platform === "linux" && config2.perAgentDesktops) {
118673
118788
  await offerDesktopInstall(await probeDesktopSupport(), { log: (line) => console.log(line) });
118789
+ if ((await probeDesktopSupport()).supported) console.log(desktopsNotice(selfCommand()));
118674
118790
  }
118675
118791
  console.log("");
118676
118792
  let checks;