@sjawhar/claude-envoy 5.24.0 → 5.25.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -980,7 +980,7 @@ __export(exports_coerce, {
980
980
  });
981
981
 
982
982
  // hooks/session-hook.ts
983
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync7, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
983
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
984
984
  import { join as join11 } from "path";
985
985
 
986
986
  // ../cipher-client/src/device-login-file.ts
@@ -2933,6 +2933,10 @@ var FORM_SESSION = "session";
2933
2933
  var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
2934
2934
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
2935
2935
  var FORM_PROJECTS = "projects";
2936
+ var FORM_SCOPE = "scope";
2937
+ var SCOPE_READ = "read";
2938
+ var FORM_AS_OF = "as_of";
2939
+ var HEADER_DPOP_HOLDER = "DPoP-Holder";
2936
2940
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
2937
2941
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
2938
2942
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
@@ -3045,6 +3049,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
3045
3049
  "The machine login the subject token belongs to has ended\\.",
3046
3050
  "The machine login has ended\\.",
3047
3051
  "Another live machine login holds the key this proof was signed with\\. A (?:machine makes a key of its own|sign-in makes a box key of its own)\\.",
3052
+ "A live read token is bound to the key this proof was signed with\\. Make a new key\\.",
3048
3053
  `${PERSON_SLOT} is a restricted member, whose token names its projects: set AGENT_SECRETS_PROJECTS to the projects this session works on\\.`,
3049
3054
  `The token names a project its person cannot see: ${PROJECT_SLOT}\\.`,
3050
3055
  `The subject token was refused: its entry names the project ${PROJECT_SLOT}, which its person ${PERSON_SLOT} cannot see\\.`,
@@ -3057,6 +3062,19 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
3057
3062
  `The session name '${SESSION_SLOT}' belongs to another daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
3058
3063
  `The session name '${SESSION_SLOT}' is bound to no daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
3059
3064
  `${PERSON_SLOT}'s credentials are held by Dispatch; they work again when \\k<person> signs in to Dispatch, or when Dispatch can confirm \\k<person> with Google again`,
3065
+ "The 'as_of' parameter names a cut, and only a trade that asks for the scope read may name one\\.",
3066
+ "The 'as_of' parameter is not an RFC 3339 time with at most six fractional digits\\.",
3067
+ "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
3068
+ "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
3069
+ "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
3070
+ `${PERSON_SLOT}'s sign-in on this machine holds no launcher credential yet, and a read trade makes none\\. Sign in with \`agent-secrets login\` first\\.`,
3071
+ `${PERSON_SLOT}'s sign-in on this machine holds a launcher credential that has lapsed, and a read trade renews none\\. One ordinary trade of the sign-in renews it, as \`agent-secrets\` makes; then trade for read again\\.`,
3072
+ "A person's read trade sends a DPoP-Holder proof: the box key proves the sign-in and is bound to no read token, so the token is bound to a key made for its holder\\.",
3073
+ "The DPoP-Holder header binds a read token to its holder's key, and this trade does not ask for the scope read\\. Ask for it, or send no DPoP-Holder header\\.",
3074
+ "The DPoP-Holder proof was refused: a trade sends one, a DPoP proof of this request signed with the key it embeds, spent nowhere before\\.",
3075
+ "The DPoP-Holder proof is signed with the key the DPoP proof is signed with, and the holder's key is a key of its own\\.",
3076
+ "The key this read token would be bound to signs launcher proofs: a live launcher credential is bound to it, and no read token is bound to such a key\\. Send a DPoP-Holder proof by a key made for the token's holder, and the token is bound to that key\\.",
3077
+ "The key this proof was signed with signs launcher proofs: a live launcher credential is bound to it, and no read token is bound to such a key\\. Ask for the scope read with a DPoP-Holder proof by a key made for the token's holder, or trade with a key that holds no launcher credential\\.",
3060
3078
  ...POLICY_REFUSAL_PATTERNS
3061
3079
  ].map((source) => new RegExp(`^${source}$`));
