@akshar5/cohall 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cohall.js CHANGED
@@ -17,7 +17,7 @@ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
17
 
18
18
  // packages/protocol/src/index.ts
19
19
  import { Effect, Schema } from "effect";
20
- var version = "0.11.1", maxSocketPayloadBytes, maxAttachmentBytes, maxTaskAttachments = 2, maxProgressNoteBytes = 1024, bounded = (maxLength) => Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(maxLength)), optionalText = (maxLength) => Schema.String.check(Schema.isMaxLength(maxLength)), boundedArray = (schema, maxLength) => Schema.Array(schema).check(Schema.isMaxLength(maxLength)), count, uuid = (name) => Schema.String.check(Schema.isUUID(4)).pipe(Schema.brand(name)), isoTimestamp = (name) => Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/, {
20
+ var version = "0.11.3", maxSocketPayloadBytes, maxAttachmentBytes, maxTaskAttachments = 2, maxProgressNoteBytes = 1024, bounded = (maxLength) => Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(maxLength)), optionalText = (maxLength) => Schema.String.check(Schema.isMaxLength(maxLength)), boundedArray = (schema, maxLength) => Schema.Array(schema).check(Schema.isMaxLength(maxLength)), count, uuid = (name) => Schema.String.check(Schema.isUUID(4)).pipe(Schema.brand(name)), isoTimestamp = (name) => Schema.String.check(Schema.isPattern(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/, {
21
21
  expected: "an ISO-8601 UTC timestamp"
22
22
  })).pipe(Schema.brand(name)), BotId, Bot, DeviceId, ThreadId, MessageId, TaskId, TaskRequestId, TaskRunId, ClarificationId, AuthSessionId, OperationId, Timestamp, TaskDeadline, taskDeadlineError = "Task deadline exceeded", taskDeadlinePassed = (task, time = Date.now()) => task.expiresAt !== undefined && Date.parse(task.expiresAt) <= time, Platform, Provider, DeviceStatus, TaskStatus, OperationStatus, TaskTraceEventKind, MessageRole, ConnectionRole, AuthSession, CreatePairingInput, PairingCredential, ExchangePairingInput, SessionCredential, PairingResult, Capability, Workspace, Device, maxDevicePageDevices = 16, maxDevicePageResponseBytes, DevicePage, minimumDeviceOperationVersion = "0.5.0", parsedVersion = (value) => {
23
23
  const match = /^v?(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
@@ -420,10 +420,10 @@ var init_src = __esm(() => {
420
420
  });
421
421
 
422
422
  // apps/relay/src/config.ts
423
- import { Effect as Effect13, Schema as Schema15 } from "effect";
423
+ import { Effect as Effect13, Schema as Schema16 } from "effect";
424
424
  import { access as access5, chmod as chmod7, mkdir as mkdir9, readFile as readFile4, writeFile as writeFile10 } from "node:fs/promises";
425
425
  import { homedir as homedir5, platform as platform5 } from "node:os";
426
- import { isAbsolute as isAbsolute6, join as join10, resolve as resolve5 } from "node:path";
426
+ import { isAbsolute as isAbsolute6, join as join10, resolve as resolve6 } from "node:path";
427
427
  var RelayConfiguration, defaultDataDirectory = () => {
428
428
  if (platform5() === "win32") {
429
429
  return join10(process.env.LOCALAPPDATA ?? join10(homedir5(), "AppData", "Local"), "Cohall");
@@ -455,14 +455,14 @@ var RelayConfiguration, defaultDataDirectory = () => {
455
455
  throw new Error(`${name} must be true or false`);
456
456
  }, isLoopback2 = (host) => host === "127.0.0.1" || host === "localhost" || host === "::1", loadEnvironmentConfiguration;
457
457
  var init_config = __esm(() => {
458
- RelayConfiguration = Schema15.Struct({
459
- host: Schema15.NonEmptyString,
460
- port: Schema15.Int.check(Schema15.isBetween({ minimum: 1, maximum: 65535 })),
461
- token: Schema15.String.check(Schema15.isMinLength(32)),
462
- dataDirectory: Schema15.NonEmptyString,
463
- databasePath: Schema15.NonEmptyString,
464
- allowRemote: Schema15.Boolean,
465
- historyTaskLimit: Schema15.Int.check(Schema15.isBetween({ minimum: 100, maximum: 1e5 }))
458
+ RelayConfiguration = Schema16.Struct({
459
+ host: Schema16.NonEmptyString,
460
+ port: Schema16.Int.check(Schema16.isBetween({ minimum: 1, maximum: 65535 })),
461
+ token: Schema16.String.check(Schema16.isMinLength(32)),
462
+ dataDirectory: Schema16.NonEmptyString,
463
+ databasePath: Schema16.NonEmptyString,
464
+ allowRemote: Schema16.Boolean,
465
+ historyTaskLimit: Schema16.Int.check(Schema16.isBetween({ minimum: 100, maximum: 1e5 }))
466
466
  });
467
467
  loadEnvironmentConfiguration = Effect13.tryPromise({
468
468
  try: async () => {
@@ -472,7 +472,7 @@ var init_config = __esm(() => {
472
472
  if (!isLoopback2(host) && !allowRemote) {
473
473
  throw new Error("Remote relay binding is disabled. Use a private network or TLS reverse proxy, then set COHALL_RELAY_ALLOW_REMOTE=true.");
474
474
  }
475
- const dataDirectory = resolve5(process.env.COHALL_DATA_DIR ?? defaultDataDirectory());
475
+ const dataDirectory = resolve6(process.env.COHALL_DATA_DIR ?? defaultDataDirectory());
476
476
  await mkdir9(dataDirectory, { recursive: true, mode: 448 });
477
477
  if (platform5() !== "win32") {
478
478
  await chmod7(dataDirectory, 448);
@@ -482,7 +482,7 @@ var init_config = __esm(() => {
482
482
  throw new Error("The Cohall relay owner token must be at least 32 characters");
483
483
  }
484
484
  const historyTaskLimit = Number(process.env.COHALL_HISTORY_TASK_LIMIT ?? "1000");
485
- return Schema15.decodeUnknownSync(RelayConfiguration)({
485
+ return Schema16.decodeUnknownSync(RelayConfiguration)({
486
486
  host,
487
487
  port,
488
488
  token,
@@ -673,12 +673,12 @@ __export(exports_store, {
673
673
  RelayStore: () => exports_store,
674
674
  PersistenceError: () => PersistenceError
675
675
  });
676
- import { Context as Context2, Effect as Effect14, Layer as Layer2, Schema as Schema16 } from "effect";
676
+ import { Context as Context2, Effect as Effect14, Layer as Layer2, Schema as Schema17 } from "effect";
677
677
  import { createHash as createHash2, randomBytes } from "node:crypto";
678
678
  var PersistenceError, TaskProgressError, TaskInputError, TaskDeadlineError, TaskRequestError, Service2, operationError = (operation) => (cause) => new PersistenceError({
679
679
  operation,
680
680
  message: cause instanceof Error ? cause.message : String(cause)
681
- }), decode2 = (operation, schema, value) => Schema16.decodeUnknownEffect(schema)(value).pipe(Effect14.mapError(operationError(operation))), threadFromRow = (row) => decode2("RelayStore.decodeThread", Thread, {
681
+ }), decode2 = (operation, schema, value) => Schema17.decodeUnknownEffect(schema)(value).pipe(Effect14.mapError(operationError(operation))), threadFromRow = (row) => decode2("RelayStore.decodeThread", Thread, {
682
682
  id: row.id,
683
683
  title: row.title,
684
684
  createdAt: row.created_at,
@@ -777,7 +777,7 @@ var PersistenceError, TaskProgressError, TaskInputError, TaskDeadlineError, Task
777
777
  kind: row.kind,
778
778
  at: row.created_at,
779
779
  ...row.detail === null ? {} : { detail: row.detail }
780
- }), rolesFromRow = (row) => Schema16.decodeUnknownSync(Schema16.Array(ConnectionRole))(JSON.parse(row.roles_json)), authSessionFromRow = (row) => {
780
+ }), rolesFromRow = (row) => Schema17.decodeUnknownSync(Schema17.Array(ConnectionRole))(JSON.parse(row.roles_json)), authSessionFromRow = (row) => {
781
781
  const roles = rolesFromRow(row);
782
782
  const role = roles[0];
783
783
  return role === undefined ? Effect14.fail(new PersistenceError({
@@ -841,7 +841,7 @@ var PersistenceError, TaskProgressError, TaskInputError, TaskDeadlineError, Task
841
841
  }
842
842
  return events;
843
843
  }, interruptedTaskStatus = `CASE
844
- WHEN json_array_length(clarifications_json) > 0
844
+ WHEN provider = 'grok-bot' AND json_array_length(clarifications_json) > 0
845
845
  AND json_extract(clarifications_json, '$[#-1].answer') IS NULL THEN 'needs_input'
846
846
  ELSE 'queued' END`, makeService = (db, retainedTerminalTasks = 1000) => {
847
847
  const requestHash = (input) => {
@@ -1115,9 +1115,9 @@ var PersistenceError, TaskProgressError, TaskInputError, TaskDeadlineError, Task
1115
1115
  const devices = new Map;
1116
1116
  let retainedTasks = 0;
1117
1117
  for (const row of rows) {
1118
- const status = Schema16.decodeUnknownSync(TaskStatus)(row.status);
1119
- const provider = Schema16.decodeUnknownSync(Provider)(row.provider);
1120
- const deviceId = Schema16.decodeUnknownSync(DeviceId)(row.device_id);
1118
+ const status = Schema17.decodeUnknownSync(TaskStatus)(row.status);
1119
+ const provider = Schema17.decodeUnknownSync(Provider)(row.provider);
1120
+ const deviceId = Schema17.decodeUnknownSync(DeviceId)(row.device_id);
1121
1121
  retainedTasks += row.tasks;
1122
1122
  totalStatus[status] += row.tasks;
1123
1123
  totalProviders.set(provider, (totalProviders.get(provider) ?? 0) + row.tasks);
@@ -1509,7 +1509,8 @@ var PersistenceError, TaskProgressError, TaskInputError, TaskDeadlineError, Task
1509
1509
  const pendingTasksFor = Effect14.fn("RelayStore.pendingTasksFor")(function* (deviceId) {
1510
1510
  const rows = yield* Effect14.try({
1511
1511
  try: () => db.query(`SELECT * FROM tasks WHERE target_device_id = ?
1512
- AND status IN ('queued', 'cancelling') ORDER BY created_at, id LIMIT 100`).all(deviceId),
1512
+ AND status IN ('queued', 'cancelling')
1513
+ ORDER BY dispatched_at IS NULL, created_at, id LIMIT 100`).all(deviceId),
1513
1514
  catch: operationError("RelayStore.pendingTasksFor")
1514
1515
  });
1515
1516
  return yield* Effect14.forEach(rows, (row) => taskFromRow(db, row));
@@ -1909,7 +1910,7 @@ var PersistenceError, TaskProgressError, TaskInputError, TaskDeadlineError, Task
1909
1910
  if (pairing === null) {
1910
1911
  throw new Error("Pairing credential is invalid, expired, or already used");
1911
1912
  }
1912
- const roles = Schema16.decodeUnknownSync(Schema16.Array(ConnectionRole))(JSON.parse(pairing.roles_json));
1913
+ const roles = Schema17.decodeUnknownSync(Schema17.Array(ConnectionRole))(JSON.parse(pairing.roles_json));
1913
1914
  const deviceId = roles.includes("device") ? makeDeviceId() : undefined;
1914
1915
  const consumed = db.query("UPDATE auth_pairings SET used_at = ? WHERE token_hash = ? AND used_at IS NULL").run(timestamp, pairing.token_hash);
1915
1916
  if (consumed.changes !== 1) {
@@ -2183,19 +2184,19 @@ var init_store = __esm(() => {
2183
2184
  init_src();
2184
2185
  init_database();
2185
2186
  init_store();
2186
- PersistenceError = class PersistenceError extends Schema16.TaggedErrorClass()("RelayStore.PersistenceError", {
2187
- operation: Schema16.String,
2188
- message: Schema16.String,
2189
- missingRecord: Schema16.optionalKey(Schema16.Literals(["task", "operation"]))
2187
+ PersistenceError = class PersistenceError extends Schema17.TaggedErrorClass()("RelayStore.PersistenceError", {
2188
+ operation: Schema17.String,
2189
+ message: Schema17.String,
2190
+ missingRecord: Schema17.optionalKey(Schema17.Literals(["task", "operation"]))
2190
2191
  }) {
2191
2192
  };
2192
- TaskProgressError = class TaskProgressError extends Schema16.TaggedErrorClass()("RelayStore.TaskProgressError", { status: Schema16.Literals([403, 409]), message: Schema16.String }) {
2193
+ TaskProgressError = class TaskProgressError extends Schema17.TaggedErrorClass()("RelayStore.TaskProgressError", { status: Schema17.Literals([403, 409]), message: Schema17.String }) {
2193
2194
  };
2194
- TaskInputError = class TaskInputError extends Schema16.TaggedErrorClass()("RelayStore.TaskInputError", { status: Schema16.Literals([403, 409]), message: Schema16.String }) {
2195
+ TaskInputError = class TaskInputError extends Schema17.TaggedErrorClass()("RelayStore.TaskInputError", { status: Schema17.Literals([403, 409]), message: Schema17.String }) {
2195
2196
  };
2196
- TaskDeadlineError = class TaskDeadlineError extends Schema16.TaggedErrorClass()("RelayStore.TaskDeadlineError", { status: Schema16.Literals([400, 409]), message: Schema16.String }) {
2197
+ TaskDeadlineError = class TaskDeadlineError extends Schema17.TaggedErrorClass()("RelayStore.TaskDeadlineError", { status: Schema17.Literals([400, 409]), message: Schema17.String }) {
2197
2198
  };
2198
- TaskRequestError = class TaskRequestError extends Schema16.TaggedErrorClass()("RelayStore.TaskRequestError", { status: Schema16.Literals([409, 410]), message: Schema16.String }) {
2199
+ TaskRequestError = class TaskRequestError extends Schema17.TaggedErrorClass()("RelayStore.TaskRequestError", { status: Schema17.Literals([409, 410]), message: Schema17.String }) {
2199
2200
  };
2200
2201
  Service2 = class Service2 extends Context2.Service()("@cohall/RelayStore") {
2201
2202
  };
@@ -2211,7 +2212,7 @@ __export(exports_main, {
2211
2212
  canReadTaskAttachments: () => canReadTaskAttachments,
2212
2213
  canDispatchTaskToDevice: () => canDispatchTaskToDevice
2213
2214
  });
2214
- import { Effect as Effect15, ManagedRuntime, Schema as Schema17, Schedule as Schedule4 } from "effect";
2215
+ import { Effect as Effect15, ManagedRuntime, Schema as Schema18, Schedule as Schedule4 } from "effect";
2215
2216
  import { createHash as createHash3, timingSafeEqual } from "node:crypto";
2216
2217
  import { access as access6, chmod as chmod8 } from "node:fs/promises";
2217
2218
  import { createServer } from "node:http";
@@ -2242,7 +2243,7 @@ var RequestError, relayListenOptions = (configuration, environment = process.env
2242
2243
  if (request.method === "GET" || request.method === "HEAD") {
2243
2244
  return Promise.resolve(undefined);
2244
2245
  }
2245
- return new Promise((resolve6, reject) => {
2246
+ return new Promise((resolve7, reject) => {
2246
2247
  const chunks = [];
2247
2248
  let size = 0;
2248
2249
  const cleanup = () => {
@@ -2261,7 +2262,7 @@ var RequestError, relayListenOptions = (configuration, environment = process.env
2261
2262
  };
2262
2263
  const onEnd = () => {
2263
2264
  cleanup();
2264
- resolve6(Buffer.concat(chunks, size));
2265
+ resolve7(Buffer.concat(chunks, size));
2265
2266
  };
2266
2267
  const onError = (cause) => {
2267
2268
  cleanup();
@@ -2314,7 +2315,7 @@ Content-Length: 0\r
2314
2315
  }, body = (request, decode3) => Effect15.tryPromise({
2315
2316
  try: () => request.json(),
2316
2317
  catch: () => new RequestError({ status: 400, message: "Expected a JSON request body" })
2317
- }).pipe(Effect15.flatMap(decode3), Effect15.mapError((cause) => cause instanceof RequestError ? cause : new RequestError({ status: 400, message: String(cause).slice(0, 2048) }))), pathId = (schema, value) => Schema17.decodeUnknownEffect(schema)(value).pipe(Effect15.mapError(() => new RequestError({ status: 400, message: `Invalid identifier: ${value}` }))), scoreDevice = (device, input, sourceDeviceId) => {
2318
+ }).pipe(Effect15.flatMap(decode3), Effect15.mapError((cause) => cause instanceof RequestError ? cause : new RequestError({ status: 400, message: String(cause).slice(0, 2048) }))), pathId = (schema, value) => Schema18.decodeUnknownEffect(schema)(value).pipe(Effect15.mapError(() => new RequestError({ status: 400, message: `Invalid identifier: ${value}` }))), scoreDevice = (device, input, sourceDeviceId) => {
2318
2319
  const prompt = `${input.prompt} ${input.context ?? ""}`.toLowerCase();
2319
2320
  const needsXcode = /\b(xcode|ios|macos|swiftui|app store)\b/.test(prompt);
2320
2321
  const needsBrowser = /\b(browser|chrome|youtube|twitter|logged[- ]?in|signed[- ]?in|x\.com)\b/.test(prompt);
@@ -3011,11 +3012,11 @@ Content-Length: 0\r
3011
3012
  websocketServer.emit("connection", websocket, request);
3012
3013
  });
3013
3014
  });
3014
- await new Promise((resolve6, reject) => {
3015
+ await new Promise((resolve7, reject) => {
3015
3016
  server.once("error", reject);
3016
3017
  server.listen(relayListenOptions(configuration), () => {
3017
3018
  server.off("error", reject);
3018
- resolve6();
3019
+ resolve7();
3019
3020
  });
3020
3021
  });
3021
3022
  const address = server.address();
@@ -3044,7 +3045,7 @@ Content-Length: 0\r
3044
3045
  for (const socket of websocketServer.clients) {
3045
3046
  socket.close(1001, "Relay shutting down");
3046
3047
  }
3047
- await new Promise((resolve6) => server.close(() => resolve6()));
3048
+ await new Promise((resolve7) => server.close(() => resolve7()));
3048
3049
  websocketServer.close();
3049
3050
  await runtime.dispose();
3050
3051
  };
@@ -3056,9 +3057,9 @@ var init_main = __esm(async () => {
3056
3057
  init_config();
3057
3058
  init_hub();
3058
3059
  init_store();
3059
- RequestError = class RequestError extends Schema17.TaggedErrorClass()("Relay.RequestError", {
3060
- status: Schema17.Int,
3061
- message: Schema17.String
3060
+ RequestError = class RequestError extends Schema18.TaggedErrorClass()("Relay.RequestError", {
3061
+ status: Schema18.Int,
3062
+ message: Schema18.String
3062
3063
  }) {
3063
3064
  };
3064
3065
  maxTaskRequestBodyBytes = 3 * 1024 * 1024;
@@ -3361,10 +3362,10 @@ init_src();
3361
3362
  init_src();
3362
3363
  import { Effect as Effect3, Schema as Schema3 } from "effect";
3363
3364
  import { execa } from "execa";
3364
- import { accessSync, constants } from "node:fs";
3365
+ import { accessSync, constants, statSync } from "node:fs";
3365
3366
  import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
3366
3367
  import { homedir, platform, tmpdir } from "node:os";
3367
- import { delimiter, extname, isAbsolute, join } from "node:path";
3368
+ import { delimiter, extname, isAbsolute, join, resolve } from "node:path";
3368
3369
  import { execFile } from "node:child_process";
3369
3370
 
3370
3371
  class ProviderUnavailableError extends Schema3.TaggedErrorClass()("CohallProvider.Unavailable", { provider: Provider, message: Schema3.String }) {
@@ -3413,14 +3414,18 @@ var executableDirectories = () => {
3413
3414
  "/opt/homebrew/bin",
3414
3415
  "/usr/local/bin"
3415
3416
  ];
3416
- return [...new Set([...configured, ...common.filter((path) => path !== undefined)])];
3417
+ return [
3418
+ ...new Set([...configured, ...common.filter((path) => path !== undefined)].map((path) => resolve(path)))
3419
+ ];
3417
3420
  };
3418
3421
  var findExecutable = (command) => {
3419
3422
  const paths = isAbsolute(command) || command.includes("/") || command.includes("\\") ? [""] : executableDirectories();
3420
3423
  for (const directory of paths) {
3421
3424
  for (const candidate of executableCandidates(command)) {
3422
- const path = directory.length === 0 ? candidate : join(directory, candidate);
3425
+ const path = resolve(directory.length === 0 ? candidate : join(directory, candidate));
3423
3426
  try {
3427
+ if (!statSync(path).isFile())
3428
+ continue;
3424
3429
  accessSync(path, platform() === "win32" ? constants.F_OK : constants.X_OK);
3425
3430
  return path;
3426
3431
  } catch {
@@ -3432,7 +3437,7 @@ var findExecutable = (command) => {
3432
3437
  };
3433
3438
  var available = (provider) => provider !== "grok-bot" && findExecutable(executables[provider]) !== undefined;
3434
3439
  var availableProviders = () => Provider.literals.filter((provider) => provider !== "grok-bot").filter(available);
3435
- var boundedText = (stream, limit, onOverflow) => new Promise((resolve, reject) => {
3440
+ var boundedText = (stream, limit, onOverflow) => new Promise((resolve2, reject) => {
3436
3441
  const chunks = [];
3437
3442
  let size = 0;
3438
3443
  const cleanup = () => {
@@ -3453,7 +3458,7 @@ var boundedText = (stream, limit, onOverflow) => new Promise((resolve, reject) =
3453
3458
  };
3454
3459
  const onEnd = () => {
3455
3460
  cleanup();
3456
- resolve(Buffer.concat(chunks, size).toString("utf8"));
3461
+ resolve2(Buffer.concat(chunks, size).toString("utf8"));
3457
3462
  };
3458
3463
  const onError = (cause) => {
3459
3464
  cleanup();
@@ -3463,7 +3468,7 @@ var boundedText = (stream, limit, onOverflow) => new Promise((resolve, reject) =
3463
3468
  stream.once("end", onEnd);
3464
3469
  stream.once("error", onError);
3465
3470
  });
3466
- var captureText = (stream, limit) => new Promise((resolve, reject) => {
3471
+ var captureText = (stream, limit) => new Promise((resolve2, reject) => {
3467
3472
  const chunks = [];
3468
3473
  let captured = 0;
3469
3474
  let truncated = false;
@@ -3477,7 +3482,7 @@ var captureText = (stream, limit) => new Promise((resolve, reject) => {
3477
3482
  }
3478
3483
  truncated ||= bytes.byteLength > remaining;
3479
3484
  };
3480
- const onEnd = () => resolve({ text: Buffer.concat(chunks, captured).toString("utf8"), truncated });
3485
+ const onEnd = () => resolve2({ text: Buffer.concat(chunks, captured).toString("utf8"), truncated });
3481
3486
  stream.on("data", onData);
3482
3487
  stream.once("end", onEnd);
3483
3488
  stream.once("error", reject);
@@ -3766,13 +3771,13 @@ var waitForProcessGroup = async (pid, timeoutMs) => {
3766
3771
  if (Date.now() >= deadline) {
3767
3772
  return false;
3768
3773
  }
3769
- await new Promise((resolve) => setTimeout(resolve, 25));
3774
+ await new Promise((resolve2) => setTimeout(resolve2, 25));
3770
3775
  }
3771
3776
  return true;
3772
3777
  };
3773
- var terminateWindowsTree = (pid) => new Promise((resolve) => {
3778
+ var terminateWindowsTree = (pid) => new Promise((resolve2) => {
3774
3779
  const systemRoot = process.env.SystemRoot ?? "C:\\Windows";
3775
- execFile(join(systemRoot, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve());
3780
+ execFile(join(systemRoot, "System32", "taskkill.exe"), ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => resolve2());
3776
3781
  });
3777
3782
  var terminateProcessTree = async (pid) => {
3778
3783
  if (platform() === "win32") {
@@ -3847,9 +3852,9 @@ var run = (options) => Effect3.callback((resume, signal) => {
3847
3852
  terminate();
3848
3853
  }
3849
3854
  try {
3850
- const written = new Promise((resolve, reject) => {
3855
+ const written = new Promise((resolve2, reject) => {
3851
3856
  child.stdin.once("error", reject);
3852
- child.stdin.end(prepared.input, (cause) => cause === undefined || cause === null ? resolve() : reject(cause));
3857
+ child.stdin.end(prepared.input, (cause) => cause === undefined || cause === null ? resolve2() : reject(cause));
3853
3858
  });
3854
3859
  const [result, stderr, exitCode] = await Promise.all([
3855
3860
  parse(options, child.stdout, terminate),
@@ -3903,10 +3908,10 @@ var run = (options) => Effect3.callback((resume, signal) => {
3903
3908
  });
3904
3909
 
3905
3910
  // apps/device/src/cli.ts
3906
- import { Effect as Effect10, Schema as Schema12 } from "effect";
3911
+ import { Effect as Effect10, Schema as Schema13 } from "effect";
3907
3912
  import { access as access4, mkdir as mkdir8, open as open5, stat as stat4, writeFile as writeFile8 } from "node:fs/promises";
3908
3913
  import { homedir as homedir4 } from "node:os";
3909
- import { dirname as dirname6, join as join9, resolve as resolve4 } from "node:path";
3914
+ import { dirname as dirname6, join as join9, resolve as resolve5 } from "node:path";
3910
3915
 
3911
3916
  // skills/cohall/SKILL.md
3912
3917
  var SKILL_default = `---
@@ -4296,7 +4301,7 @@ init_src();
4296
4301
  import { Effect as Effect4, Schema as Schema4 } from "effect";
4297
4302
  import { access, chmod as chmod2, mkdir, readFile, realpath, rename, stat, writeFile as writeFile2 } from "node:fs/promises";
4298
4303
  import { homedir as homedir2, hostname, platform as platform2 } from "node:os";
4299
- import { dirname, isAbsolute as isAbsolute2, join as join2, resolve } from "node:path";
4304
+ import { dirname, isAbsolute as isAbsolute2, join as join2, resolve as resolve2 } from "node:path";
4300
4305
  var WorkspaceList = Schema4.Array(Schema4.NonEmptyString).check(Schema4.isMaxLength(64));
4301
4306
  var ProviderList = Schema4.Array(Provider).check(Schema4.isMinLength(1)).check(Schema4.isMaxLength(Provider.literals.length));
4302
4307
  var Sandbox = Schema4.Literals(["read-only", "workspace-write", "danger-full-access"]);
@@ -4304,7 +4309,7 @@ var StoredConfiguration = Schema4.Struct({
4304
4309
  version: Schema4.Literal(1),
4305
4310
  relayUrl: Schema4.NonEmptyString,
4306
4311
  deviceId: DeviceId,
4307
- deviceName: Schema4.NonEmptyString,
4312
+ deviceName: Device.fields.name,
4308
4313
  workspaces: WorkspaceList,
4309
4314
  clientToken: Schema4.optionalKey(Schema4.NonEmptyString),
4310
4315
  deviceToken: Schema4.optionalKey(Schema4.NonEmptyString),
@@ -4313,6 +4318,10 @@ var StoredConfiguration = Schema4.Struct({
4313
4318
  sandbox: Schema4.optionalKey(Sandbox),
4314
4319
  grokGateway: Schema4.optionalKey(Schema4.NonEmptyString)
4315
4320
  });
4321
+ var ReadableConfiguration = Schema4.Struct({
4322
+ ...StoredConfiguration.fields,
4323
+ deviceName: Schema4.NonEmptyString
4324
+ });
4316
4325
  var ClientConfiguration = Schema4.Struct({
4317
4326
  relayUrl: Schema4.NonEmptyString,
4318
4327
  token: Schema4.NonEmptyString,
@@ -4324,7 +4333,7 @@ var DeviceConfiguration = Schema4.Struct({
4324
4333
  relayUrl: Schema4.NonEmptyString,
4325
4334
  token: Schema4.NonEmptyString,
4326
4335
  id: DeviceId,
4327
- name: Schema4.NonEmptyString,
4336
+ name: Device.fields.name,
4328
4337
  workspaces: WorkspaceList,
4329
4338
  providers: Schema4.optionalKey(ProviderList),
4330
4339
  model: Schema4.optionalKey(Schema4.NonEmptyString),
@@ -4351,8 +4360,8 @@ var defaultRelayDataDirectory = () => {
4351
4360
  const dataHome = process.env.XDG_DATA_HOME;
4352
4361
  return join2(dataHome !== undefined && isAbsolute2(dataHome) ? dataHome : join2(homedir2(), ".local", "share"), "cohall");
4353
4362
  };
4354
- var relayDataDirectory = () => resolve(process.env.COHALL_DATA_DIR ?? defaultRelayDataDirectory());
4355
- var configurationPath = () => resolve(process.env.COHALL_CONFIG ?? join2(defaultConfigDirectory(), "config.json"));
4363
+ var relayDataDirectory = () => resolve2(process.env.COHALL_DATA_DIR ?? defaultRelayDataDirectory());
4364
+ var configurationPath = () => resolve2(process.env.COHALL_CONFIG ?? join2(defaultConfigDirectory(), "config.json"));
4356
4365
  var normalizeRelayUrl = (input) => {
4357
4366
  const url = new URL(input);
4358
4367
  if (url.protocol !== "http:" && url.protocol !== "https:") {
@@ -4371,7 +4380,7 @@ var parseWorkspaces = (workspaceList, workspaceJson) => Effect4.tryPromise({
4371
4380
  try: async () => {
4372
4381
  const values = workspaceJson === undefined ? workspaceList.split(",").map((workspace) => workspace.trim()).filter((workspace) => workspace.length > 0) : Schema4.decodeUnknownSync(WorkspaceList)(JSON.parse(workspaceJson));
4373
4382
  const canonical = await Promise.all(values.map(async (workspace) => {
4374
- const path = await realpath(resolve(workspace));
4383
+ const path = await realpath(resolve2(workspace));
4375
4384
  if (!(await stat(path)).isDirectory()) {
4376
4385
  throw new Error(`Not a directory: ${workspace}`);
4377
4386
  }
@@ -4393,7 +4402,7 @@ var readStoredConfiguration = async () => {
4393
4402
  await chmod2(path, 384);
4394
4403
  }
4395
4404
  try {
4396
- return Schema4.decodeUnknownSync(StoredConfiguration)(JSON.parse(await readFile(path, "utf8")));
4405
+ return Schema4.decodeUnknownSync(ReadableConfiguration)(JSON.parse(await readFile(path, "utf8")));
4397
4406
  } catch (cause) {
4398
4407
  throw new Error(`Invalid Cohall configuration at ${path}: ${String(cause)}`);
4399
4408
  }
@@ -4463,7 +4472,7 @@ var environmentProviders = (stored) => {
4463
4472
  };
4464
4473
  var storedOrDefaults = async () => {
4465
4474
  const stored = await readStoredConfiguration();
4466
- return stored ?? StoredConfiguration.make({
4475
+ return stored ?? ReadableConfiguration.make({
4467
4476
  version: 1,
4468
4477
  relayUrl: "http://127.0.0.1:8787",
4469
4478
  deviceId: makeDeviceId(),
@@ -4534,7 +4543,7 @@ var loadDeviceConfiguration = Effect4.tryPromise({
4534
4543
  ...providers === undefined ? {} : { providers },
4535
4544
  ...model === undefined ? {} : { model },
4536
4545
  ...sandbox === undefined ? {} : { sandbox },
4537
- ...grokGateway === undefined ? {} : { grokGateway: resolve(grokGateway) }
4546
+ ...grokGateway === undefined ? {} : { grokGateway: resolve2(grokGateway) }
4538
4547
  });
4539
4548
  },
4540
4549
  catch: (cause) => cause instanceof Error ? cause : new Error(String(cause))
@@ -4818,6 +4827,7 @@ var allDeviceHealth = (devices, localVersion) => {
4818
4827
  // apps/device/src/grok-bot.ts
4819
4828
  init_src();
4820
4829
  import { Effect as Effect6, Schedule as Schedule2, Schema as Schema7 } from "effect";
4830
+ import { constants as constants2 } from "node:fs";
4821
4831
  import { open as open2 } from "node:fs/promises";
4822
4832
  import { isIP } from "node:net";
4823
4833
 
@@ -5026,6 +5036,24 @@ var cleanupBotReply = async (taskId, runId) => {
5026
5036
  }
5027
5037
  };
5028
5038
 
5039
+ // apps/device/src/bounded-file.ts
5040
+ var readBoundedFile = async (handle, limit) => {
5041
+ const buffer = Buffer.allocUnsafe(limit + 1);
5042
+ let size = 0;
5043
+ while (size < buffer.length) {
5044
+ const { bytesRead } = await handle.read({
5045
+ buffer,
5046
+ offset: size,
5047
+ length: buffer.length - size,
5048
+ position: null
5049
+ });
5050
+ if (bytesRead === 0)
5051
+ break;
5052
+ size += bytesRead;
5053
+ }
5054
+ return buffer.subarray(0, size);
5055
+ };
5056
+
5029
5057
  // apps/device/src/grok-bot.ts
5030
5058
  var maxResponseBytes = 4 * 1024 * 1024;
5031
5059
  var maxDiscoveryBytes = 64 * 1024;
@@ -5064,13 +5092,15 @@ var decode = (schema, value, label) => {
5064
5092
  };
5065
5093
  var readConnection = async (path) => {
5066
5094
  const value = await (async () => {
5067
- const file = await open2(path, "r");
5095
+ const file = await open2(path, constants2.O_RDONLY | (process.platform === "win32" ? 0 : constants2.O_NONBLOCK));
5068
5096
  try {
5069
- const buffer = Buffer.alloc(maxDiscoveryBytes + 1);
5070
- const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
5071
- if (bytesRead > maxDiscoveryBytes)
5097
+ const metadata = await file.stat();
5098
+ if (!metadata.isFile())
5099
+ throw new Error("Discovery must be a regular file");
5100
+ const buffer = await readBoundedFile(file, maxDiscoveryBytes);
5101
+ if (buffer.length > maxDiscoveryBytes)
5072
5102
  throw new Error("Discovery file exceeds its size limit");
5073
- return decode(Discovery, JSON.parse(buffer.subarray(0, bytesRead).toString("utf8")), "discovery file");
5103
+ return decode(Discovery, JSON.parse(buffer.toString("utf8")), "discovery file");
5074
5104
  } finally {
5075
5105
  await file.close();
5076
5106
  }
@@ -5288,7 +5318,8 @@ var runGrokBot = async (path, task, signal, supportsClarification = false) => {
5288
5318
  };
5289
5319
 
5290
5320
  // apps/device/src/setup.ts
5291
- import { Effect as Effect7 } from "effect";
5321
+ init_src();
5322
+ import { Effect as Effect7, Schema as Schema8 } from "effect";
5292
5323
  import { hostname as hostname2 } from "node:os";
5293
5324
  import { Writable } from "node:stream";
5294
5325
  import { createInterface } from "node:readline/promises";
@@ -5374,8 +5405,9 @@ var guidedSetupInput = async (options, prompter) => {
5374
5405
  const root = await prompter.answer("Workspace root", existing?.workspaces[0] ?? options.cwd);
5375
5406
  workspaces = existing !== undefined && root === existing.workspaces[0] ? existing.workspaces : [root];
5376
5407
  }
5377
- const deviceName = options.clientOnly ? undefined : options.deviceName ?? await prompter.answer("Device name", existing?.deviceName ?? hostname2());
5378
- const providers = options.providers ?? (options.clientOnly ? existing?.providers?.join(",") ?? "auto" : await prompter.answer("Providers", existing?.providers?.join(",") ?? "auto"));
5408
+ const deviceName = options.clientOnly ? undefined : Schema8.decodeUnknownSync(Device.fields.name)(options.deviceName ?? await prompter.answer("Device name", existing?.deviceName ?? hostname2()));
5409
+ const providerInput = options.providers ?? (options.clientOnly ? existing?.providers?.join(",") ?? "auto" : await prompter.answer("Providers", existing?.providers?.join(",") ?? "auto"));
5410
+ const providers = providerInput === "auto" ? "auto" : parseProviders(providerInput);
5379
5411
  const token = options.readToken === undefined ? hasRequiredCredentials ? undefined : await prompter.secret("Pairing token") : await options.readToken();
5380
5412
  if (!hasRequiredCredentials && (token === undefined || token.length === 0)) {
5381
5413
  throw new Error("A pairing token is required");
@@ -5395,7 +5427,7 @@ var guidedSetupInput = async (options, prompter) => {
5395
5427
 
5396
5428
  // apps/device/src/relay-migration.ts
5397
5429
  init_src();
5398
- import { Effect as Effect8, Schema as Schema9 } from "effect";
5430
+ import { Effect as Effect8, Schema as Schema10 } from "effect";
5399
5431
  import { createHash } from "node:crypto";
5400
5432
  import { createReadStream } from "node:fs";
5401
5433
  import {
@@ -5412,8 +5444,9 @@ import {
5412
5444
  stat as stat3,
5413
5445
  writeFile as writeFile5
5414
5446
  } from "node:fs/promises";
5415
- import { basename, dirname as dirname5, join as join6, resolve as resolve3 } from "node:path";
5447
+ import { basename, dirname as dirname5, join as join6, resolve as resolve4 } from "node:path";
5416
5448
  import { backup as sqliteBackup, DatabaseSync } from "node:sqlite";
5449
+ import { isDeepStrictEqual } from "node:util";
5417
5450
  import { WebSocket } from "ws";
5418
5451
 
5419
5452
  // apps/device/src/service.ts
@@ -5423,9 +5456,9 @@ import { homedir as homedir3 } from "node:os";
5423
5456
  import { dirname as dirname4, isAbsolute as isAbsolute4, join as join5 } from "node:path";
5424
5457
 
5425
5458
  // apps/device/src/upgrade.ts
5426
- import { Schema as Schema8 } from "effect";
5459
+ import { Schema as Schema9 } from "effect";
5427
5460
  import { execa as execa2 } from "execa";
5428
- import { constants as constants2 } from "node:fs";
5461
+ import { constants as constants3 } from "node:fs";
5429
5462
  import {
5430
5463
  access as access2,
5431
5464
  chmod as chmod4,
@@ -5438,7 +5471,7 @@ import {
5438
5471
  stat as stat2,
5439
5472
  writeFile as writeFile3
5440
5473
  } from "node:fs/promises";
5441
- import { delimiter as delimiter2, dirname as dirname3, extname as extname2, isAbsolute as isAbsolute3, join as join4, relative, resolve as resolve2 } from "node:path";
5474
+ import { delimiter as delimiter2, dirname as dirname3, extname as extname2, isAbsolute as isAbsolute3, join as join4, relative, resolve as resolve3 } from "node:path";
5442
5475
  import { platform as operatingSystem } from "node:os";
5443
5476
  var packageName = "@akshar5/cohall";
5444
5477
  var minimumBunLookupVersion = "1.2.15";
@@ -5486,14 +5519,14 @@ var compareVersions = (left, right) => {
5486
5519
  }
5487
5520
  return 0;
5488
5521
  };
5489
- var PackageManager = Schema8.Literals(["npm", "bun", "pnpm"]);
5490
- var RestartReceipt = Schema8.Struct({
5491
- version: Schema8.String,
5492
- fromVersion: Schema8.String,
5522
+ var PackageManager = Schema9.Literals(["npm", "bun", "pnpm"]);
5523
+ var RestartReceipt = Schema9.Struct({
5524
+ version: Schema9.String,
5525
+ fromVersion: Schema9.String,
5493
5526
  packageManager: PackageManager,
5494
- pendingServices: Schema8.Array(Schema8.String),
5495
- restartedServices: Schema8.Array(Schema8.String),
5496
- restartingService: Schema8.optionalKey(Schema8.String)
5527
+ pendingServices: Schema9.Array(Schema9.String),
5528
+ restartedServices: Schema9.Array(Schema9.String),
5529
+ restartingService: Schema9.optionalKey(Schema9.String)
5497
5530
  });
5498
5531
  var pnpmEnvironment = () => Object.fromEntries([
5499
5532
  ["COREPACK_ENABLE_PROJECT_SPEC", "0"],
@@ -5541,7 +5574,7 @@ var packageInstallation = (canonicalEntrypoint, entrypoint = canonicalEntrypoint
5541
5574
  var resolvePackageInstallation = async (entrypoint, options = {}) => {
5542
5575
  const canonicalEntrypoint = await realpath2(entrypoint);
5543
5576
  const runtimePlatform = options.platform ?? process.platform;
5544
- const installation = packageInstallation(canonicalEntrypoint, resolve2(entrypoint), runtimePlatform);
5577
+ const installation = packageInstallation(canonicalEntrypoint, resolve3(entrypoint), runtimePlatform);
5545
5578
  if (installation.manager !== "pnpm") {
5546
5579
  const prefix = installation.prefix;
5547
5580
  if (installation.manager === "npm" && prefix !== undefined) {
@@ -5571,7 +5604,7 @@ var resolvePackageInstallation = async (entrypoint, options = {}) => {
5571
5604
  }) === canonicalEntrypoint)
5572
5605
  return {
5573
5606
  manager: "bun",
5574
- entrypoint: resolve2(entrypoint),
5607
+ entrypoint: resolve3(entrypoint),
5575
5608
  canonicalEntrypoint,
5576
5609
  globalDir: root2,
5577
5610
  pnpmExecutable: undefined,
@@ -5594,8 +5627,8 @@ var resolvePackageInstallation = async (entrypoint, options = {}) => {
5594
5627
  }, 1e4);
5595
5628
  const reported = normalizePath(result.stdout.trim().split(/\r?\n/).at(-1)?.trim() ?? "");
5596
5629
  const root = reported.endsWith("/node_modules") ? dirname3(reported) : reported;
5597
- const selected = resolve2(globalRoot);
5598
- const configured = isAbsolute3(root) ? resolve2(root) : undefined;
5630
+ const selected = resolve3(globalRoot);
5631
+ const configured = isAbsolute3(root) ? resolve3(root) : undefined;
5599
5632
  if (configured === undefined || (process.platform === "win32" ? selected.toLowerCase() !== configured.toLowerCase() : selected !== configured))
5600
5633
  throw globalEntrypointError();
5601
5634
  const packageEntry = (root2) => join4(root2, "node_modules", packageName, "bin", "cohall.js");
@@ -5695,11 +5728,11 @@ var isTrustedGroupWritablePath = (options) => {
5695
5728
  var validateExecutable = async (candidate, installationRoot, preserveSymlink = false) => {
5696
5729
  const canonical = await realpath2(candidate);
5697
5730
  if (operatingSystem() === "win32") {
5698
- return preserveSymlink ? resolve2(candidate) : canonical;
5731
+ return preserveSymlink ? resolve3(candidate) : canonical;
5699
5732
  }
5700
5733
  const uid = process.getuid?.();
5701
5734
  const writableRoot = installationRoot === undefined ? undefined : await realpath2(installationRoot);
5702
- for (const executablePath of preserveSymlink ? [canonical, resolve2(candidate)] : [canonical]) {
5735
+ for (const executablePath of preserveSymlink ? [canonical, resolve3(candidate)] : [canonical]) {
5703
5736
  for (let path = executablePath;; path = dirname3(path)) {
5704
5737
  const metadata = await stat2(path);
5705
5738
  const trustedGroupWritablePath = isTrustedGroupWritablePath({
@@ -5723,13 +5756,13 @@ var validateExecutable = async (candidate, installationRoot, preserveSymlink = f
5723
5756
  }
5724
5757
  }
5725
5758
  }
5726
- return preserveSymlink ? resolve2(candidate) : canonical;
5759
+ return preserveSymlink ? resolve3(candidate) : canonical;
5727
5760
  };
5728
5761
  var trustedExecutable = async (command, options = {}) => {
5729
5762
  const candidates = isAbsolute3(command) ? [command] : (process.env.PATH ?? "").split(delimiter2).filter(Boolean).flatMap((directory) => executableNames(command).map((name) => join4(directory, name)));
5730
5763
  let failure;
5731
5764
  for (const path of candidates) {
5732
- const available2 = await access2(path, operatingSystem() === "win32" ? constants2.F_OK : constants2.X_OK).then(() => true).catch(() => false);
5765
+ const available2 = await access2(path, operatingSystem() === "win32" ? constants3.F_OK : constants3.X_OK).then(() => true).catch(() => false);
5733
5766
  if (!available2)
5734
5767
  continue;
5735
5768
  try {
@@ -5775,9 +5808,9 @@ var trustedServices = async (services, resolveExecutable) => {
5775
5808
  }
5776
5809
  return secured;
5777
5810
  };
5778
- var ScheduledTaskAction = Schema8.Struct({
5779
- Execute: Schema8.NonEmptyString,
5780
- Arguments: Schema8.NonEmptyString
5811
+ var ScheduledTaskAction = Schema9.Struct({
5812
+ Execute: Schema9.NonEmptyString,
5813
+ Arguments: Schema9.NonEmptyString
5781
5814
  });
5782
5815
  var powershellLiteral = "(?:[^'\\r\\n]|'')+";
5783
5816
  var scheduledTaskBootstrap = new RegExp([
@@ -5794,7 +5827,7 @@ var scheduledTaskEntrypoint = (output) => {
5794
5827
  } catch {
5795
5828
  return;
5796
5829
  }
5797
- const decoded = Schema8.decodeUnknownOption(ScheduledTaskAction)(value);
5830
+ const decoded = Schema9.decodeUnknownOption(ScheduledTaskAction)(value);
5798
5831
  if (decoded._tag === "None")
5799
5832
  return;
5800
5833
  const action = decoded.value;
@@ -5950,7 +5983,7 @@ ${result.stderr}`);
5950
5983
  throw new Error(`Could not resolve the executable used by active ${service.label}: ${cause instanceof Error ? cause.message : String(cause)}`);
5951
5984
  });
5952
5985
  if (canonicalServiceEntrypoint === installation.canonicalEntrypoint) {
5953
- const servicePath = resolve2(serviceEntrypoint);
5986
+ const servicePath = resolve3(serviceEntrypoint);
5954
5987
  const sameEntrypoint = service.manager === "scheduled-task" ? servicePath.toLowerCase() === installation.entrypoint.toLowerCase() : servicePath === installation.entrypoint;
5955
5988
  if (installation.manager === "pnpm" && !sameEntrypoint)
5956
5989
  throw new Error(`Active ${service.label} is pinned to a pnpm package directory that changes during upgrades. ${service.device ? "Run cohall service install through the global cohall command before upgrading." : `Update the relay service executable to ${installation.entrypoint} before upgrading.`}`);
@@ -5959,7 +5992,7 @@ ${result.stderr}`);
5959
5992
  throw new Error(`Active ${service.label} uses ${serviceEntrypoint}, but this Cohall CLI uses ${installation.entrypoint}. Run the service executable's upgrade command so its installation is updated before restart.`);
5960
5993
  }
5961
5994
  };
5962
- var readReceipt = async (path) => readFile2(path, "utf8").then((content) => Schema8.decodeUnknownOption(RestartReceipt)(JSON.parse(content))).then((decoded) => decoded._tag === "Some" ? decoded.value : undefined).catch(() => {
5995
+ var readReceipt = async (path) => readFile2(path, "utf8").then((content) => Schema9.decodeUnknownOption(RestartReceipt)(JSON.parse(content))).then((decoded) => decoded._tag === "Some" ? decoded.value : undefined).catch(() => {
5963
5996
  return;
5964
5997
  });
5965
5998
  var writeReceipt = async (path, value) => {
@@ -6035,7 +6068,9 @@ var upgrade = async (options) => {
6035
6068
  platform: runtimePlatform,
6036
6069
  ...options.resolveExecutable === undefined ? {} : { resolveExecutable }
6037
6070
  });
6038
- if (previous?.version === options.currentVersion && (target === "latest" || target === previous.version)) {
6071
+ if (previous?.version === options.currentVersion && (target === previous.version || target === "latest" && options.restart) && await installedVersion(installation.entrypoint).catch(() => {
6072
+ return;
6073
+ }) === previous.version) {
6039
6074
  const pending = candidates.filter((service) => previous.pendingServices.includes(service.id));
6040
6075
  const active = await activeServices(runner, pending);
6041
6076
  await assertServiceInstallations(runner, active, installation);
@@ -6140,7 +6175,7 @@ var upgrade = async (options) => {
6140
6175
  requested_version: target,
6141
6176
  package_manager: installation.manager,
6142
6177
  services_restarted: [],
6143
- services_pending_restart: [],
6178
+ services_pending_restart: previous?.pendingServices ?? [],
6144
6179
  resumed_after_restart: false,
6145
6180
  dry_run: options.dryRun
6146
6181
  };
@@ -6214,6 +6249,7 @@ var deviceServicePlan = (options) => {
6214
6249
  const pnpmHome = options.pnpm?.home ?? (options.platform === "darwin" ? join5(options.home, "Library", "pnpm") : join5(options.home, ".local", "share", "pnpm"));
6215
6250
  const servicePath = [
6216
6251
  dirname4(options.nodeExecutable),
6252
+ ...options.npmPrefix === undefined ? [] : [join5(options.npmPrefix, "bin")],
6217
6253
  join5(options.home, ".local", "bin"),
6218
6254
  join5(options.home, ".npm-global", "bin"),
6219
6255
  join5(options.home, ".bun", "bin"),
@@ -6331,8 +6367,8 @@ ${options.pnpm === undefined ? "" : ` <key>PNPM_HOME</key>
6331
6367
  var defaultRunner2 = {
6332
6368
  run: async (command, arguments_, timeoutMs = 60000) => {
6333
6369
  const executable = await trustedExecutable(command);
6334
- return new Promise((resolve3) => {
6335
- execFile2(executable, [...arguments_], { encoding: "utf8", maxBuffer: 1024 * 1024, timeout: timeoutMs, windowsHide: true }, (error, stdout, stderr) => resolve3({
6370
+ return new Promise((resolve4) => {
6371
+ execFile2(executable, [...arguments_], { encoding: "utf8", maxBuffer: 1024 * 1024, timeout: timeoutMs, windowsHide: true }, (error, stdout, stderr) => resolve4({
6336
6372
  exitCode: typeof error?.code === "number" ? error.code : error === null ? 0 : 1,
6337
6373
  stdout,
6338
6374
  stderr,
@@ -6349,11 +6385,12 @@ var checked2 = async (runner, command, arguments_, allowFailure = false) => {
6349
6385
  throw new Error(`${command} failed: ${result.stderr.trim() || result.stdout.trim() || result.error || `status ${result.exitCode}`}`);
6350
6386
  };
6351
6387
  var installDeviceService = async (options = {}) => {
6352
- const { entrypoint, canonicalEntrypoint, pnpmExecutable, globalDir, globalRoot } = await resolvePackageInstallation(options.entrypoint ?? process.argv[1] ?? "", {
6388
+ const installation = await resolvePackageInstallation(options.entrypoint ?? process.argv[1] ?? "", {
6353
6389
  ...options.platform === undefined ? {} : { platform: options.platform },
6354
6390
  ...options.runner === undefined ? {} : { runner: options.runner },
6355
6391
  ...options.resolveExecutable === undefined ? {} : { resolveExecutable: options.resolveExecutable }
6356
6392
  });
6393
+ const { entrypoint, canonicalEntrypoint, pnpmExecutable, globalDir, globalRoot } = installation;
6357
6394
  const platform4 = options.platform ?? process.platform;
6358
6395
  const home = options.home ?? homedir3();
6359
6396
  const pnpm = pnpmExecutable === undefined || globalDir === undefined || globalRoot === undefined ? undefined : {
@@ -6399,6 +6436,7 @@ var installDeviceService = async (options = {}) => {
6399
6436
  home,
6400
6437
  nodeExecutable: process.execPath,
6401
6438
  configPath: configurationPath(),
6439
+ ...installation.manager === "npm" && installation.prefix !== undefined ? { npmPrefix: installation.prefix } : {},
6402
6440
  ...pnpm === undefined ? {} : { pnpm },
6403
6441
  ...uid === undefined ? {} : { uid }
6404
6442
  });
@@ -6431,10 +6469,10 @@ ${check.stderr}`)) {
6431
6469
  };
6432
6470
 
6433
6471
  // apps/device/src/relay-migration.ts
6434
- var sha256 = Schema9.String.check(Schema9.isPattern(/^[a-f0-9]{64}$/, { expected: "a lowercase SHA-256 digest" }));
6435
- var RelayBackupManifest = Schema9.Struct({
6436
- formatVersion: Schema9.Literal(1),
6437
- cohallVersion: Schema9.NonEmptyString,
6472
+ var sha256 = Schema10.String.check(Schema10.isPattern(/^[a-f0-9]{64}$/, { expected: "a lowercase SHA-256 digest" }));
6473
+ var RelayBackupManifest = Schema10.Struct({
6474
+ formatVersion: Schema10.Literal(1),
6475
+ cohallVersion: Schema10.NonEmptyString,
6438
6476
  createdAt: Timestamp,
6439
6477
  databaseSha256: sha256,
6440
6478
  ownerTokenSha256: sha256
@@ -6458,7 +6496,7 @@ var verifyBackupMember = async (path, maximumBytes) => {
6458
6496
  };
6459
6497
  var readManifest = async (path) => {
6460
6498
  await verifyBackupMember(path, 16384);
6461
- return Schema9.decodeUnknownSync(RelayBackupManifest)(JSON.parse(await readFile3(path, "utf8")));
6499
+ return Schema10.decodeUnknownSync(RelayBackupManifest)(JSON.parse(await readFile3(path, "utf8")));
6462
6500
  };
6463
6501
  var verifyBackupDestinationParent = async (path) => {
6464
6502
  if (process.platform === "win32") {
@@ -6508,7 +6546,7 @@ var backupRelay = async (destinationInput) => {
6508
6546
  if (!await exists(sourceDatabase)) {
6509
6547
  throw new Error(`Relay database was not found at ${sourceDatabase}`);
6510
6548
  }
6511
- const destination = resolve3(destinationInput);
6549
+ const destination = resolve4(destinationInput);
6512
6550
  if (await exists(destination)) {
6513
6551
  throw new Error(`Backup destination already exists: ${destination}`);
6514
6552
  }
@@ -6555,7 +6593,7 @@ var backupRelay = async (destinationInput) => {
6555
6593
  }
6556
6594
  };
6557
6595
  var restoreRelay = async (sourceInput) => {
6558
- const source = resolve3(sourceInput);
6596
+ const source = resolve4(sourceInput);
6559
6597
  const sourceDatabase = join6(source, "cohall.db");
6560
6598
  const sourceOwnerToken = join6(source, "owner-token");
6561
6599
  const sourceManifest = join6(source, "manifest.json");
@@ -6650,7 +6688,7 @@ var verifyLegacyDeviceCredential = (relayUrl, token) => new Promise((resolveProm
6650
6688
  });
6651
6689
  socket.on("message", (data) => {
6652
6690
  try {
6653
- const event = Schema9.decodeUnknownSync(SocketEvent)(JSON.parse(data.toString()));
6691
+ const event = Schema10.decodeUnknownSync(SocketEvent)(JSON.parse(data.toString()));
6654
6692
  if (event._tag === "Connected") {
6655
6693
  finish();
6656
6694
  } else if (event._tag === "Error") {
@@ -6700,6 +6738,9 @@ var switchRelay = async (options) => {
6700
6738
  }
6701
6739
  roles.push("device");
6702
6740
  }
6741
+ if (!isDeepStrictEqual(await readStoredConfiguration(), configuration)) {
6742
+ throw new Error("Cohall configuration changed during relay verification. Retry the command.");
6743
+ }
6703
6744
  const updated = configuration.relayUrl !== relayUrl;
6704
6745
  if (updated) {
6705
6746
  await writeStoredConfiguration(StoredConfiguration.make({ ...configuration, relayUrl }));
@@ -6723,38 +6764,18 @@ var switchRelay = async (options) => {
6723
6764
 
6724
6765
  // apps/device/src/task-attachments.ts
6725
6766
  init_src();
6726
- import { Effect as Effect9, Schema as Schema10 } from "effect";
6727
- import { constants as constants3 } from "node:fs";
6767
+ import { Effect as Effect9, Schema as Schema11 } from "effect";
6768
+ import { constants as constants4 } from "node:fs";
6728
6769
  import { lstat as lstat2, mkdtemp as mkdtemp3, mkdir as mkdir6, open as open3, readdir as readdir2, rm as rm4, writeFile as writeFile6 } from "node:fs/promises";
6729
6770
  import { tmpdir as tmpdir2 } from "node:os";
6730
6771
  import { basename as basename2, join as join7 } from "node:path";
6731
-
6732
- // apps/device/src/bounded-file.ts
6733
- var readBoundedFile = async (handle, limit) => {
6734
- const buffer = Buffer.allocUnsafe(limit + 1);
6735
- let size = 0;
6736
- while (size < buffer.length) {
6737
- const { bytesRead } = await handle.read({
6738
- buffer,
6739
- offset: size,
6740
- length: buffer.length - size,
6741
- position: null
6742
- });
6743
- if (bytesRead === 0)
6744
- break;
6745
- size += bytesRead;
6746
- }
6747
- return buffer.subarray(0, size);
6748
- };
6749
-
6750
- // apps/device/src/task-attachments.ts
6751
6772
  var readInputAttachments = async (paths2) => {
6752
6773
  if (paths2.length > maxTaskAttachments) {
6753
6774
  throw new Error(`A task supports at most ${maxTaskAttachments} input files`);
6754
6775
  }
6755
6776
  const names = new Set;
6756
6777
  return Promise.all(paths2.map(async (path) => {
6757
- const name = Schema10.decodeUnknownSync(AttachmentName)(basename2(path));
6778
+ const name = Schema11.decodeUnknownSync(AttachmentName)(basename2(path));
6758
6779
  const key = name.normalize("NFC").toLocaleLowerCase("en-US");
6759
6780
  if (names.has(key)) {
6760
6781
  throw new Error(`Attachment name ${name} is repeated`);
@@ -6764,7 +6785,7 @@ var readInputAttachments = async (paths2) => {
6764
6785
  if (!source.isFile()) {
6765
6786
  throw new Error(`Attachment ${name} must be a regular file`);
6766
6787
  }
6767
- const handle = await open3(path, constants3.O_RDONLY | (process.platform === "win32" ? 0 : constants3.O_NOFOLLOW | constants3.O_NONBLOCK));
6788
+ const handle = await open3(path, constants4.O_RDONLY | (process.platform === "win32" ? 0 : constants4.O_NOFOLLOW | constants4.O_NONBLOCK));
6768
6789
  try {
6769
6790
  const metadata = await handle.stat();
6770
6791
  if (!metadata.isFile() || metadata.dev !== source.dev || metadata.ino !== source.ino || metadata.size < 1 || metadata.size > maxAttachmentBytes) {
@@ -6812,7 +6833,7 @@ var collectOutputs = async (directory) => {
6812
6833
  const files = [];
6813
6834
  const names = new Set;
6814
6835
  for (const entry of entries) {
6815
- const name = Schema10.decodeUnknownSync(AttachmentName)(entry.name);
6836
+ const name = Schema11.decodeUnknownSync(AttachmentName)(entry.name);
6816
6837
  if (!entry.isFile()) {
6817
6838
  throw new Error(`Output ${name} must be a regular file`);
6818
6839
  }
@@ -6821,7 +6842,7 @@ var collectOutputs = async (directory) => {
6821
6842
  throw new Error(`Output ${name} repeats another file name`);
6822
6843
  }
6823
6844
  names.add(key);
6824
- const handle = await open3(join7(directory, name), constants3.O_RDONLY | (process.platform === "win32" ? 0 : constants3.O_NOFOLLOW | constants3.O_NONBLOCK));
6845
+ const handle = await open3(join7(directory, name), constants4.O_RDONLY | (process.platform === "win32" ? 0 : constants4.O_NOFOLLOW | constants4.O_NONBLOCK));
6825
6846
  try {
6826
6847
  const metadata = await handle.stat();
6827
6848
  const pathMetadata = await lstat2(join7(directory, name));
@@ -6851,30 +6872,43 @@ import {
6851
6872
  // apps/device/src/mcp-host-diagnostics.ts
6852
6873
  init_src();
6853
6874
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6854
- import { Schema as Schema11 } from "effect";
6875
+ import { Schema as Schema12 } from "effect";
6855
6876
  import { randomUUID as randomUUID2 } from "node:crypto";
6856
- import { constants as constants4 } from "node:fs";
6877
+ import { constants as constants5 } from "node:fs";
6857
6878
  import { lstat as lstat3, mkdir as mkdir7, open as open4, opendir, rename as rename4, rm as rm5, writeFile as writeFile7 } from "node:fs/promises";
6858
6879
  import { join as join8 } from "node:path";
6859
6880
  var maxRecords = 8;
6860
6881
  var maxRecordBytes = 4096;
6861
6882
  var retentionMs = 7 * 24 * 60 * 60 * 1000;
6862
6883
  var recordName = /^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.json$/;
6863
- var text3 = Schema11.String.check(Schema11.isMaxLength(128));
6864
- var count2 = Schema11.Int.check(Schema11.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }));
6865
- var McpHostSession = Schema11.Struct({
6866
- schema_version: Schema11.Literal(1),
6867
- launch_id: Schema11.String.check(Schema11.isUUID(4)),
6884
+ var text3 = Schema12.String.check(Schema12.isMaxLength(128));
6885
+ var count2 = Schema12.Int.check(Schema12.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }));
6886
+ var McpHostSession = Schema12.Struct({
6887
+ schema_version: Schema12.Literal(1),
6888
+ launch_id: Schema12.String.check(Schema12.isUUID(4)),
6868
6889
  launched_at: Timestamp,
6869
6890
  server_version: text3,
6870
- initialized_at: Schema11.optionalKey(Timestamp),
6871
- client: Schema11.optionalKey(Schema11.Struct({ name: text3, version: text3 })),
6872
- tools_list: Schema11.optionalKey(Schema11.Struct({ at: Timestamp, tool_count: count2 })),
6891
+ initialized_at: Schema12.optionalKey(Timestamp),
6892
+ client: Schema12.optionalKey(Schema12.Struct({ name: text3, version: text3 })),
6893
+ tools_list: Schema12.optionalKey(Schema12.Struct({ at: Timestamp, tool_count: count2 })),
6873
6894
  tools_call_count: count2,
6874
- last_tool_call_at: Schema11.optionalKey(Timestamp),
6875
- closed_at: Schema11.optionalKey(Timestamp)
6895
+ last_tool_call_at: Schema12.optionalKey(Timestamp),
6896
+ closed_at: Schema12.optionalKey(Timestamp)
6876
6897
  });
6877
6898
  var storagePath = (configPath) => `${configPath}.mcp-hosts`;
6899
+ var replaceRecord = async (source, target) => {
6900
+ for (let attempt = 0;; attempt += 1) {
6901
+ try {
6902
+ await rename4(source, target);
6903
+ return;
6904
+ } catch (cause) {
6905
+ if (attempt === 5 || !(cause instanceof Error && ("code" in cause) && (cause.code === "EPERM" || cause.code === "EACCES" || cause.code === "EBUSY"))) {
6906
+ throw cause;
6907
+ }
6908
+ await new Promise((resolve5) => setTimeout(resolve5, 50));
6909
+ }
6910
+ }
6911
+ };
6878
6912
  var recordsIn = async (directory) => {
6879
6913
  const records = [];
6880
6914
  let entries = 0;
@@ -6916,7 +6950,7 @@ var readMcpHostDiagnostics = async (configPath = configurationPath()) => {
6916
6950
  let invalid = 0;
6917
6951
  for (const record2 of records.filter((record3) => record3.modified >= Date.now() - retentionMs).slice(0, maxRecords)) {
6918
6952
  try {
6919
- const handle = await open4(record2.path, constants4.O_RDONLY | (process.platform === "win32" ? 0 : constants4.O_NOFOLLOW | constants4.O_NONBLOCK));
6953
+ const handle = await open4(record2.path, constants5.O_RDONLY | (process.platform === "win32" ? 0 : constants5.O_NOFOLLOW | constants5.O_NONBLOCK));
6920
6954
  try {
6921
6955
  const metadata = await handle.stat();
6922
6956
  if (!metadata.isFile() || metadata.size > maxRecordBytes)
@@ -6924,7 +6958,7 @@ var readMcpHostDiagnostics = async (configPath = configurationPath()) => {
6924
6958
  const data = await readBoundedFile(handle, maxRecordBytes);
6925
6959
  if (data.length > maxRecordBytes)
6926
6960
  throw new Error("Invalid record");
6927
- sessions.push(Schema11.decodeUnknownSync(McpHostSession)(JSON.parse(data.toString("utf8"))));
6961
+ sessions.push(Schema12.decodeUnknownSync(McpHostSession)(JSON.parse(data.toString("utf8"))));
6928
6962
  } finally {
6929
6963
  await handle.close();
6930
6964
  }
@@ -7006,7 +7040,7 @@ var createMcpHostDiagnostics = (server) => {
7006
7040
  if (Buffer.byteLength(json) > maxRecordBytes)
7007
7041
  throw new Error("Record exceeded its limit");
7008
7042
  await writeFile7(temporary, json, { flag: "wx", mode: 384 });
7009
- await rename4(temporary, path);
7043
+ await replaceRecord(temporary, path);
7010
7044
  } finally {
7011
7045
  await rm5(temporary, { force: true });
7012
7046
  }
@@ -7400,11 +7434,11 @@ var runCli = async (command, raw) => {
7400
7434
  }
7401
7435
  if (command === "reply") {
7402
7436
  allowOptions(arguments_, ["message", "message-file", "error", "question", "run-id"]);
7403
- const id = Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7437
+ const id = Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7404
7438
  const error = option(arguments_, "error");
7405
7439
  const question = option(arguments_, "question");
7406
7440
  const rawRunId = option(arguments_, "run-id");
7407
- const runId = rawRunId === undefined ? undefined : Schema12.decodeUnknownSync(TaskRunId)(rawRunId);
7441
+ const runId = rawRunId === undefined ? undefined : Schema13.decodeUnknownSync(TaskRunId)(rawRunId);
7408
7442
  if ((error !== undefined || question !== undefined) && (option(arguments_, "message") !== undefined || option(arguments_, "message-file") !== undefined || error !== undefined && question !== undefined)) {
7409
7443
  throw new Error("Use one of --question, --error, or --message/--message-file");
7410
7444
  }
@@ -7412,7 +7446,7 @@ var runCli = async (command, raw) => {
7412
7446
  if (error === undefined && question === undefined && message === undefined) {
7413
7447
  throw new Error("A bot reply requires --message, --message-file, --error, or --question");
7414
7448
  }
7415
- const reply = question !== undefined ? { question: Schema12.decodeUnknownSync(RequestTaskInput.fields.question)(question) } : error === undefined ? { result: message ?? "" } : { error };
7449
+ const reply = question !== undefined ? { question: Schema13.decodeUnknownSync(RequestTaskInput.fields.question)(question) } : error === undefined ? { result: message ?? "" } : { error };
7416
7450
  await writeBotReply(id, reply, runId);
7417
7451
  print({ submitted: true, task_id: id });
7418
7452
  return;
@@ -7454,14 +7488,13 @@ var runCli = async (command, raw) => {
7454
7488
  ...deviceName === undefined ? {} : { deviceName },
7455
7489
  ...providerInput === undefined ? {} : { providers: providerInput }
7456
7490
  }, prompter);
7457
- const providers = input.providers === "auto" ? "auto" : parseProviders(input.providers);
7458
7491
  const existing = await readStoredConfiguration();
7459
7492
  const result = input.reusedConfiguration ? {
7460
7493
  configuration: await makeStoredConfiguration({
7461
7494
  relayUrl: input.relayUrl,
7462
7495
  ...input.deviceName === undefined ? {} : { deviceName: input.deviceName },
7463
7496
  ...clientOnly ? {} : { workspaces: input.workspaces },
7464
- providers
7497
+ providers: input.providers
7465
7498
  }),
7466
7499
  roles: [
7467
7500
  ...existing?.clientToken === undefined ? [] : ["client"],
@@ -7473,7 +7506,7 @@ var runCli = async (command, raw) => {
7473
7506
  clientOnly,
7474
7507
  ...input.deviceName === undefined ? {} : { deviceName: input.deviceName },
7475
7508
  ...clientOnly ? {} : { workspaces: input.workspaces },
7476
- providers
7509
+ providers: input.providers
7477
7510
  });
7478
7511
  if (input.reusedConfiguration) {
7479
7512
  await writeStoredConfiguration(result.configuration);
@@ -7582,7 +7615,7 @@ var runCli = async (command, raw) => {
7582
7615
  if (arguments_.positionals.length !== 2 || arguments_.positionals[0] !== "abandon") {
7583
7616
  throw new Error("Usage: cohall upgrades [abandon <operation-id>]");
7584
7617
  }
7585
- print(await Effect10.runPromise(relay2.abandonOperation(Schema12.decodeUnknownSync(OperationId)(arguments_.positionals[1]))));
7618
+ print(await Effect10.runPromise(relay2.abandonOperation(Schema13.decodeUnknownSync(OperationId)(arguments_.positionals[1]))));
7586
7619
  return;
7587
7620
  }
7588
7621
  print(await Effect10.runPromise(relay2.operations()));
@@ -7600,19 +7633,18 @@ var runCli = async (command, raw) => {
7600
7633
  noPositionals(arguments_, command);
7601
7634
  const existing = await readStoredConfiguration();
7602
7635
  const relayUrl = setupRelayUrl(option(arguments_, "relay") ?? existing?.relayUrl);
7603
- const token = await pairingToken(arguments_);
7636
+ const clientOnly = arguments_.options.has("client-only");
7604
7637
  const suppliedWorkspaces = values(arguments_, "workspace");
7605
- const workspaces = suppliedWorkspaces.length === 0 ? existing?.workspaces : suppliedWorkspaces;
7638
+ const workspaces = suppliedWorkspaces.length > 0 ? suppliedWorkspaces : clientOnly ? undefined : existing?.workspaces;
7606
7639
  const deviceName = option(arguments_, "name");
7607
7640
  const providerInput = option(arguments_, "providers");
7608
7641
  const providers = providerInput === undefined ? undefined : providerInput === "auto" ? "auto" : parseProviders(providerInput);
7609
- if (!arguments_.options.has("client-only") && (workspaces?.length ?? 0) === 0) {
7642
+ if (!clientOnly && (workspaces?.length ?? 0) === 0) {
7610
7643
  throw new Error("At least one --workspace is required when joining a device");
7611
7644
  }
7612
- const clientOnly = arguments_.options.has("client-only");
7613
7645
  const { configuration: configuration2, roles } = await joinRelay({
7614
7646
  relayUrl,
7615
- token,
7647
+ token: await pairingToken(arguments_),
7616
7648
  clientOnly,
7617
7649
  ...deviceName === undefined ? {} : { deviceName },
7618
7650
  ...workspaces === undefined ? {} : { workspaces },
@@ -7668,7 +7700,7 @@ var runCli = async (command, raw) => {
7668
7700
  const sandbox = option(arguments_, "sandbox");
7669
7701
  const model = option(arguments_, "model") ?? existing?.model;
7670
7702
  const gatewayInput = option(arguments_, "grok-gateway") ?? existing?.grokGateway;
7671
- const grokGateway = gatewayInput === undefined ? undefined : resolve4(gatewayInput);
7703
+ const grokGateway = gatewayInput === undefined ? undefined : resolve5(gatewayInput);
7672
7704
  const providerInput = option(arguments_, "providers");
7673
7705
  const providers = providerInput === undefined ? existing?.providers : providerInput === "auto" ? undefined : parseProviders(providerInput);
7674
7706
  const configuration2 = StoredConfiguration.make({
@@ -7682,7 +7714,7 @@ var runCli = async (command, raw) => {
7682
7714
  ...model === undefined ? {} : { model },
7683
7715
  ...grokGateway === undefined ? {} : { grokGateway },
7684
7716
  ...(sandbox ?? existing?.sandbox) === undefined ? {} : {
7685
- sandbox: Schema12.decodeUnknownSync(Schema12.Literals(["read-only", "workspace-write", "danger-full-access"]))(sandbox ?? existing?.sandbox)
7717
+ sandbox: Schema13.decodeUnknownSync(Schema13.Literals(["read-only", "workspace-write", "danger-full-access"]))(sandbox ?? existing?.sandbox)
7686
7718
  }
7687
7719
  });
7688
7720
  await writeStoredConfiguration(configuration2);
@@ -7847,11 +7879,11 @@ var runCli = async (command, raw) => {
7847
7879
  }
7848
7880
  if (command === "forget") {
7849
7881
  allowOptions(arguments_, []);
7850
- print(await Effect10.runPromise(relay2.forgetDevice(Schema12.decodeUnknownSync(DeviceId)(identifier(arguments_, "device id")))));
7882
+ print(await Effect10.runPromise(relay2.forgetDevice(Schema13.decodeUnknownSync(DeviceId)(identifier(arguments_, "device id")))));
7851
7883
  return;
7852
7884
  }
7853
7885
  allowOptions(arguments_, []);
7854
- print(await Effect10.runPromise(relay2.revokeAuthSession(Schema12.decodeUnknownSync(AuthSessionId)(identifier(arguments_, "session id")))));
7886
+ print(await Effect10.runPromise(relay2.revokeAuthSession(Schema13.decodeUnknownSync(AuthSessionId)(identifier(arguments_, "session id")))));
7855
7887
  return;
7856
7888
  }
7857
7889
  const { configuration, relay } = await client();
@@ -7860,20 +7892,20 @@ var runCli = async (command, raw) => {
7860
7892
  const rawQuestion = option(arguments_, "question");
7861
7893
  if (rawQuestion === undefined)
7862
7894
  throw new Error("--question is required");
7863
- const question = Schema12.decodeUnknownSync(RequestTaskInput.fields.question)(rawQuestion);
7864
- const id = arguments_.positionals.length === 0 ? undefined : Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7895
+ const question = Schema13.decodeUnknownSync(RequestTaskInput.fields.question)(rawQuestion);
7896
+ const id = arguments_.positionals.length === 0 ? undefined : Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7865
7897
  const rawRunId = option(arguments_, "run-id");
7866
- const runId = rawRunId === undefined ? undefined : Schema12.decodeUnknownSync(TaskRunId)(rawRunId);
7898
+ const runId = rawRunId === undefined ? undefined : Schema13.decodeUnknownSync(TaskRunId)(rawRunId);
7867
7899
  print(await Effect10.runPromise(requestInput(relay, configuration, question, id, runId)));
7868
7900
  return;
7869
7901
  }
7870
7902
  if (command === "answer") {
7871
7903
  allowOptions(arguments_, ["request-id", "message", "message-file"]);
7872
- const id = Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7904
+ const id = Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7873
7905
  const requestId = option(arguments_, "request-id");
7874
7906
  if (requestId === undefined)
7875
7907
  throw new Error("--request-id is required; use the input request id from status or inbox");
7876
- const input = Schema12.decodeUnknownSync(AnswerTaskInput)({
7908
+ const input = Schema13.decodeUnknownSync(AnswerTaskInput)({
7877
7909
  requestId,
7878
7910
  answer: await readInput(arguments_, "message")
7879
7911
  });
@@ -7888,8 +7920,8 @@ var runCli = async (command, raw) => {
7888
7920
  const note = option(arguments_, "message");
7889
7921
  if (note === undefined)
7890
7922
  throw new Error("--message is required");
7891
- const input = Schema12.decodeUnknownSync(TaskProgressInput)({ note });
7892
- print(await Effect10.runPromise(relay.reportTaskProgress(Schema12.decodeUnknownSync(TaskId)(rawId), input)));
7923
+ const input = Schema13.decodeUnknownSync(TaskProgressInput)({ note });
7924
+ print(await Effect10.runPromise(relay.reportTaskProgress(Schema13.decodeUnknownSync(TaskId)(rawId), input)));
7893
7925
  return;
7894
7926
  }
7895
7927
  if (command === "devices") {
@@ -7949,15 +7981,15 @@ var runCli = async (command, raw) => {
7949
7981
  const requestId = option(arguments_, "request-id");
7950
7982
  const task = await Effect10.runPromise(createDelegation(relay, configuration, {
7951
7983
  prompt,
7952
- ...requestId === undefined ? {} : { requestId: Schema12.decodeUnknownSync(TaskRequestId)(requestId) },
7984
+ ...requestId === undefined ? {} : { requestId: Schema13.decodeUnknownSync(TaskRequestId)(requestId) },
7953
7985
  ...target === undefined ? {} : { target },
7954
7986
  ...context === undefined ? {} : { context },
7955
- ...thread === undefined ? {} : { threadId: Schema12.decodeUnknownSync(ThreadId)(thread) },
7956
- ...parent === undefined ? {} : { parentTaskId: Schema12.decodeUnknownSync(TaskId)(parent) },
7987
+ ...thread === undefined ? {} : { threadId: Schema13.decodeUnknownSync(ThreadId)(thread) },
7988
+ ...parent === undefined ? {} : { parentTaskId: Schema13.decodeUnknownSync(TaskId)(parent) },
7957
7989
  ...workspace === undefined ? {} : { workspace },
7958
- ...provider === undefined ? {} : { provider: Schema12.decodeUnknownSync(Provider)(provider) },
7990
+ ...provider === undefined ? {} : { provider: Schema13.decodeUnknownSync(Provider)(provider) },
7959
7991
  ...attachments2.length === 0 ? {} : { attachments: attachments2 },
7960
- ...deadline === undefined ? {} : { expiresAt: Schema12.decodeUnknownSync(TaskDeadline)(deadline) }
7992
+ ...deadline === undefined ? {} : { expiresAt: Schema13.decodeUnknownSync(TaskDeadline)(deadline) }
7961
7993
  }));
7962
7994
  const completed = arguments_.options.has("no-wait") ? task : await Effect10.runPromise(waitForTask(relay, task, waitSeconds));
7963
7995
  print(arguments_.options.has("no-wait") ? taskResult(completed) : await acknowledgedTaskResult(relay, completed));
@@ -7968,7 +8000,7 @@ var runCli = async (command, raw) => {
7968
8000
  if (arguments_.positionals[0] === "ack") {
7969
8001
  if (arguments_.positionals.length !== 2)
7970
8002
  throw new Error("Usage: cohall inbox ack <task-id>");
7971
- const id = Schema12.decodeUnknownSync(TaskId)(arguments_.positionals[1]);
8003
+ const id = Schema13.decodeUnknownSync(TaskId)(arguments_.positionals[1]);
7972
8004
  print(await Effect10.runPromise(relay.acknowledgeCompletion(id)));
7973
8005
  return;
7974
8006
  }
@@ -7978,13 +8010,13 @@ var runCli = async (command, raw) => {
7978
8010
  }
7979
8011
  if (command === "status") {
7980
8012
  allowOptions(arguments_, []);
7981
- const id = Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8013
+ const id = Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7982
8014
  print(taskResult(await Effect10.runPromise(relay.getTask(id))));
7983
8015
  return;
7984
8016
  }
7985
8017
  if (command === "attachments") {
7986
8018
  allowOptions(arguments_, []);
7987
- const id = Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8019
+ const id = Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
7988
8020
  print(await Effect10.runPromise(relay.listAttachments(id)));
7989
8021
  return;
7990
8022
  }
@@ -7997,18 +8029,18 @@ var runCli = async (command, raw) => {
7997
8029
  if (destination === undefined) {
7998
8030
  throw new Error("--output is required");
7999
8031
  }
8000
- const id = Schema12.decodeUnknownSync(TaskId)(arguments_.positionals[0]);
8001
- const name = Schema12.decodeUnknownSync(AttachmentName)(arguments_.positionals[1]);
8032
+ const id = Schema13.decodeUnknownSync(TaskId)(arguments_.positionals[0]);
8033
+ const name = Schema13.decodeUnknownSync(AttachmentName)(arguments_.positionals[1]);
8002
8034
  const directionInput = option(arguments_, "direction");
8003
- const direction = directionInput === undefined ? undefined : Schema12.decodeUnknownSync(AttachmentDirection)(directionInput);
8035
+ const direction = directionInput === undefined ? undefined : Schema13.decodeUnknownSync(AttachmentDirection)(directionInput);
8004
8036
  const data = await Effect10.runPromise(relay.readAttachment(id, name, direction));
8005
8037
  await writeFile8(destination, data, { flag: "wx", mode: 384 });
8006
- print({ task_id: id, name, path: resolve4(destination), bytes: data.length });
8038
+ print({ task_id: id, name, path: resolve5(destination), bytes: data.length });
8007
8039
  return;
8008
8040
  }
8009
8041
  if (command === "trace") {
8010
8042
  allowOptions(arguments_, ["follow"]);
8011
- const id = Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8043
+ const id = Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8012
8044
  if (arguments_.options.has("follow")) {
8013
8045
  await Effect10.runPromise(followTaskTrace(relay, id, printLine));
8014
8046
  return;
@@ -8018,19 +8050,19 @@ var runCli = async (command, raw) => {
8018
8050
  }
8019
8051
  if (command === "wait") {
8020
8052
  allowOptions(arguments_, ["timeout"]);
8021
- const id = Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8053
+ const id = Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8022
8054
  print(taskResult(await Effect10.runPromise(waitForTask(relay, id, timeout(arguments_)))));
8023
8055
  return;
8024
8056
  }
8025
8057
  if (command === "cancel") {
8026
8058
  allowOptions(arguments_, []);
8027
- const id = Schema12.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8059
+ const id = Schema13.decodeUnknownSync(TaskId)(identifier(arguments_, "task id"));
8028
8060
  print(taskResult(await Effect10.runPromise(relay.cancelTask(id))));
8029
8061
  return;
8030
8062
  }
8031
8063
  if (command === "thread") {
8032
8064
  allowOptions(arguments_, []);
8033
- const id = Schema12.decodeUnknownSync(ThreadId)(identifier(arguments_, "thread id"));
8065
+ const id = Schema13.decodeUnknownSync(ThreadId)(identifier(arguments_, "thread id"));
8034
8066
  print(await Effect10.runPromise(threadContext(relay, id)));
8035
8067
  return;
8036
8068
  }
@@ -8039,15 +8071,15 @@ var runCli = async (command, raw) => {
8039
8071
 
8040
8072
  // apps/device/src/daemon.ts
8041
8073
  init_src();
8042
- import { Effect as Effect11, Schedule as Schedule3, Schema as Schema13 } from "effect";
8043
- import { constants as constants5 } from "node:fs";
8074
+ import { Effect as Effect11, Schedule as Schedule3, Schema as Schema14 } from "effect";
8075
+ import { constants as constants6 } from "node:fs";
8044
8076
  import { open as open6, realpath as realpath4, stat as stat5 } from "node:fs/promises";
8045
8077
  import { arch, hostname as hostname3, platform as platform4 } from "node:os";
8046
8078
  import { basename as basename3, isAbsolute as isAbsolute5, relative as relative2, sep } from "node:path";
8047
8079
  import { WebSocket as WebSocket2 } from "ws";
8048
8080
  var maxQueuedRelayMessages = 8;
8049
8081
 
8050
- class DeviceConnectionError extends Schema13.TaggedErrorClass()("Device.ConnectionError", { message: Schema13.String }) {
8082
+ class DeviceConnectionError extends Schema14.TaggedErrorClass()("Device.ConnectionError", { message: Schema14.String }) {
8051
8083
  }
8052
8084
  var socketUrl = (configuration) => {
8053
8085
  const url = new URL(configuration.relayUrl);
@@ -8134,31 +8166,35 @@ var allowedWorkspace = async (configuration, requested) => {
8134
8166
  var openAllowedWorkspace = async (configuration, requested) => {
8135
8167
  const path = await allowedWorkspace(configuration, requested);
8136
8168
  const operatingSystem2 = platform4();
8137
- const flags = constants5.O_RDONLY | (operatingSystem2 === "win32" ? 0 : constants5.O_DIRECTORY | constants5.O_NOFOLLOW);
8169
+ const flags = constants6.O_RDONLY | (operatingSystem2 === "win32" ? 0 : constants6.O_DIRECTORY | constants6.O_NOFOLLOW);
8138
8170
  const handle = await open6(path, flags);
8139
- const identity = await handle.stat();
8140
- if (!identity.isDirectory()) {
8141
- await handle.close();
8142
- throw new Error(`Workspace ${path} is not a directory`);
8143
- }
8144
- const cwd = operatingSystem2 === "linux" ? `/proc/self/fd/${handle.fd}` : path;
8145
- return {
8146
- cwd,
8147
- validate: async () => {
8171
+ try {
8172
+ const identity = await handle.stat();
8173
+ if (!identity.isDirectory()) {
8174
+ throw new Error(`Workspace ${path} is not a directory`);
8175
+ }
8176
+ const cwd = operatingSystem2 === "linux" ? `/proc/self/fd/${handle.fd}` : path;
8177
+ const validate = async () => {
8148
8178
  const current = await handle.stat();
8149
8179
  if (!current.isDirectory() || current.dev !== identity.dev || current.ino !== identity.ino) {
8150
8180
  throw new Error(`Workspace ${path} changed before provider startup`);
8151
8181
  }
8182
+ const currentPath = await allowedWorkspace(configuration, cwd);
8152
8183
  if (operatingSystem2 !== "linux") {
8153
- const currentPath = await realpath4(path);
8154
8184
  const currentPathIdentity = await stat5(currentPath);
8155
8185
  if (currentPathIdentity.dev !== identity.dev || currentPathIdentity.ino !== identity.ino) {
8156
8186
  throw new Error(`Workspace ${path} changed before provider startup`);
8157
8187
  }
8158
8188
  }
8159
- },
8160
- close: () => handle.close()
8161
- };
8189
+ };
8190
+ await validate();
8191
+ return { cwd, validate, close: () => handle.close() };
8192
+ } catch (cause) {
8193
+ await handle.close().catch(() => {
8194
+ return;
8195
+ });
8196
+ throw cause;
8197
+ }
8162
8198
  };
8163
8199
  var promptFor = (task, deviceName, supportsClarification, files) => {
8164
8200
  const context = task.context === undefined ? "" : `
@@ -8663,7 +8699,7 @@ var runDaemon = (configuration) => {
8663
8699
  // apps/device/src/mcp.ts
8664
8700
  init_src();
8665
8701
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8666
- import { Effect as Effect12, Schema as Schema14 } from "effect";
8702
+ import { Effect as Effect12, Schema as Schema15 } from "effect";
8667
8703
  import * as z from "zod/v4";
8668
8704
  import { writeFile as writeFile9 } from "node:fs/promises";
8669
8705
 
@@ -8735,7 +8771,7 @@ var runMcp = async (configuration) => {
8735
8771
  run_id: z.string().uuid().optional(),
8736
8772
  question: z.string().min(1).max(maxClarificationBytes)
8737
8773
  }
8738
- }, async ({ task_id, run_id, question }) => output(await Effect12.runPromise(requestInput(client2, configuration, Schema14.decodeUnknownSync(RequestTaskInput.fields.question)(question), task_id === undefined ? undefined : Schema14.decodeUnknownSync(TaskId)(task_id), run_id === undefined ? undefined : Schema14.decodeUnknownSync(TaskRunId)(run_id)))));
8774
+ }, async ({ task_id, run_id, question }) => output(await Effect12.runPromise(requestInput(client2, configuration, Schema15.decodeUnknownSync(RequestTaskInput.fields.question)(question), task_id === undefined ? undefined : Schema15.decodeUnknownSync(TaskId)(task_id), run_id === undefined ? undefined : Schema15.decodeUnknownSync(TaskRunId)(run_id)))));
8739
8775
  server.registerTool("task_answer", {
8740
8776
  title: "Answer a worker's question",
8741
8777
  description: "Answer the current clarification and resume the same task. Use input_request.id from task_status or delegate as request_id, or inputRequest.id from completion_inbox. Only the original requester or relay owner can answer. Use wait_task to collect the resumed result.",
@@ -8744,7 +8780,7 @@ var runMcp = async (configuration) => {
8744
8780
  request_id: z.string().uuid(),
8745
8781
  answer: z.string().min(1).max(maxClarificationBytes)
8746
8782
  }
8747
- }, async ({ task_id, request_id, answer }) => output(taskResult(await Effect12.runPromise(client2.answerTaskInput(Schema14.decodeUnknownSync(TaskId)(task_id), Schema14.decodeUnknownSync(AnswerTaskInput)({ requestId: request_id, answer }))))));
8783
+ }, async ({ task_id, request_id, answer }) => output(taskResult(await Effect12.runPromise(client2.answerTaskInput(Schema15.decodeUnknownSync(TaskId)(task_id), Schema15.decodeUnknownSync(AnswerTaskInput)({ requestId: request_id, answer }))))));
8748
8784
  server.registerTool("task_progress", {
8749
8785
  title: "Report task progress",
8750
8786
  description: `Replace the latest progress note for a running task on this device. Use brief milestones, up to ${maxProgressNoteBytes} UTF-8 bytes. Inherits the delegated task ID when omitted.`,
@@ -8756,8 +8792,8 @@ var runMcp = async (configuration) => {
8756
8792
  const id = task_id ?? configuration.mcpTaskId;
8757
8793
  if (id === undefined)
8758
8794
  throw new Error("Task id is required outside delegated work");
8759
- const input = Schema14.decodeUnknownSync(TaskProgressInput)({ note });
8760
- return output(await Effect12.runPromise(client2.reportTaskProgress(Schema14.decodeUnknownSync(TaskId)(id), input)));
8795
+ const input = Schema15.decodeUnknownSync(TaskProgressInput)({ note });
8796
+ return output(await Effect12.runPromise(client2.reportTaskProgress(Schema15.decodeUnknownSync(TaskId)(id), input)));
8761
8797
  });
8762
8798
  server.registerTool("list_devices", {
8763
8799
  title: "List Cohall devices",
@@ -8803,7 +8839,7 @@ var runMcp = async (configuration) => {
8803
8839
  const attachments2 = await readInputAttachments(attachment_paths ?? []);
8804
8840
  const task = await Effect12.runPromise(createDelegation(client2, configuration, {
8805
8841
  prompt,
8806
- ...request_id === undefined ? {} : { requestId: Schema14.decodeUnknownSync(TaskRequestId)(request_id) },
8842
+ ...request_id === undefined ? {} : { requestId: Schema15.decodeUnknownSync(TaskRequestId)(request_id) },
8807
8843
  ...provider === undefined ? {} : { provider },
8808
8844
  ...target === undefined ? {} : { target },
8809
8845
  ...context === undefined ? {} : { context },
@@ -8811,7 +8847,7 @@ var runMcp = async (configuration) => {
8811
8847
  ...parent_task_id === undefined ? {} : { parentTaskId: TaskId.make(parent_task_id) },
8812
8848
  ...workspace === undefined ? {} : { workspace },
8813
8849
  ...attachments2.length === 0 ? {} : { attachments: attachments2 },
8814
- ...deadline === undefined ? {} : { expiresAt: Schema14.decodeUnknownSync(TaskDeadline)(deadline) }
8850
+ ...deadline === undefined ? {} : { expiresAt: Schema15.decodeUnknownSync(TaskDeadline)(deadline) }
8815
8851
  }), { signal });
8816
8852
  const completed = wait ? await Effect12.runPromise(waitForTask(client2, task, timeout_seconds), { signal }) : task;
8817
8853
  return output(wait ? await acknowledgedTaskResult(client2, completed, signal) : taskResult(completed));
@@ -8846,8 +8882,8 @@ var runMcp = async (configuration) => {
8846
8882
  direction: z.enum(["input", "output"]).optional()
8847
8883
  }
8848
8884
  }, async ({ task_id, name, output_path, direction }, { signal }) => {
8849
- const safeName = Schema14.decodeUnknownSync(AttachmentName)(name);
8850
- const safeDirection = direction === undefined ? undefined : Schema14.decodeUnknownSync(AttachmentDirection)(direction);
8885
+ const safeName = Schema15.decodeUnknownSync(AttachmentName)(name);
8886
+ const safeDirection = direction === undefined ? undefined : Schema15.decodeUnknownSync(AttachmentDirection)(direction);
8851
8887
  const data = await Effect12.runPromise(client2.readAttachment(TaskId.make(task_id), safeName, safeDirection), { signal });
8852
8888
  signal.throwIfAborted();
8853
8889
  await writeFile9(output_path, data, { flag: "wx", mode: 384, signal });
@@ -8936,4 +8972,4 @@ await main().catch((cause) => {
8936
8972
  process.exitCode = 1;
8937
8973
  });
8938
8974
 
8939
- //# debugId=DE88F22C811E1F1F64756E2164756E21
8975
+ //# debugId=83A2666BE91A2AA364756E2164756E21