3062
3080
  var LIBRARY_DESCRIPTIONS = [
@@ -3352,32 +3370,8 @@ function isFinalRefusal(error) {
3352
3370
  return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
3353
3371
  }
3354
3372
 
3355
- // ../cipher-client/src/token-client.ts
3356
- var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
3373
+ // ../cipher-client/src/broker-request.ts
3357
3374
  var BROKER_URL_SETTING = "the broker URL";
3358
- var RETRY_FIRST_WAIT_MS = 15000;
3359
- var RETRY_MAX_WAIT_MS = 5 * 60000;
3360
- var PENDING_FIRST_WAIT_MS = 2000;
3361
- var PENDING_MAX_WAIT_MS = 30000;
3362
- var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
3363
- var TRADE_ATTEMPT_MS = 30000;
3364
- function sleep(ms, signal, holdsProcess = false) {
3365
- const { promise, resolve } = Promise.withResolvers();
3366
- if (signal?.aborted) {
3367
- resolve();
3368
- return promise;
3369
- }
3370
- const done = () => {
3371
- clearTimeout(timer);
3372
- signal?.removeEventListener("abort", done);
3373
- resolve();
3374
- };
3375
- const timer = setTimeout(done, ms);
3376
- if (!holdsProcess)
3377
- timer.unref();
3378
- signal?.addEventListener("abort", done, { once: true });
3379
- return promise;
3380
- }
3381
3375
  function statusOf(error) {
3382
3376
  let cause = error;
3383
3377
  for (let depth = 0;depth < 4; depth += 1) {
@@ -3414,7 +3408,11 @@ function requestInit(options, signal, headers) {
3414
3408
  async function sendWithProof(proved, url, options, signal) {
3415
3409
  const send = async () => {
3416
3410
  const headers = new Headers(options.headers);
3417
- headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
3411
+ const request = { method: options.method, url, nonce: proved.nonce.value };
3412
+ headers.set("DPoP", await proved.key.proof(request));
3413
+ if (proved.holderKey !== undefined) {
3414
+ headers.set(HEADER_DPOP_HOLDER, await proved.holderKey.proof(request));
3415
+ }
3418
3416
  return await proved.fetch(url, requestInit(options, signal, headers));
3419
3417
  };
3420
3418
  let answer = await send();
@@ -3430,14 +3428,50 @@ async function sendWithProof(proved, url, options, signal) {
3430
3428
  return answer;
3431
3429
  }
3432
3430
 
3431
+ // ../cipher-client/src/token-client.ts
3432
+ var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
3433
+ function renewalAt(expiresAt, now, renewBeforeMs) {
3434
+ const left = expiresAt - now;
3435
+ if (left <= 0)
3436
+ return now;
3437
+ return Math.max(expiresAt - renewBeforeMs, now + left / 2);
3438
+ }
3439
+ var EXPIRES_IN_STEP_MS = 1000;
3440
+ var RETRY_FIRST_WAIT_MS = 15000;
3441
+ var RETRY_MAX_WAIT_MS = 5 * 60000;
3442
+ var PENDING_FIRST_WAIT_MS = 2000;
3443
+ var PENDING_MAX_WAIT_MS = 30000;
3444
+ var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
3445
+ var TRADE_ATTEMPT_MS = 30000;
3446
+ function sleep(ms, signal, holdsProcess = false) {
3447
+ const { promise, resolve } = Promise.withResolvers();
3448
+ if (signal?.aborted) {
3449
+ resolve();
3450
+ return promise;
3451
+ }
3452
+ const done = () => {
3453
+ clearTimeout(timer);
3454
+ signal?.removeEventListener("abort", done);
3455
+ resolve();
3456
+ };
3457
+ const timer = setTimeout(done, ms);
3458
+ if (!holdsProcess)
3459
+ timer.unref();
3460
+ signal?.addEventListener("abort", done, { once: true });
3461
+ return promise;
3462
+ }
3463
+
3433
3464
  class BrokerTokenClient {
3434
3465
  #brokerUrl;
3435
3466
  #key;
3467
+ #holderKey;
3436
3468
  #subject;
3437
3469
  #actor;
3438
3470
  #session;
3439
3471
  #projects;
3440
3472
  #launcherCredential;
3473
+ #scope;
3474
+ #asOf;
3441
3475
  #renewBeforeMs;
3442
3476
  #now;
3443
3477
  #attemptMs;
@@ -3466,11 +3500,14 @@ class BrokerTokenClient {
3466
3500
  throw new Error("broker client: the broker URL is not an http or https URL");
3467
3501
  this.#brokerUrl = holdUrlUserinfo(brokerUrl);
3468
3502
  this.#key = options.key;
3503
+ this.#holderKey = options.holderKey;
3469
3504
  this.#subject = options.subject;
3470
3505
  this.#actor = options.actor;
3471
3506
  this.#session = options.session ?? "";
3472
3507
  this.#projects = [...options.projects ?? []];
3473
3508
  this.#launcherCredential = options.launcherCredential ?? true;
3509
+ this.#scope = options.scope ?? "";
3510
+ this.#asOf = options.asOf ?? "";
3474
3511
  this.#renewBeforeMs = options.renewBeforeMs ?? DEFAULT_RENEW_BEFORE_MS;
3475
3512
  this.#now = options.now ?? Date.now;
3476
3513
  this.#attemptMs = options.attemptMs ?? TRADE_ATTEMPT_MS;
@@ -3480,7 +3517,7 @@ class BrokerTokenClient {
3480
3517
  this.#random = options.random ?? Math.random;
3481
3518
  }
3482
3519
  get key() {
3483
- return this.#key;
3520
+ return this.#holderKey ?? this.#key;
3484
3521
  }
3485
3522
  describe() {
3486
3523
  return this.#subject.describe();
@@ -3489,10 +3526,11 @@ class BrokerTokenClient {
3489
3526
  const waitForReady = options.waitForReady === true;
3490
3527
  const now = this.#now();
3491
3528
  const held = this.#held;
3492
- if (held !== null && now < held.expiresAt.getTime() - this.#renewBeforeMs)
3493
- return held;
3494
- if (held !== null && now < held.expiresAt.getTime() && this.#last !== null)
3495
- return held;
3529
+ if (held !== null && now < held.renewsAt)
3530
+ return held.token;
3531
+ if (held !== null && now < held.token.expiresAt.getTime() && this.#last !== null) {
3532
+ return held.token;
3533
+ }
3496
3534
  const closed = this.#closed.signal;
3497
3535
  if (closed.aborted)
3498
3536
  throw closed.reason;
@@ -3526,8 +3564,8 @@ class BrokerTokenClient {
3526
3564
  const stop = () => {
3527
3565
  this.#waiters.delete(waiter);
3528
3566
  const held = this.#held;
3529
- if (held !== null && this.#now() < held.expiresAt.getTime())
3530
- resolve(held);
3567
+ if (held !== null && this.#now() < held.token.expiresAt.getTime())
3568
+ resolve(held.token);
3531
3569
  else
3532
3570
  reject(this.#stopped(signal?.reason));
3533
3571
  };
@@ -3567,7 +3605,7 @@ class BrokerTokenClient {
3567
3605
  });
3568
3606
  }
3569
3607
  drop(accessToken) {
3570
- if (accessToken !== undefined && this.#held?.accessToken !== accessToken)
3608
+ if (accessToken !== undefined && this.#held?.token.accessToken !== accessToken)
3571
3609
  return;
3572
3610
  this.#held = null;
3573
3611
  }
@@ -3598,7 +3636,10 @@ class BrokerTokenClient {
3598
3636
  if (this.#pendingSaid !== null && this.#since !== null) {
3599
3637
  this.#log(`the secrets broker answered this pod's session ${this.#session} once it was registered, ${Math.round((this.#now() - this.#since) / 1000)} s and ${this.#failed} failed trades after the first`);
3600
3638
  }
3601
- this.#held = token;
3639
+ this.#held = {
3640
+ token,
3641
+ renewsAt: renewalAt(token.expiresAt.getTime(), this.#now(), this.#renewBeforeMs)
3642
+ };
3602
3643
  this.#last = null;
3603
3644
  this.#since = null;
3604
3645
  this.#failed = 0;
@@ -3638,8 +3679,8 @@ class BrokerTokenClient {
3638
3679
  this.#since ??= now;
3639
3680
  this.#failed += 1;
3640
3681
  const held = this.#held;
3641
- if (held !== null && now < held.expiresAt.getTime()) {
3642
- this.#tell((waiter) => waiter.resolve(held));
3682
+ if (held !== null && now < held.token.expiresAt.getTime()) {
3683
+ this.#tell((waiter) => waiter.resolve(held.token));
3643
3684
  } else {
3644
3685
  this.#held = null;
3645
3686
  if (failure.kind !== "pending") {
@@ -3691,7 +3732,8 @@ class BrokerTokenClient {
3691
3732
  async#trade(signal) {
3692
3733
  const source = this.#subject;
3693
3734
  if (source.spend !== undefined) {
3694
- return await source.spend((subject) => this.#exchange(subject, signal), signal);
3735
+ const leastLifeMs = this.#scope === SCOPE_READ ? this.#renewBeforeMs + EXPIRES_IN_STEP_MS : undefined;
3736
+ return await source.spend((subject) => this.#exchange(subject, signal), signal, leastLifeMs);
3695
3737
  }
3696
3738
  return await this.#exchange(await source.read(signal), signal);
3697
3739
  }
@@ -3705,6 +3747,10 @@ class BrokerTokenClient {
3705
3747
  form[FORM_SESSION] = this.#session;
3706
3748
  if (this.#projects.length > 0)
3707
3749
  form[FORM_PROJECTS] = this.#projects.join(" ");
3750
+ if (this.#scope !== "")
3751
+ form[FORM_SCOPE] = this.#scope;
3752
+ if (this.#asOf !== "")
3753
+ form[FORM_AS_OF] = this.#asOf;
3708
3754
  if (!this.#launcherCredential) {
3709
3755
  form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
3710
3756
  }
@@ -3737,7 +3783,7 @@ class BrokerTokenClient {
3737
3783
  return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
3738
3784
  }
3739
3785
  async#send(url, options, signal, raw) {
3740
- const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
3786
+ const answer = await sendWithProof({ key: this.#key, holderKey: this.#holderKey, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
3741
3787
  raw.body = await answer.clone().json().catch(() => {
3742
3788
  return;
3743
3789
  });
@@ -4000,6 +4046,10 @@ function member(json, name) {
4000
4046
  const value = json[name];
4001
4047
  return typeof value === "string" ? value : "";
4002
4048
  }
4049
+ function wholeMember(json, name) {
4050
+ const value = json[name];
4051
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
4052
+ }
4003
4053
  function checkPrivate(info, what, forbidden, opens, notOwned) {
4004
4054
  const mode = info.mode & 511;
4005
4055
  if ((mode & forbidden) !== 0) {
@@ -4357,7 +4407,8 @@ async function readDeviceLogin(path) {
4357
4407
  expiresAt,
4358
4408
  broker,
4359
4409
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
4360
- accessExpiresAt: accessUsable ? accessExpiresAt : null
4410
+ accessExpiresAt: accessUsable ? accessExpiresAt : null,
4411
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
4361
4412
  };
4362
4413
  }
4363
4414
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -4390,7 +4441,8 @@ async function saveDeviceLogin(path, login, held, keep = false) {
4390
4441
  broker: login.broker,
4391
4442
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
4392
4443
  access_token: login.accessToken,
4393
- access_expires_at: login.accessExpiresAt.toISOString()
4444
+ access_expires_at: login.accessExpiresAt.toISOString(),
4445
+ ...login.accessLifeSeconds === null ? {} : { access_life_seconds: login.accessLifeSeconds }
4394
4446
  }
4395
4447
  });
4396
4448
  await deviceLoginPlace(path);
@@ -23402,17 +23454,16 @@ function askAnswerText(answer) {
23402
23454
 
23403
23455
  // ../envoy-client/src/envoy-config.ts
23404
23456
  import {
23405
- chmodSync,
23406
- closeSync as closeSync2,
23407
- existsSync,
23408
- lstatSync,
23409
- mkdtempSync,
23410
- openSync as openSync2,
23411
- readFileSync as readFileSync2,
23412
- readlinkSync,
23413
- rmSync,
23414
- statSync
23415
- } from "fs";
23457
+ access as access2,
23458
+ chmod,
23459
+ lstat as lstat3,
23460
+ mkdtemp,
23461
+ open as open3,
23462
+ readFile as readFile4,
23463
+ readlink as readlink2,
23464
+ rm as rm3,
23465
+ stat as stat3
23466
+ } from "fs/promises";
23416
23467
  import { homedir, tmpdir } from "os";
23417
23468
  import * as path from "path";
23418
23469
 
@@ -23502,15 +23553,44 @@ function jsonErrorPosition(text) {
23502
23553
  }
23503
23554
  }
23504
23555
 
23556
+ // ../envoy-client/src/process-group.ts
23557
+ function killGroup(pid) {
23558
+ try {
23559
+ process.kill(-pid, "SIGKILL");
23560
+ } catch {}
23561
+ }
23562
+ var WATCH = 'exec 3<&0; (while read -r line <&3; do :; done; kill -s KILL -- -$$) </dev/null >/dev/null 2>&1 & exec "$0" "$@" </dev/null 3<&-';
23563
+ function groupWatchedBy(argv) {
23564
+ return ["/bin/sh", "-c", WATCH, ...argv];
23565
+ }
23566
+ function spawnWatched(argv, options) {
23567
+ const child = Bun.spawn(groupWatchedBy(argv), {
23568
+ ...options,
23569
+ stdin: "pipe",
23570
+ detached: true
23571
+ });
23572
+ let closed = false;
23573
+ return {
23574
+ child,
23575
+ endGroup: () => {
23576
+ killGroup(child.pid);
23577
+ if (closed)
23578
+ return;
23579
+ closed = true;
23580
+ child.stdin.end();
23581
+ }
23582
+ };
23583
+ }
23584
+
23505
23585
  // ../envoy-client/src/secret-file.ts
23506
- import { readFileSync } from "fs";
23586
+ import { readFile as readFile3 } from "fs/promises";
23507
23587
  function sendable(value) {
23508
23588
  return !/[\s\p{Cc}]/u.test(value);
23509
23589
  }
23510
- function readSecretFile(variable, filePath) {
23590
+ async function readSecretFile(variable, filePath) {
23511
23591
  let contents;
23512
23592
  try {
23513
- contents = readFileSync(filePath, "utf8");
23593
+ contents = await readFile3(filePath, "utf8");
23514
23594
  } catch (error) {
23515
23595
  throw new Error(`${variable} names a file that could not be read (${readErrorCode(error)})`);
23516
23596
  }
@@ -23645,20 +23725,28 @@ function describeSchemaIssue(filePath, error) {
23645
23725
  }
23646
23726
  return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
23647
23727
  }
23648
- function danglingLink(filePath) {
23728
+ async function danglingLink(filePath) {
23649
23729
  try {
23650
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
23730
+ return (await lstat3(filePath)).isSymbolicLink() ? await readlink2(filePath) : null;
23651
23731
  } catch {
23652
23732
  return null;
23653
23733
  }
23654
23734
  }
23655
- function parseFile(filePath, schema, checkout) {
23735
+ async function exists(file) {
23736
+ try {
23737
+ await access2(file);
23738
+ return true;
23739
+ } catch {
23740
+ return false;
23741
+ }
23742
+ }
23743
+ async function parseFile(filePath, schema, checkout) {
23656
23744
  let raw;
23657
23745
  try {
23658
- raw = readFileSync2(filePath, "utf-8");
23746
+ raw = await readFile4(filePath, "utf-8");
23659
23747
  } catch (error) {
23660
23748
  if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
23661
- return { kind: "absent", link: danglingLink(filePath) };
23749
+ return { kind: "absent", link: checkout ? null : await danglingLink(filePath) };
23662
23750
  }
23663
23751
  return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
23664
23752
  }
@@ -23686,53 +23774,77 @@ function parseFile(filePath, schema, checkout) {
23686
23774
  }
23687
23775
  var FAILURE_KEPT_MS = 60000;
23688
23776
  var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
23777
+ var COMMAND_RUNS = Symbol.for("legion.envoy-config.command-runs.v1");
23689
23778
  var processGlobal = globalThis;
23690
23779
  var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
23691
23780
  processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
23692
- function runCommand(command, env, cwd) {
23781
+ var commandRuns = processGlobal[COMMAND_RUNS] ?? new Map;
23782
+ processGlobal[COMMAND_RUNS] = commandRuns;
23783
+ async function unnamedFile() {
23784
+ const directory = await mkdtemp(path.join(tmpdir(), "envoy-command-"));
23785
+ try {
23786
+ await chmod(directory, 448);
23787
+ return await open3(path.join(directory, "stdout"), "wx+", 384);
23788
+ } finally {
23789
+ await rm3(directory, { recursive: true, force: true });
23790
+ }
23791
+ }
23792
+ async function readOutput(file) {
23793
+ const output = Buffer.alloc((await file.stat()).size);
23794
+ let read = 0;
23795
+ while (read < output.length) {
23796
+ const { bytesRead } = await file.read(output, read, output.length - read, read);
23797
+ if (bytesRead === 0)
23798
+ break;
23799
+ read += bytesRead;
23800
+ }
23801
+ return output.toString("utf-8", 0, read);
23802
+ }
23803
+ async function runCommand(command, env, cwd) {
23693
23804
  const timeoutMs = commandTimeoutMs(env);
23694
23805
  const childEnv = {};
23695
23806
  for (const [name, variable] of Object.entries(env)) {
23696
23807
  if (variable !== undefined)
23697
23808
  childEnv[name] = variable;
23698
23809
  }
23699
- const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
23810
+ const file = await unnamedFile();
23700
23811
  try {
23701
- chmodSync(directory, 448);
23702
- const output = path.join(directory, "stdout");
23703
- const fd = openSync2(output, "wx", 384);
23704
- let result;
23812
+ let watched;
23705
23813
  try {
23706
- result = Bun.spawnSync(["/bin/sh", "-c", command], {
23814
+ watched = spawnWatched(["/bin/sh", "-c", command], {
23707
23815
  cwd,
23708
23816
  env: childEnv,
23709
- stdin: "ignore",
23710
- stdout: fd,
23711
- stderr: "ignore",
23712
- timeout: timeoutMs,
23713
- detached: true
23817
+ stdout: file.fd,
23818
+ stderr: "ignore"
23714
23819
  });
23715
23820
  } catch (error) {
23716
23821
  return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
23717
- } finally {
23718
- closeSync2(fd);
23719
23822
  }
23823
+ const { child, endGroup } = watched;
23824
+ let timedOut = false;
23825
+ const timer = setTimeout(() => {
23826
+ timedOut = true;
23827
+ endGroup();
23828
+ }, timeoutMs);
23720
23829
  try {
23721
- process.kill(-result.pid, "SIGKILL");
23722
- } catch {}
23723
- if (result.exitedDueToTimeout) {
23830
+ await child.exited;
23831
+ } finally {
23832
+ clearTimeout(timer);
23833
+ }
23834
+ endGroup();
23835
+ if (timedOut) {
23724
23836
  return {
23725
23837
  failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
23726
23838
  timedOut: true
23727
23839
  };
23728
23840
  }
23729
- if (!result.success) {
23841
+ if (child.exitCode !== 0) {
23730
23842
  return {
23731
- failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
23843
+ failure: `exited with ${child.signalCode ?? `status ${child.exitCode}`}`,
23732
23844
  timedOut: false
23733
23845
  };
23734
23846
  }
23735
- const value = readFileSync2(output, "utf-8").trim();
23847
+ const value = (await readOutput(file)).trim();
23736
23848
  if (value.length === 0)
23737
23849
  return { failure: "printed nothing", timedOut: false };
23738
23850
  if (!sendable(value)) {
@@ -23743,10 +23855,10 @@ function runCommand(command, env, cwd) {
23743
23855
  }
23744
23856
  return { value };
23745
23857
  } finally {
23746
- rmSync(directory, { recursive: true, force: true });
23858
+ await file.close();
23747
23859
  }
23748
23860
  }
23749
- function fileValue(value, field, filePath, env, commands = "run") {
23861
+ async function fileValue(value, field, filePath, env, commands = "run") {
23750
23862
  if (!value.startsWith("!")) {
23751
23863
  if (!sendable(value)) {
23752
23864
  throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
@@ -23762,42 +23874,50 @@ function fileValue(value, field, filePath, env, commands = "run") {
23762
23874
  throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
23763
23875
  }
23764
23876
  } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
23765
- outcome = { ...runCommand(command, env, cwd), at: Date.now() };
23766
- commandOutcomes.set(key, outcome);
23877
+ let run = commandRuns.get(key);
23878
+ if (run === undefined) {
23879
+ run = runCommand(command, env, cwd).then((ran) => {
23880
+ const kept = { ...ran, at: Date.now() };
23881
+ commandOutcomes.set(key, kept);
23882
+ return kept;
23883
+ }).finally(() => commandRuns.delete(key));
23884
+ commandRuns.set(key, run);
23885
+ }
23886
+ outcome = await run;
23767
23887
  }
23768
23888
  if ("failure" in outcome)
23769
23889
  throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
23770
23890
  return outcome.value;
23771
23891
  }
23772
- function statDevice(directory) {
23892
+ async function statDevice(directory) {
23773
23893
  try {
23774
- return statSync(directory).dev;
23894
+ return (await stat3(directory)).dev;
23775
23895
  } catch {
23776
23896
  return;
23777
23897
  }
23778
23898
  }
23779
- function moveNotice(oldFile, newFile, move, deviceOf) {
23780
- const oldDevice = deviceOf(path.dirname(oldFile));
23899
+ async function moveNotice(oldFile, newFile, move, deviceOf) {
23900
+ const oldDevice = await deviceOf(path.dirname(oldFile));
23781
23901
  let ancestor = path.dirname(newFile);
23782
- let newDevice = deviceOf(ancestor);
23902
+ let newDevice = await deviceOf(ancestor);
23783
23903
  while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
23784
23904
  ancestor = path.dirname(ancestor);
23785
- newDevice = deviceOf(ancestor);
23905
+ newDevice = await deviceOf(ancestor);
23786
23906
  }
23787
23907
  if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
23788
23908
  return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
23789
23909
  }
23790
23910
  return `${oldFile} is not read: ${move}`;
23791
23911
  }
23792
- function oldUserFileNotice(filePath, env, deviceOf) {
23912
+ async function oldUserFileNotice(filePath, env, deviceOf) {
23793
23913
  const home = nonEmpty(env.HOME) ?? homedir();
23794
23914
  const old = path.join(home, ".config", "opencode", "envoy.json");
23795
- if (!existsSync(old))
23915
+ if (!await exists(old))
23796
23916
  return;
23797
23917
  const selected = path.resolve(filePath);
23798
23918
  const userFile = path.resolve(home, ".config", "legion", "envoy.json");
23799
23919
  if (selected === userFile) {
23800
- return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
23920
+ return await moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
23801
23921
  }
23802
23922
  const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
23803
23923
  if (profileFile) {
@@ -23815,14 +23935,18 @@ function missingConfigNotice(filePath, missing, off) {
23815
23935
  const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
23816
23936
  return `no envoy.json at ${filePath}${link}: ${off}${old}`;
23817
23937
  }
23818
- function readEnvoyConfig(filePath, env, options) {
23938
+ async function readEnvoyConfig(filePath, env, options) {
23819
23939
  const deviceOf = options.deviceOf ?? statDevice;
23820
- const chosen = parseFile(filePath, EnvoyFileSchema, false);
23821
- if (chosen.kind === "invalid")
23822
- return { kind: "failed", path: filePath, error: chosen.reason };
23823
23940
  const resolvedChosen = path.resolve(filePath);
23824
23941
  const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
23825
- const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
23942
+ const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
23943
+ const [chosen, checkoutFile, oldCheckoutThere] = await Promise.all([
23944
+ parseFile(filePath, EnvoyFileSchema, false),
23945
+ checkoutPath === resolvedChosen ? Promise.resolve({ kind: "absent", link: null }) : parseFile(checkoutPath, CheckoutFileSchema, true),
23946
+ oldCheckout === resolvedChosen ? Promise.resolve(false) : exists(oldCheckout)
23947
+ ]);
23948
+ if (chosen.kind === "invalid")
23949
+ return { kind: "failed", path: filePath, error: chosen.reason };
23826
23950
  const own = chosen.kind === "valid" ? chosen.settings : {};
23827
23951
  let checkout = null;
23828
23952
  if (checkoutFile.kind === "invalid") {
@@ -23836,11 +23960,11 @@ function readEnvoyConfig(filePath, env, options) {
23836
23960
  askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
23837
23961
  };
23838
23962
  }
23839
- const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
23840
- const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
23841
- moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
23963
+ const checkoutMissing = checkoutPath === resolvedChosen ? chosen.kind === "absent" : checkoutFile.kind === "absent" || checkoutFile.kind === "invalid" && !await exists(checkoutPath);
23964
+ const warnings = oldCheckout !== resolvedChosen && checkoutMissing && oldCheckoutThere ? [
23965
+ await moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
23842
23966
  ] : [];
23843
- const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
23967
+ const unreadOldUserFile = chosen.kind === "absent" ? await oldUserFileNotice(filePath, env, deviceOf) : undefined;
23844
23968
  return {
23845
23969
  kind: "read",
23846
23970
  path: filePath,
@@ -23868,10 +23992,10 @@ function bearerCredential(token) {
23868
23992
  secret: () => token
23869
23993
  };
23870
23994
  }
23871
- function bearerSource(env, section, written) {
23995
+ async function bearerSource(env, section, written) {
23872
23996
  const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
23873
23997
  if (pointer !== undefined) {
23874
- return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
23998
+ return { kind: "variable", token: await readSecretFile(`${section}_TOKEN_FILE`, pointer) };
23875
23999
  }
23876
24000
  const plain = nonEmpty(env[`${section}_TOKEN`]);
23877
24001
  if (plain !== undefined) {
@@ -23883,7 +24007,7 @@ function bearerSource(env, section, written) {
23883
24007
  const bearer = written();
23884
24008
  return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
23885
24009
  }
23886
- function fileBearer(bearer, url, section, env, commands = "run") {
24010
+ async function fileBearer(bearer, url, section, env, commands = "run") {
23887
24011
  const named = httpUrl2(url)?.origin;
23888
24012
  const paired = httpUrl2(bearer.server)?.origin;
23889
24013
  if (named !== paired) {
@@ -31650,12 +31774,12 @@ async function reviewCommand(context) {
31650
31774
  }
31651
31775
 
31652
31776
  // ../envoy-client/src/session-answers.ts
31653
- import { mkdirSync, readFileSync as readFileSync3 } from "fs";
31777
+ import { mkdirSync, readFileSync } from "fs";
31654
31778
  import { join as join6 } from "path";
31655
31779
 
31656
31780
  // ../envoy-client/src/dispatch-session-directory.ts
31657
31781
  import { randomUUID as randomUUID3 } from "crypto";
31658
- import { renameSync, rmSync as rmSync2, writeFileSync } from "fs";
31782
+ import { renameSync, rmSync, writeFileSync } from "fs";
31659
31783
  import { homedir as homedir2 } from "os";
31660
31784
  import { join as join5 } from "path";
31661
31785
  var SESSION_ID_PATH_SEGMENT = /^[A-Za-z0-9._-]{1,128}$/;
@@ -31678,7 +31802,7 @@ function writeAtomically(path, text) {
31678
31802
  writeFileSync(temporary, text, { mode: PRIVATE_FILE });
31679
31803
  renameSync(temporary, path);
31680
31804
  } catch (error) {
31681
- rmSync2(temporary, { force: true });
31805
+ rmSync(temporary, { force: true });
31682
31806
  throw error;
31683
31807
  }
31684
31808
  }
@@ -31821,7 +31945,7 @@ processGlobal2[STATE_KEY] = state;
31821
31945
  var CACHE_FILE = "answers.json";
31822
31946
  function readCacheFile(directory, url) {
31823
31947
  try {
31824
- const value = JSON.parse(readFileSync3(join6(directory, CACHE_FILE), "utf-8"));
31948
+ const value = JSON.parse(readFileSync(join6(directory, CACHE_FILE), "utf-8"));
31825
31949
  if (typeof value === "object" && value !== null && "dispatch_url" in value && typeof value.dispatch_url === "string" && value.dispatch_url === url && "read_at" in value && typeof value.read_at === "string" && "total" in value && typeof value.total === "number" && "items" in value && Array.isArray(value.items)) {
31826
31950
  return {
31827
31951
  dispatch_url: value.dispatch_url,
@@ -32022,13 +32146,29 @@ async function whoamiCommand(context) {
32022
32146
  const service = identity.kind === "agent" ? identity.service ?? null : null;
32023
32147
  const proved = identity.kind === "agent" ? identity.session ?? null : null;
32024
32148
  const project = identity.kind === "agent" ? identity.project ?? null : null;
32149
+ const readOnly = identity.scopes?.includes("read") === true;
32150
+ const cut = identity.kind === "agent" ? identity.cut ?? null : null;
32025
32151
  const session = proved ?? sessionId;
32026
32152
  const unowned = "no owner, so an issue you create without an assignee takes its parent's assignee when the parent is in the same project, else the project's default assignee, which every project names, so the issue always has one.";
32027
32153
  const answered = identity.kind === "agent" ? identity.sign_in_required : undefined;
32028
32154
  const signInNeeded = answered ?? (owner === null && service !== null && proved !== null);
32029
- const acting = owner !== null ? `Session ${session} acts for ${owner}: issues you create without an assignee are assigned to ${owner}.` : service !== null ? signInNeeded ? `Session ${session} runs as service ${serviceSubjectLabel(service)} and no person, so it may read but Dispatch refuses every write it makes: run \`agent-secrets login\` on this machine to write as yourself.` : `Session ${session} runs as service ${serviceSubjectLabel(service)}: ${unowned}` : `Session ${session} runs under the shared token: ${unowned}`;
32030
- const elsewhere = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId}): Dispatch records every write you make as ${proved}.` : "";
32031
- const writable = project !== null ? ` It may write project ${project} and no other.` : "";
32155
+ const who = owner !== null ? `acts for ${owner}` : service !== null ? `runs as service ${serviceSubjectLabel(service)}` : "runs";
32156
+ const named = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId})` : "";
32157
+ let acting;
32158
+ let elsewhere = named === "" ? "" : `${named}: Dispatch records every write you make as ${proved}.`;
32159
+ if (readOnly) {
32160
+ acting = `Session ${session} ${who} with a read-only credential: it may read, and Dispatch refuses every write it makes.${cut === null ? "" : ` Its cut is ${cut}, the past time it reads Dispatch at.`}`;
32161
+ elsewhere = named === "" ? "" : `${named}.`;
32162
+ } else if (owner !== null) {
32163
+ acting = `Session ${session} ${who}: issues you create without an assignee are assigned to ${owner}.`;
32164
+ } else if (signInNeeded) {
32165
+ acting = `Session ${session} ${who} and no person, so it may read but Dispatch refuses every write it makes: run \`agent-secrets login\` on this machine to write as yourself.`;
32166
+ } else if (service !== null) {
32167
+ acting = `Session ${session} ${who}: ${unowned}`;
32168
+ } else {
32169
+ acting = `Session ${session} runs under the shared token: ${unowned}`;
32170
+ }
32171
+ const writable = project !== null && !readOnly ? ` It may write project ${project} and no other.` : "";
32032
32172
  return {
32033
32173
  text: acting + elsewhere + writable,
32034
32174
  details: { session, owner, service, project }
@@ -32298,7 +32438,7 @@ async function executeDispatchTool(input) {
32298
32438
  }
32299
32439
 
32300
32440
  // ../envoy-client/src/dispatch-first.ts
32301
- import { readFileSync as readFileSync4 } from "fs";
32441
+ import { readFileSync as readFileSync2 } from "fs";
32302
32442
  import { join as join7 } from "path";
32303
32443
  var DISPATCH_FIRST_MARKER = "<dispatch-first-skill>";
32304
32444
  function dispatchFirstSkillFile(skillsDirectory) {
@@ -32307,7 +32447,7 @@ function dispatchFirstSkillFile(skillsDirectory) {
32307
32447
  function readDispatchFirstContext(skillFile) {
32308
32448
  let skill;
32309
32449
  try {
32310
- skill = readFileSync4(skillFile, "utf8");
32450
+ skill = readFileSync2(skillFile, "utf8");
32311
32451
  } catch (error) {
32312
32452
  throw new Error(`the dispatch-first skill ${skillFile} could not be read: ${messageFor(error)}`);
32313
32453
  }
@@ -32697,6 +32837,11 @@ async function importDpopKey(pkcs8Pem, name) {
32697
32837
  // ../cipher-client/src/device-login.ts
32698
32838
  var BROKER_SETTING = "AGENT_SECRETS_URL";
32699
32839
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
32840
+ function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
32841
+ if (leastLifeMs === undefined || lifeSeconds === null)
32842
+ return ACCESS_MARGIN_MS;
32843
+ return Math.max(ACCESS_MARGIN_MS, Math.min(leastLifeMs, lifeSeconds * 1000 / 2));
32844
+ }
32700
32845
  var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
32701
32846
  var DEFAULT_POLL_SECONDS = 5;
32702
32847
  var LEAST_POLL_SECONDS = 1;
@@ -32772,7 +32917,8 @@ function loginOf(key, broker, answered, now) {
32772
32917
  expiresAt,
32773
32918
  broker,
32774
32919
  accessToken: holdSecret(answered.access_token, accessExpiresAt),
32775
- accessExpiresAt
32920
+ accessExpiresAt,
32921
+ accessLifeSeconds: seconds
32776
32922
  };
32777
32923
  }
32778
32924
  async function startDeviceLogin(options) {
@@ -32904,7 +33050,7 @@ class DeviceLoginIdentity {
32904
33050
  }
32905
33051
  return this.#key;
32906
33052
  }
32907
- async spend(trade, signal) {
33053
+ async spend(trade, signal, leastLifeMs) {
32908
33054
  const { thumbprint } = await this.#loaded();
32909
33055
  return await withDeviceLoginLock(this.#path, async (held) => {
32910
33056
  let login = await readDeviceLogin(this.#path);
@@ -32916,7 +33062,8 @@ class DeviceLoginIdentity {
32916
33062
  }
32917
33063
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
32918
33064
  const expires = login.accessExpiresAt?.getTime() ?? 0;
32919
- let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
33065
+ const least = leastAccessLifeMs(leastLifeMs, login.accessLifeSeconds);
33066
+ let refreshed = login.accessToken === "" || expires - Date.now() < least;
32920
33067
  if (refreshed)
32921
33068
  login = await refresh();
32922
33069
  while (true) {
@@ -33248,14 +33395,14 @@ function poolIdentity(options) {
33248
33395
  }
33249
33396
 
33250
33397
  // ../cipher-client/src/projected-token.ts
33251
- import { readFile as readFile3 } from "fs/promises";
33398
+ import { readFile as readFile5 } from "fs/promises";
33252
33399
  function projectedToken(path, variable) {
33253
33400
  const named = `the projected service-account token ${variable} names`;
33254
33401
  return {
33255
33402
  async read(signal) {
33256
33403
  let contents;
33257
33404
  try {
33258
- contents = await readFile3(path, {
33405
+ contents = await readFile5(path, {
33259
33406
  encoding: "utf8",
33260
33407
  ...signal === undefined ? {} : { signal }
33261
33408
  });
@@ -33364,13 +33511,15 @@ function tradeProjects(env) {
33364
33511
  }
33365
33512
  return sorted;
33366
33513
  }
33367
- async function brokerTokenClient(env, own = "") {
33514
+ async function brokerTokenClient(env, own = "", read) {
33368
33515
  const brokerUrl = value(env, BROKER_URL_VAR);
33369
33516
  const machine = machineIdentity(env);
33370
33517
  if (brokerUrl === "" || machine === undefined)
33371
33518
  return;
33372
33519
  if (!isHttpUrl(brokerUrl))
33373
33520
  throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
33521
+ const narrowed = read === undefined ? {} : { scope: SCOPE_READ, asOf: read.asOf };
33522
+ const heldApart = async () => read === undefined ? {} : { ...narrowed, holderKey: await newDpopKey() };
33374
33523
  if (machine instanceof DeviceLoginIdentity) {
33375
33524
  if (personTradeOff(env)) {
33376
33525
  throw new Error(`${PERSON_TRADE_VAR}=off turns off every trade made as a person, and ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} trades this machine's device login as the person who approved it; unset one of them`);
@@ -33380,7 +33529,8 @@ async function brokerTokenClient(env, own = "") {
33380
33529
  key: await machine.key(),
33381
33530
  subject: machine,
33382
33531
  session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
33383
- projects: tradeProjects(env)
33532
+ projects: tradeProjects(env),
33533
+ ...await heldApart()
33384
33534
  });
33385
33535
  return { client, signIn: undefined };
33386
33536
  }
@@ -33391,7 +33541,8 @@ async function brokerTokenClient(env, own = "") {
33391
33541
  key: await newDpopKey(),
33392
33542
  subject: machine,
33393
33543
  session: tradeSession(env, own),
33394
- launcherCredential: false
33544
+ launcherCredential: false,
33545
+ ...narrowed
33395
33546
  });
33396
33547
  return { client, signIn: undefined };
33397
33548
  }
@@ -33405,7 +33556,8 @@ async function brokerTokenClient(env, own = "") {
33405
33556
  subject: personIdentity(record, flow),
33406
33557
  actor: machine,
33407
33558
  session: own.trim() || signInSessionName(record),
33408
- projects: tradeProjects(env)
33559
+ projects: tradeProjects(env),
33560
+ ...await heldApart()
33409
33561
  });
33410
33562
  return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
33411
33563
  }
@@ -33438,11 +33590,11 @@ function forgetBrokerSession(session) {
33438
33590
  function signInName(record) {
33439
33591
  return `${record.person}\x00${record.thumbprint}`;
33440
33592
  }
33441
- function keyOf(env, own) {
33442
- return {
33443
- session: own.trim(),
33444
- variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
33445
- };
33593
+ function keyOf(env, own, read) {
33594
+ const values = BROKER_VARIABLES.map((name) => env[name]);
33595
+ if (read !== undefined)
33596
+ values.push({ read: true, asOf: read.asOf ?? "" });
33597
+ return { session: own.trim(), variables: JSON.stringify(values) };
33446
33598
  }
33447
33599
  function entryFor(key) {
33448
33600
  let sessions = CLIENTS.get(key.session);
@@ -33457,13 +33609,13 @@ function entryFor(key) {
33457
33609
  }
33458
33610
  return entry;
33459
33611
  }
33460
- async function make(env, own) {
33461
- const made = await brokerTokenClient(env, own);
33612
+ async function make(env, own, read) {
33613
+ const made = await brokerTokenClient(env, own, read);
33462
33614
  const signIn = made?.signIn;
33463
33615
  return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
33464
33616
  }
33465
- async function clientFor(env, own) {
33466
- const key = keyOf(env, own);
33617
+ async function clientFor(env, own, read) {
33618
+ const key = keyOf(env, own, read);
33467
33619
  const entry = entryFor(key);
33468
33620
  if (entry.refused.size > 0) {
33469
33621
  const record = await chooseSignIn(env);
@@ -33478,7 +33630,7 @@ async function clientFor(env, own) {
33478
33630
  }
33479
33631
  let making = entry.making;
33480
33632
  if (making === undefined) {
33481
- const started = make(env, key.session);
33633
+ const started = make(env, key.session, read);
33482
33634
  making = started;
33483
33635
  entry.making = started;
33484
33636
  started.then((made) => {
@@ -33508,13 +33660,13 @@ function untilAborted(promise, signal) {
33508
33660
  });
33509
33661
  });
33510
33662
  }
33511
- async function tradedToken(env, own, signal, waitForReady = false) {
33512
- const { entry, made } = await untilAborted(clientFor(env, own), signal);
33663
+ async function tradedToken(env, own, { signal, waitForReady = false, read }) {
33664
+ const { entry, made } = await untilAborted(clientFor(env, own, read), signal);
33513
33665
  const { client } = made;
33514
33666
  if (client === undefined) {
33515
33667
  throw new LoggableError("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
33516
33668
  }
33517
- const { session, variables } = keyOf(env, own);
33669
+ const { session, variables } = keyOf(env, own, read);
33518
33670
  try {
33519
33671
  return {
33520
33672
  token: await client.token(signal, { waitForReady }),
@@ -33529,7 +33681,7 @@ async function tradedToken(env, own, signal, waitForReady = false) {
33529
33681
  }
33530
33682
  }
33531
33683
  function brokerTokenFor(env, session) {
33532
- return (signal, waitForReady) => tradedToken(env, sessionName(session), signal, waitForReady);
33684
+ return (signal, waitForReady) => tradedToken(env, sessionName(session), { signal, waitForReady });
33533
33685
  }
33534
33686
  function dropHeld(key, token) {
33535
33687
  CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop(token);
@@ -33537,14 +33689,14 @@ function dropHeld(key, token) {
33537
33689
  function dropTradedToken(env, traded) {
33538
33690
  dropHeld(keyOf(env, traded.session), traded.token.accessToken);
33539
33691
  }
33540
- function brokerCredential(env, session) {
33692
+ function brokerCredential(env, session, read) {
33541
33693
  let presented = "";
33542
33694
  const presentedAs = new WeakMap;
33543
33695
  const own = (acting) => (acting ?? "").trim() || sessionName(session);
33544
33696
  return {
33545
33697
  scheme: "DPoP",
33546
33698
  async headers(method, url, acting, signal) {
33547
- const traded = await tradedToken(env, own(acting), signal);
33699
+ const traded = await tradedToken(env, own(acting), { signal, read });
33548
33700
  const { token, key, identity } = traded;
33549
33701
  presented = token.accessToken;
33550
33702
  const headers = {
@@ -33553,7 +33705,7 @@ function brokerCredential(env, session) {
33553
33705
  };
33554
33706
  presentedAs.set(headers, {
33555
33707
  identity,
33556
- key: keyOf(env, traded.session),
33708
+ key: keyOf(env, traded.session, read),
33557
33709
  token: token.accessToken
33558
33710
  });
33559
33711
  return headers;
@@ -33561,8 +33713,61 @@ function brokerCredential(env, session) {
33561
33713
  identity: (headers) => presentedAs.get(headers)?.identity,
33562
33714
  stale(acting, headers) {
33563
33715
  const told = headers === undefined ? undefined : presentedAs.get(headers);
33564
- dropHeld(told?.key ?? keyOf(env, own(acting)), told?.token);
33716
+ dropHeld(told?.key ?? keyOf(env, own(acting), read), told?.token);
33717
+ },
33718
+ secret: () => presented
33719
+ };
33720
+ }
33721
+
33722
+ // ../envoy-client/src/file-token-credential.ts
33723
+ import { readFileSync as readFileSync3 } from "fs";
33724
+ var TOKEN_FILE_VAR = "DISPATCH_BROKER_TOKEN_FILE";
33725
+ var DPOP_KEY_FILE_VAR = "DISPATCH_BROKER_DPOP_KEY_FILE";
33726
+ var PKCS8_LABEL = "PRIVATE KEY";
33727
+ var PKCS8_PEM = new RegExp(`^-----BEGIN ${PKCS8_LABEL}-----\\r?\\n(?:[A-Za-z0-9+/=]+\\r?\\n)+-----END ${PKCS8_LABEL}-----$`);
33728
+ function readNamed(variable, filePath) {
33729
+ try {
33730
+ return readFileSync3(filePath, "utf8");
33731
+ } catch (error) {
33732
+ throw new Error(`${variable} names ${filePath}, which could not be read (${readErrorCode(error)})`);
33733
+ }
33734
+ }
33735
+ function tokenIn(filePath) {
33736
+ const token = readNamed(TOKEN_FILE_VAR, filePath).trim();
33737
+ if (token === "") {
33738
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds no token: it is empty or blank`);
33739
+ }
33740
+ if (!sendable(token)) {
33741
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds whitespace or a control character inside its token`);
33742
+ }
33743
+ return holdSecret(token);
33744
+ }
33745
+ async function keyIn(filePath) {
33746
+ const pem = readNamed(DPOP_KEY_FILE_VAR, filePath).trim();
33747
+ if (!PKCS8_PEM.test(pem)) {
33748
+ throw new Error(`${DPOP_KEY_FILE_VAR} names ${filePath}, which does not hold one P-256 private key in PKCS#8 PEM`);
33749
+ }
33750
+ return await importDpopKey(pem, `${DPOP_KEY_FILE_VAR}'s key ${filePath}`);
33751
+ }
33752
+ function fileTokenCredential(files, dispatchUrl) {
33753
+ const origin = httpUrl2(dispatchUrl)?.origin;
33754
+ let presented = "";
33755
+ return {
33756
+ scheme: "DPoP",
33757
+ async headers(method, url) {
33758
+ const target = httpUrl2(url)?.origin;
33759
+ if (origin === undefined || target !== origin) {
33760
+ throw new Error(`the token ${TOKEN_FILE_VAR} names goes to DISPATCH_URL's origin (${origin}) alone, and this request is for ${target ?? "a URL that is not http or https"}`);
33761
+ }
33762
+ const token = tokenIn(files.tokenFile);
33763
+ const key = await keyIn(files.keyFile);
33764
+ presented = token;
33765
+ return {
33766
+ Authorization: `DPoP ${token}`,
33767
+ DPoP: await key.proof({ method, url, accessToken: token })
33768
+ };
33565
33769
  },
33770
+ stale() {},
33566
33771
  secret: () => presented
33567
33772
  };
33568
33773
  }
@@ -33610,14 +33815,20 @@ function lostDispatchUrlNotice(env, config) {
33610
33815
  ...old === undefined ? [] : [old]
33611
33816
  ].join("; ");
33612
33817
  }
33613
- function dispatchSettings(env, config, options = {}) {
33614
- const target = dispatchTarget(env, config);
33818
+ async function dispatchSettings(env, config, options = {}) {
33819
+ const target = await dispatchTarget(env, config, options.tokenFiles === true);
33615
33820
  if (!target.enabled)
33616
33821
  return target;
33617
33822
  const { url, urlSetting, source } = target;
33618
33823
  let credential;
33619
33824
  try {
33620
- credential = source.kind === "broker" ? brokerCredential(env, options.session) : bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
33825
+ if (source.kind === "broker")
33826
+ credential = brokerCredential(env, options.session, source.read);
33827
+ else if (source.kind === "files")
33828
+ credential = fileTokenCredential(source, url);
33829
+ else {
33830
+ credential = bearerCredential(source.kind === "variable" ? source.token : await fileBearer(source, url, "DISPATCH", env, options.commands));
33831
+ }
33621
33832
  } catch (error) {
33622
33833
  return offWithError(messageFor(error));
33623
33834
  }
@@ -33636,10 +33847,67 @@ function dispatchSettings(env, config, options = {}) {
33636
33847
  ...linkNotice === undefined ? {} : { linkNotice }
33637
33848
  };
33638
33849
  }
33639
- function dispatchUrl(env, config) {
33640
- const target = dispatchTarget(env, config);
33850
+ async function dispatchUrl(env, config) {
33851
+ const target = await dispatchTarget(env, config);
33641
33852
  return target.enabled ? target.url : undefined;
33642
33853
  }
33854
+ var BESIDE_TOKEN_FILES = [
33855
+ "DISPATCH_TOKEN_BROKER",
33856
+ "DISPATCH_TOKEN_BROKER_READ",
33857
+ "DISPATCH_TOKEN_BROKER_AS_OF",
33858
+ "DISPATCH_TOKEN",
33859
+ "DISPATCH_TOKEN_FILE",
33860
+ BROKER_URL_VAR,
33861
+ IDENTITY_VAR
33862
+ ];
33863
+ function tokenFilesSet(env) {
33864
+ const set = [
33865
+ ...nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE) === undefined ? [] : [TOKEN_FILE_VAR],
33866
+ ...nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE) === undefined ? [] : [DPOP_KEY_FILE_VAR]
33867
+ ];
33868
+ if (set.length === 0)
33869
+ return;
33870
+ return `${set.join(" and ")} ${set.length === 1 ? "is" : "are"} set`;
33871
+ }
33872
+ function settingsBesideTokenFiles(env) {
33873
+ return BESIDE_TOKEN_FILES.filter((name) => nonEmpty(env[name]) !== undefined).map((name) => `${name} is set`);
33874
+ }
33875
+ function tokenFilesTarget(env, config, taken) {
33876
+ const set = tokenFilesSet(env);
33877
+ if (set === undefined)
33878
+ return;
33879
+ if (!taken) {
33880
+ return offWithError(`${set}, and only the dispatch command reads the token files: Dispatch is off here rather than written with another credential beside them`);
33881
+ }
33882
+ const tokenFile = nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE);
33883
+ const keyFile = nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE);
33884
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
33885
+ const { checkout } = config;
33886
+ const problems = [
33887
+ ...tokenFile === undefined ? [`${TOKEN_FILE_VAR} is not set`] : [],
33888
+ ...keyFile === undefined ? [`${DPOP_KEY_FILE_VAR} is not set`] : [],
33889
+ ...explicitUrl === undefined ? ["DISPATCH_URL is not set"] : [],
33890
+ ...settingsBesideTokenFiles(env),
33891
+ ...config.dispatch.token === undefined ? [] : [`dispatch.token is set in ${config.path}`],
33892
+ ...checkout?.kind === "valid" && checkout.dispatch.token !== undefined ? [`dispatch.token is set in ${checkout.path}`] : [],
33893
+ ...checkout?.kind === "invalid" ? [`${checkout.error}, so whether it sets dispatch.token cannot be told`] : []
33894
+ ];
33895
+ if (problems.length > 0 || tokenFile === undefined || keyFile === undefined || explicitUrl === undefined) {
33896
+ return offWithError(`${TOKEN_FILE_VAR} and ${DPOP_KEY_FILE_VAR} go together, with DISPATCH_URL, as the dispatch command's only Dispatch credential: ${problems.join("; ")}`);
33897
+ }
33898
+ if (config.dispatch.enabled === false) {
33899
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
33900
+ }
33901
+ if (httpUrl2(explicitUrl) === undefined) {
33902
+ return offWithError("DISPATCH_URL must be an http or https URL");
33903
+ }
33904
+ return {
33905
+ enabled: true,
33906
+ url: withoutTrailingSlashes(explicitUrl),
33907
+ urlSetting: "DISPATCH_URL",
33908
+ source: { kind: "files", tokenFile, keyFile }
33909
+ };
33910
+ }
33643
33911
  function brokerRouteForced(env) {
33644
33912
  const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
33645
33913
  if (written === "")
@@ -33648,12 +33916,55 @@ function brokerRouteForced(env) {
33648
33916
  return true;
33649
33917
  return offWithError("DISPATCH_TOKEN_BROKER takes 1: set it to 1 where this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and leave it unset where a bearer is read as usual");
33650
33918
  }
33651
- function dispatchTarget(env, config) {
33919
+ var CUT_FORM = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
33920
+ var ZERO_TIME = Date.parse("0001-01-01T00:00:00.000Z");
33921
+ function isCut(text) {
33922
+ const parts = CUT_FORM.exec(text);
33923
+ if (parts === null)
33924
+ return false;
33925
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = parts.slice(1, 7).map((part) => Number(part ?? "0"));
33926
+ const [zoneHour = 0, zoneMinute = 0] = parts.slice(9, 11).map((part) => Number(part ?? "0"));
33927
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
33928
+ const exists = month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth && hour <= 23 && minute <= 59 && second <= 59 && zoneHour <= 23 && zoneMinute <= 59;
33929
+ if (!exists)
33930
+ return false;
33931
+ const offset = (parts[8] === "-" ? -1 : 1) * (zoneHour * 60 + zoneMinute);
33932
+ const instant = new Date(0);
33933
+ instant.setUTCFullYear(year, month - 1, day);
33934
+ instant.setUTCHours(hour, minute - offset, second, 0);
33935
+ return Number(parts[7] ?? "0") !== 0 || instant.getTime() !== ZERO_TIME;
33936
+ }
33937
+ function readTradeSetting(env) {
33938
+ const read = (env.DISPATCH_TOKEN_BROKER_READ ?? "").trim();
33939
+ const cut = (env.DISPATCH_TOKEN_BROKER_AS_OF ?? "").trim();
33940
+ if (read !== "" && read !== "1") {
33941
+ return offWithError("DISPATCH_TOKEN_BROKER_READ takes 1: set it to 1 where this session's Dispatch credential is a broker token that only reads, and leave it unset where it writes");
33942
+ }
33943
+ if (read === "") {
33944
+ if (cut === "")
33945
+ return;
33946
+ return offWithError("DISPATCH_TOKEN_BROKER_AS_OF names the cut a read-only token reads at, and goes only beside DISPATCH_TOKEN_BROKER_READ=1: set DISPATCH_TOKEN_BROKER_READ to 1 beside it, or unset DISPATCH_TOKEN_BROKER_AS_OF");
33947
+ }
33948
+ if (cut === "")
33949
+ return {};
33950
+ if (!isCut(cut)) {
33951
+ return offWithError("DISPATCH_TOKEN_BROKER_AS_OF is not an RFC 3339 time with at most six fractional digits and Z or a numeric offset, such as 1999-12-31T23:59:59Z");
33952
+ }
33953
+ return { asOf: cut };
33954
+ }
33955
+ async function dispatchTarget(env, config, tokenFiles = false) {
33652
33956
  if (config.kind === "failed")
33653
33957
  return offWithError(config.error);
33654
- const forced = brokerRouteForced(env);
33655
- if (typeof forced !== "boolean")
33656
- return forced;
33958
+ const files = tokenFilesTarget(env, config, tokenFiles);
33959
+ if (files !== undefined)
33960
+ return files;
33961
+ const brokerOnly = brokerRouteForced(env);
33962
+ if (typeof brokerOnly !== "boolean")
33963
+ return brokerOnly;
33964
+ const read = readTradeSetting(env);
33965
+ if (read !== undefined && "enabled" in read)
33966
+ return read;
33967
+ const forced = brokerOnly || read !== undefined;
33657
33968
  const explicitUrl = nonEmpty(env.DISPATCH_URL);
33658
33969
  const checkoutFile = explicitUrl === undefined ? config.checkout : null;
33659
33970
  if (checkoutFile?.kind === "invalid")
@@ -33680,7 +33991,7 @@ function dispatchTarget(env, config) {
33680
33991
  let source = { kind: "none" };
33681
33992
  if (!forced) {
33682
33993
  try {
33683
- source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33994
+ source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : await bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33684
33995
  } catch (error) {
33685
33996
  return offWithError(messageFor(error));
33686
33997
  }
@@ -33695,10 +34006,10 @@ function dispatchTarget(env, config) {
33695
34006
  if (route.traded) {
33696
34007
  const brokered = withoutTrailingSlashes(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
33697
34008
  const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
33698
- return { enabled: true, url: brokered, urlSetting, source: { kind: "broker" } };
34009
+ return { enabled: true, url: brokered, urlSetting, source: { kind: "broker", read } };
33699
34010
  }
33700
34011
  if (forced) {
33701
- return offWithError(`DISPATCH_TOKEN_BROKER is set, so this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
34012
+ return offWithError(`${read === undefined ? "DISPATCH_TOKEN_BROKER" : "DISPATCH_TOKEN_BROKER_READ"} is set, so this session's Dispatch credential is traded at the secrets broker (the person signed in on this machine, else the machine's own identity), and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
33702
34013
  }
33703
34014
  return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
33704
34015
  }
@@ -33884,7 +34195,6 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
33884
34195
  admissions: () => admissions
33885
34196
  };
33886
34197
  }
33887
- var RENEW_FLOOR_MS = 1000;
33888
34198
  var RETRY_FIRST_MS = 2000;
33889
34199
  var RETRY_LAST_MS = 60000;
33890
34200
  var WARN_AGAIN_MS = 30 * 60000;
@@ -33941,11 +34251,7 @@ function warnedEvery(warn) {
33941
34251
  };
33942
34252
  }
33943
34253
  function renewDelay(expiry, now) {
33944
- const remaining = expiry - now;
33945
- if (remaining <= 0)
33946
- return 0;
33947
- const ahead = remaining - Math.min(DEFAULT_RENEW_BEFORE_MS, remaining / 2);
33948
- return Math.max(Math.min(RENEW_FLOOR_MS, remaining / 2), ahead);
34254
+ return renewalAt(expiry, now, DEFAULT_RENEW_BEFORE_MS) - now;
33949
34255
  }
33950
34256
  function keepNatsCredential(connection, credential, warn) {
33951
34257
  let stopped = false;
@@ -34119,13 +34425,13 @@ function resolvedInterval(raw, fallback) {
34119
34425
  return named === undefined ? fallback : Math.min(Math.max(named, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
34120
34426
  }
34121
34427
  var ENVOY_INBOUND_VAR = "ENVOY_INBOUND";
34122
- function natsSeedFromEnvironment(env) {
34428
+ async function natsSeedFromEnvironment(env) {
34123
34429
  const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
34124
34430
  if (file !== undefined) {
34125
34431
  if (file === "")
34126
34432
  throw new Error("NATS_NKEY_SEED_FILE is set but empty");
34127
34433
  return {
34128
- value: readSecretFile("NATS_NKEY_SEED_FILE", file),
34434
+ value: await readSecretFile("NATS_NKEY_SEED_FILE", file),
34129
34435
  source: "the file NATS_NKEY_SEED_FILE names"
34130
34436
  };
34131
34437
  }
@@ -34154,23 +34460,23 @@ function requireFileServers(section, namedNatsUrls, filePath, remedy) {
34154
34460
  throw new Error(`ENVOY_NATS_URL names other servers than ${filePath}'s envoy.natsUrls; set ${remedy} for them`);
34155
34461
  }
34156
34462
  }
34157
- function natsSeed(env, section, namedNatsUrls, filePath) {
34158
- const fromEnvironment = natsSeedFromEnvironment(env);
34463
+ async function natsSeed(env, section, namedNatsUrls, filePath) {
34464
+ const fromEnvironment = await natsSeedFromEnvironment(env);
34159
34465
  if (fromEnvironment !== undefined || section.natsSeed === undefined)
34160
34466
  return fromEnvironment;
34161
34467
  requireFileServers(section, namedNatsUrls, filePath, "NATS_NKEY_SEED_FILE");
34162
34468
  return {
34163
- value: fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
34469
+ value: await fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
34164
34470
  source: `envoy.natsSeed in ${filePath}`
34165
34471
  };
34166
34472
  }
34167
- function natsCredential(env, section, namedNatsUrls, filePath, session) {
34473
+ async function natsCredential(env, section, namedNatsUrls, filePath, session) {
34168
34474
  const named = nonEmpty(env.NATS_AUTH);
34169
34475
  const auth = named !== undefined ? { value: named, source: NATS_AUTH_VAR } : section.natsAuth === undefined ? undefined : { value: section.natsAuth, source: `envoy.natsAuth in ${filePath}` };
34170
34476
  if (auth !== undefined && auth.value !== "broker" && auth.value !== "none") {
34171
34477
  throw new Error(`${auth.source} is neither broker nor none`);
34172
34478
  }
34173
- const seed = natsSeed(env, section, namedNatsUrls, filePath);
34479
+ const seed = await natsSeed(env, section, namedNatsUrls, filePath);
34174
34480
  if (seed !== undefined) {
34175
34481
  if (auth?.value === "broker") {
34176
34482
  throw new Error(`${auth.source} is ${auth.value}, and ${seed.source} names an nkey seed: set one of the two`);
@@ -34215,7 +34521,7 @@ function plainHttpOffMachine(url) {
34215
34521
  const host = URL.canParse(url) ? new URL(url) : undefined;
34216
34522
  return host?.protocol === "http:" && !LOOPBACK_HOST2.test(host.hostname) ? host.hostname : undefined;
34217
34523
  }
34218
- function envoySettings(env, config, options = {}) {
34524
+ async function envoySettings(env, config, options = {}) {
34219
34525
  if (config.kind === "failed")
34220
34526
  return offWithError(config.error);
34221
34527
  const section = config.envoy;
@@ -34246,7 +34552,7 @@ function envoySettings(env, config, options = {}) {
34246
34552
  let credential;
34247
34553
  let noBrokerRoute = "";
34248
34554
  try {
34249
- const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
34555
+ const source = await bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
34250
34556
  token: section.token,
34251
34557
  field: "envoy.token",
34252
34558
  path: config.path,
@@ -34259,7 +34565,7 @@ function envoySettings(env, config, options = {}) {
34259
34565
  if (!route.traded)
34260
34566
  noBrokerRoute = route.gap;
34261
34567
  } else {
34262
- credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
34568
+ credential = bearerCredential(source.kind === "variable" ? source.token : await fileBearer(source, url, "ENVOY", env));
34263
34569
  }
34264
34570
  } catch (error) {
34265
34571
  return offWithError(messageFor(error));
@@ -34279,7 +34585,7 @@ function envoySettings(env, config, options = {}) {
34279
34585
  inbound = {
34280
34586
  natsUrls,
34281
34587
  natsServersSetting: natsSetting,
34282
- natsCredential: natsCredential(env, section, namedNatsUrls, config.path, options.session)
34588
+ natsCredential: await natsCredential(env, section, namedNatsUrls, config.path, options.session)
34283
34589
  };
34284
34590
  } catch (error) {
34285
34591
  inbound = error instanceof NoSessionNamedError ? { off: messageFor(error), noSessionNamed: true } : { off: messageFor(error) };
@@ -34363,42 +34669,45 @@ function startNotice(config, dispatch, envoy, nats, lost) {
34363
34669
  }
34364
34670
  return parts.length === 0 ? null : parts.join("; ");
34365
34671
  }
34366
- function sessionSettings(file, env, options) {
34672
+ async function sessionSettings(file, env, options) {
34367
34673
  if (file.path === null) {
34368
34674
  const off = offWithError(file.error);
34369
34675
  return { dispatch: off, envoy: off, notice: `${file.error}: Dispatch and Envoy are off` };
34370
34676
  }
34371
- const config = readEnvoyConfig(file.path, env, options);
34372
- const dispatch = dispatchSettings(env, config, { session: options.session });
34373
- const envoy = envoySettings(env, config, { nats: options.nats, session: options.session });
34677
+ const config = await readEnvoyConfig(file.path, env, options);
34678
+ const [dispatch, envoy] = await Promise.all([
34679
+ dispatchSettings(env, config, { session: options.session }),
34680
+ envoySettings(env, config, { nats: options.nats, session: options.session })
34681
+ ]);
34374
34682
  return {
34375
34683
  dispatch,
34376
34684
  envoy,
34377
34685
  notice: startNotice(config, dispatch, envoy, options.nats !== false, config.kind === "read" ? lostDispatchUrlNotice(env, config) : undefined)
34378
34686
  };
34379
34687
  }
34380
- function sessionDispatchSettings(file, env, options) {
34688
+ async function sessionDispatchSettings(file, env, options) {
34381
34689
  if (file.path === null)
34382
34690
  return { dispatch: offWithError(file.error), warnings: [], missing: null };
34383
- const config = readEnvoyConfig(file.path, env, options);
34691
+ const config = await readEnvoyConfig(file.path, env, options);
34384
34692
  return {
34385
- dispatch: dispatchSettings(env, config, {
34693
+ dispatch: await dispatchSettings(env, config, {
34386
34694
  commands: options.commands,
34387
- session: options.session
34695
+ session: options.session,
34696
+ tokenFiles: options.tokenFiles
34388
34697
  }),
34389
34698
  warnings: config.kind === "read" ? config.warnings : [],
34390
34699
  missing: config.kind === "read" ? config.missing : null
34391
34700
  };
34392
34701
  }
34393
- function sessionDispatchUrl(file, env, options) {
34702
+ async function sessionDispatchUrl(file, env, options) {
34394
34703
  if (file.path === null)
34395
34704
  return;
34396
- return dispatchUrl(env, readEnvoyConfig(file.path, env, options));
34705
+ return dispatchUrl(env, await readEnvoyConfig(file.path, env, options));
34397
34706
  }
34398
- function sessionEnvoySettings(file, env, options) {
34707
+ async function sessionEnvoySettings(file, env, options) {
34399
34708
  if (file.path === null)
34400
34709
  return offWithError(file.error);
34401
- return envoySettings(env, readEnvoyConfig(file.path, env, options), {
34710
+ return envoySettings(env, await readEnvoyConfig(file.path, env, options), {
34402
34711
  nats: options.nats,
34403
34712
  session: options.session
34404
34713
  });
@@ -34496,12 +34805,7 @@ async function userConfigChain(timeoutMs = JJ_CONFIG_PATH_TIMEOUT_MS, env = proc
34496
34805
  stdout: "pipe",
34497
34806
  stderr: "pipe"
34498
34807
  });
34499
- const killGroup = () => {
34500
- try {
34501
- process.kill(-child.pid, "SIGKILL");
34502
- } catch {}
34503
- };
34504
- const exited = child.exited.finally(killGroup);
34808
+ const exited = child.exited.finally(() => killGroup(child.pid));
34505
34809
  const completed = Promise.all([
34506
34810
  exited,
34507
34811
  new Response(child.stdout).text(),
@@ -34510,7 +34814,7 @@ async function userConfigChain(timeoutMs = JJ_CONFIG_PATH_TIMEOUT_MS, env = proc
34510
34814
  const stdout = await new Promise((resolve) => {
34511
34815
  const stop = () => {
34512
34816
  clearTimeout(timer);
34513
- killGroup();
34817
+ killGroup(child.pid);
34514
34818
  resolve(undefined);
34515
34819
  };
34516
34820
  const timer = setTimeout(stop, timeoutMs);
@@ -34594,18 +34898,18 @@ function claudeProjectDirectory(environment, fallback) {
34594
34898
 
34595
34899
  // src/codex/codex-session-record.ts
34596
34900
  import { spawnSync } from "child_process";
34597
- import { readFileSync as readFileSync6, readlinkSync as readlinkSync2, unwatchFile, watchFile } from "fs";
34598
- import { mkdir as mkdir4, readFile as readFile5, rename as rename5, utimes as utimes3, writeFile as writeFile3 } from "fs/promises";
34901
+ import { readFileSync as readFileSync5, readlinkSync, unwatchFile, watchFile } from "fs";
34902
+ import { mkdir as mkdir4, readFile as readFile7, rename as rename5, utimes as utimes3, writeFile as writeFile3 } from "fs/promises";
34599
34903
  import { homedir as homedir3 } from "os";
34600
34904
  import { basename as basename4, dirname as dirname5, join as join10 } from "path";
34601
34905
 
34602
34906
  // src/session-identity.ts
34603
- import { readFile as readFile4 } from "fs/promises";
34907
+ import { readFile as readFile6 } from "fs/promises";
34604
34908
  import { basename as basename3, join as join9 } from "path";
34605
34909
 
34606
34910
  // src/session-state.ts
34607
- import { readFileSync as readFileSync5 } from "fs";
34608
- import { mkdir as mkdir3, readdir as readdir3, rename as rename4, rm as rm3, stat as stat3, utimes as utimes2, writeFile as writeFile2 } from "fs/promises";
34911
+ import { readFileSync as readFileSync4 } from "fs";
34912
+ import { mkdir as mkdir3, readdir as readdir3, rename as rename4, rm as rm4, stat as stat4, utimes as utimes2, writeFile as writeFile2 } from "fs/promises";
34609
34913
  import { dirname as dirname4, join as join8 } from "path";
34610
34914
  async function writeAtomicStateFile(file, contents) {
34611
34915
  await mkdir3(dirname4(file), { recursive: true, mode: 448 });
@@ -34627,12 +34931,12 @@ async function pruneStateDirectory(directory, isStale) {
34627
34931
  const file = join8(directory, entry);
34628
34932
  if (!await isStale(file))
34629
34933
  continue;
34630
- await rm3(file, { recursive: true, force: true });
34934
+ await rm4(file, { recursive: true, force: true });
34631
34935
  }
34632
34936
  }
34633
34937
  var STATE_FILE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
34634
34938
  async function writtenLongAgo(file) {
34635
- const modified = await stat3(file).then((stats) => stats.mtimeMs, () => {
34939
+ const modified = await stat4(file).then((stats) => stats.mtimeMs, () => {
34636
34940
  return;
34637
34941
  });
34638
34942
  return modified !== undefined && Date.now() - modified > STATE_FILE_MAX_AGE_MS;
@@ -34646,11 +34950,11 @@ async function writeChosenTitle(file, title) {
34646
34950
  `);
34647
34951
  }
34648
34952
  async function removeChosenTitle(file) {
34649
- await rm3(file, { force: true });
34953
+ await rm4(file, { force: true });
34650
34954
  }
34651
34955
  function readChosenTitleSync(file) {
34652
34956
  try {
34653
- return readFileSync5(file, "utf8");
34957
+ return readFileSync4(file, "utf8");
34654
34958
  } catch {
34655
34959
  return;
34656
34960
  }
@@ -34711,7 +35015,7 @@ class UnparseableRoleRecordError extends Error {
34711
35015
  async function readPersistedRole(roleFile) {
34712
35016
  let bytes;
34713
35017
  try {
34714
- bytes = await readFile4(roleFile, "utf8");
35018
+ bytes = await readFile6(roleFile, "utf8");
34715
35019
  } catch (error) {
34716
35020
  if (hasErrnoCode(error, "ENOENT"))
34717
35021
  return;
@@ -34733,7 +35037,7 @@ async function writeSessionHandoff(file, sessionId) {
34733
35037
  }
34734
35038
  async function readSessionHandoff(file) {
34735
35039
  try {
34736
- const id = (await readFile4(file, "utf8")).trim();
35040
+ const id = (await readFile6(file, "utf8")).trim();
34737
35041
  return id.length === 0 ? undefined : id;
34738
35042
  } catch (error) {
34739
35043
  if (hasErrnoCode(error, "ENOENT"))
@@ -34797,7 +35101,7 @@ function watchRecord(file, pid, ended, changed, intervalMs) {
34797
35101
  }
34798
35102
  async function sessionEnded(file) {
34799
35103
  try {
34800
- await readFile5(file);
35104
+ await readFile7(file);
34801
35105
  return true;
34802
35106
  } catch {
34803
35107
  return false;
@@ -34811,7 +35115,7 @@ async function writeCodexSessionRecord(file, value) {
34811
35115
  }
34812
35116
  async function readCodexSessionRecord(file) {
34813
35117
  try {
34814
- const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile5(file, "utf8")));
35118
+ const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile7(file, "utf8")));
34815
35119
  return parsed.success ? parsed.data : undefined;
34816
35120
  } catch {
34817
35121
  return;
@@ -34843,14 +35147,14 @@ function codexProcessId(readComm = procComm, readParent = procParent) {
34843
35147
  }
34844
35148
  function procComm(pid) {
34845
35149
  try {
34846
- return readFileSync6(`/proc/${pid}/comm`, "utf8").trim();
35150
+ return readFileSync5(`/proc/${pid}/comm`, "utf8").trim();
34847
35151
  } catch {
34848
35152
  return;
34849
35153
  }
34850
35154
  }
34851
35155
  function procParent(pid) {
34852
35156
  try {
34853
- const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
35157
+ const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
34854
35158
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
34855
35159
  return Number.isInteger(parent) ? parent : undefined;
34856
35160
  } catch {
@@ -34864,7 +35168,7 @@ var PS_OPTIONS = {
34864
35168
  };
34865
35169
  function procStarted(pid) {
34866
35170
  try {
34867
- const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
35171
+ const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
34868
35172
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
34869
35173
  } catch {
34870
35174
  return;
@@ -34885,7 +35189,7 @@ function recordOfProcess(record, pid) {
34885
35189
  function sharedAppServer(pid) {
34886
35190
  let argv;
34887
35191
  try {
34888
- argv = readFileSync6(`/proc/${pid}/cmdline`, "utf8").split("\x00");
35192
+ argv = readFileSync5(`/proc/${pid}/cmdline`, "utf8").split("\x00");
34889
35193
  } catch {
34890
35194
  const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS);
34891
35195
  if (ps.status !== 0)
@@ -34942,7 +35246,7 @@ async function pruneCodexSessionRecords(stateDirectory) {
34942
35246
  }
34943
35247
  function codexExecutable(pid) {
34944
35248
  try {
34945
- return readlinkSync2(`/proc/${pid}/exe`);
35249
+ return readlinkSync(`/proc/${pid}/exe`);
34946
35250
  } catch {
34947
35251
  return;
34948
35252
  }
@@ -35038,7 +35342,7 @@ function singleQuoted(value) {
35038
35342
  }
35039
35343
  function envFileText(envFile) {
35040
35344
  try {
35041
- return readFileSync7(envFile, "utf8");
35345
+ return readFileSync6(envFile, "utf8");
35042
35346
  } catch (error) {
35043
35347
  if (!hasErrnoCode(error, "ENOENT"))
35044
35348
  throw error;
@@ -35115,7 +35419,7 @@ async function openAsks(raw) {
35115
35419
  `);
35116
35420
  }
35117
35421
  const directory = claudeProjectDirectory({ CLAUDE_PROJECT_DIR: process.env["CLAUDE_PROJECT_DIR"] }, input.cwd ?? process.cwd());
35118
- const { dispatch, warnings, missing } = sessionDispatchSettings(chosen, process.env, {
35422
+ const { dispatch, warnings, missing } = await sessionDispatchSettings(chosen, process.env, {
35119
35423
  cwd: directory,
35120
35424
  session: input.session_id
35121
35425
  });
@@ -35142,12 +35446,13 @@ ${formatOpenAsksSummary(snapshot, linkBaseOf(dispatch.publicUrl ?? dispatch.url)
35142
35446
  `);
35143
35447
  }
35144
35448
  }
35145
- function dispatchFirst(raw) {
35449
+ async function dispatchFirst(raw) {
35146
35450
  const input = DispatchFirstInput.parse(raw);
35147
35451
  const directory = claudeProjectDirectory({ CLAUDE_PROJECT_DIR: process.env["CLAUDE_PROJECT_DIR"] }, input.cwd ?? process.cwd());
35148
35452
  const chosen = sessionConfigFile(HOST, process.env);
35149
- if (!sessionDispatchSettings(chosen, process.env, { cwd: directory }).dispatch.enabled)
35453
+ if (!(await sessionDispatchSettings(chosen, process.env, { cwd: directory })).dispatch.enabled) {
35150
35454
  return;
35455
+ }
35151
35456
  const pluginRoot = configuredValue(process.env["CLAUDE_PLUGIN_ROOT"]);
35152
35457
  if (pluginRoot === undefined) {
35153
35458
  throw new Error("CLAUDE_PLUGIN_ROOT is unset; Claude Code sets it for every plugin hook");
@@ -35163,8 +35468,8 @@ function refreshLockHeld(lock) {
35163
35468
  let age;
35164
35469
  let text;
35165
35470
  try {
35166
- age = Date.now() - statSync2(lock).mtimeMs;
35167
- text = readFileSync7(lock, "utf8");
35471
+ age = Date.now() - statSync(lock).mtimeMs;
35472
+ text = readFileSync6(lock, "utf8");
35168
35473
  } catch (error) {
35169
35474
  if (hasErrnoCode(error, "ENOENT"))
35170
35475
  return false;
@@ -35193,14 +35498,14 @@ function takeRefreshLock(lock) {
35193
35498
  }
35194
35499
  if (refreshLockHeld(lock))
35195
35500
  return false;
35196
- rmSync3(lock, { force: true });
35501
+ rmSync2(lock, { force: true });
35197
35502
  }
35198
35503
  return false;
35199
35504
  }
35200
35505
  function refreshOutcome(file, since) {
35201
35506
  let value;
35202
35507
  try {
35203
- value = JSON.parse(readFileSync7(file, "utf8"));
35508
+ value = JSON.parse(readFileSync6(file, "utf8"));
35204
35509
  } catch {
35205
35510
  return;
35206
35511
  }
@@ -35243,14 +35548,14 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
35243
35548
  }
35244
35549
  async function answersMessage(session, cwd, startedAt, by) {
35245
35550
  const file = sessionConfigFile(HOST, process.env);
35246
- let { dispatch } = sessionDispatchSettings(file, process.env, {
35551
+ let { dispatch } = await sessionDispatchSettings(file, process.env, {
35247
35552
  cwd,
35248
35553
  commands: "kept",
35249
35554
  session
35250
35555
  });
35251
35556
  let dispatchUrl;
35252
35557
  if (!dispatch.enabled && dispatch.error !== null) {
35253
- dispatchUrl = sessionDispatchUrl(file, process.env, { cwd });
35558
+ dispatchUrl = await sessionDispatchUrl(file, process.env, { cwd });
35254
35559
  if (dispatchUrl !== undefined) {
35255
35560
  const refreshed = await refreshedAnswers(session, cwd, dispatchUrl, startedAt, by);
35256
35561
  if ("text" in refreshed)
@@ -35305,8 +35610,8 @@ async function answersRefresh(session, cwd) {
35305
35610
  if (takeRefreshLock(lock)) {
35306
35611
  try {
35307
35612
  const file = sessionConfigFile(HOST, process.env);
35308
- const dispatchUrl = sessionDispatchUrl(file, process.env, { cwd }) ?? null;
35309
- const { dispatch } = sessionDispatchSettings(file, process.env, { cwd, session });
35613
+ const dispatchUrl = await sessionDispatchUrl(file, process.env, { cwd }) ?? null;
35614
+ const { dispatch } = await sessionDispatchSettings(file, process.env, { cwd, session });
35310
35615
  const read = await readSessionAnswers({
35311
35616
  session,
35312
35617
  dispatch,
@@ -35321,7 +35626,7 @@ async function answersRefresh(session, cwd) {
35321
35626
  };
35322
35627
  writeAtomically(join11(directory, REFRESH_OUTCOME), JSON.stringify(outcome));
35323
35628
  } finally {
35324
- rmSync3(lock, { force: true });
35629
+ rmSync2(lock, { force: true });
35325
35630
  }
35326
35631
  }
35327
35632
  process.exit(0);
@@ -35353,4 +35658,4 @@ if (mode === "open-asks") {
35353
35658
  await openAsks(input);
35354
35659
  await endOnceWritten([process.stdout, process.stderr], holdsDeviceLoginLock, (code) => process.exit(code));
35355
35660
  } else
35356
- dispatchFirst(input);
35661
+ await dispatchFirst(input);