@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/codex-hook.ts
983
- import { rm as rm4 } from "fs/promises";
983
+ import { rm as rm5 } from "fs/promises";
984
984
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/core/core.js
985
985
  var NEVER = Object.freeze({
986
986
  status: "aborted"
@@ -20161,6 +20161,10 @@ var FORM_SESSION = "session";
20161
20161
  var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
20162
20162
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
20163
20163
  var FORM_PROJECTS = "projects";
20164
+ var FORM_SCOPE = "scope";
20165
+ var SCOPE_READ = "read";
20166
+ var FORM_AS_OF = "as_of";
20167
+ var HEADER_DPOP_HOLDER = "DPoP-Holder";
20164
20168
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
20165
20169
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
20166
20170
  var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
@@ -20273,6 +20277,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
20273
20277
  "The machine login the subject token belongs to has ended\\.",
20274
20278
  "The machine login has ended\\.",
20275
20279
  "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)\\.",
20280
+ "A live read token is bound to the key this proof was signed with\\. Make a new key\\.",
20276
20281
  `${PERSON_SLOT} is a restricted member, whose token names its projects: set AGENT_SECRETS_PROJECTS to the projects this session works on\\.`,
20277
20282
  `The token names a project its person cannot see: ${PROJECT_SLOT}\\.`,
20278
20283
  `The subject token was refused: its entry names the project ${PROJECT_SLOT}, which its person ${PERSON_SLOT} cannot see\\.`,
@@ -20285,6 +20290,19 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
20285
20290
  `The session name '${SESSION_SLOT}' belongs to another daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
20286
20291
  `The session name '${SESSION_SLOT}' is bound to no daemon: a pod trades only under a session name the daemon that registered it holds\\.`,
20287
20292
  `${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`,
20293
+ "The 'as_of' parameter names a cut, and only a trade that asks for the scope read may name one\\.",
20294
+ "The 'as_of' parameter is not an RFC 3339 time with at most six fractional digits\\.",
20295
+ "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
20296
+ "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
20297
+ "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
20298
+ `${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\\.`,
20299
+ `${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\\.`,
20300
+ "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\\.",
20301
+ "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\\.",
20302
+ "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\\.",
20303
+ "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\\.",
20304
+ "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\\.",
20305
+ "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\\.",
20288
20306
  ...POLICY_REFUSAL_PATTERNS
20289
20307
  ].map((source) => new RegExp(`^${source}$`));
20290
20308
  var LIBRARY_DESCRIPTIONS = [
@@ -20602,17 +20620,16 @@ function isFinalRefusal(error) {
20602
20620
 
20603
20621
  // ../envoy-client/src/envoy-config.ts
20604
20622
  import {
20605
- chmodSync,
20606
- closeSync,
20607
- existsSync,
20608
- lstatSync,
20609
- mkdtempSync,
20610
- openSync,
20611
- readFileSync as readFileSync2,
20612
- readlinkSync,
20613
- rmSync,
20614
- statSync
20615
- } from "fs";
20623
+ access,
20624
+ chmod,
20625
+ lstat,
20626
+ mkdtemp,
20627
+ open,
20628
+ readFile as readFile3,
20629
+ readlink,
20630
+ rm,
20631
+ stat
20632
+ } from "fs/promises";
20616
20633
  import { homedir, tmpdir } from "os";
20617
20634
  import * as path from "path";
20618
20635
 
@@ -20702,15 +20719,44 @@ function jsonErrorPosition(text) {
20702
20719
  }
20703
20720
  }
20704
20721
 
20722
+ // ../envoy-client/src/process-group.ts
20723
+ function killGroup(pid) {
20724
+ try {
20725
+ process.kill(-pid, "SIGKILL");
20726
+ } catch {}
20727
+ }
20728
+ 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<&-';
20729
+ function groupWatchedBy(argv) {
20730
+ return ["/bin/sh", "-c", WATCH, ...argv];
20731
+ }
20732
+ function spawnWatched(argv, options) {
20733
+ const child = Bun.spawn(groupWatchedBy(argv), {
20734
+ ...options,
20735
+ stdin: "pipe",
20736
+ detached: true
20737
+ });
20738
+ let closed = false;
20739
+ return {
20740
+ child,
20741
+ endGroup: () => {
20742
+ killGroup(child.pid);
20743
+ if (closed)
20744
+ return;
20745
+ closed = true;
20746
+ child.stdin.end();
20747
+ }
20748
+ };
20749
+ }
20750
+
20705
20751
  // ../envoy-client/src/secret-file.ts
20706
- import { readFileSync } from "fs";
20752
+ import { readFile as readFile2 } from "fs/promises";
20707
20753
  function sendable(value) {
20708
20754
  return !/[\s\p{Cc}]/u.test(value);
20709
20755
  }
20710
- function readSecretFile(variable, filePath) {
20756
+ async function readSecretFile(variable, filePath) {
20711
20757
  let contents;
20712
20758
  try {
20713
- contents = readFileSync(filePath, "utf8");
20759
+ contents = await readFile2(filePath, "utf8");
20714
20760
  } catch (error) {
20715
20761
  throw new Error(`${variable} names a file that could not be read (${readErrorCode(error)})`);
20716
20762
  }
@@ -20845,20 +20891,28 @@ function describeSchemaIssue(filePath, error) {
20845
20891
  }
20846
20892
  return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
20847
20893
  }
20848
- function danglingLink(filePath) {
20894
+ async function danglingLink(filePath) {
20849
20895
  try {
20850
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
20896
+ return (await lstat(filePath)).isSymbolicLink() ? await readlink(filePath) : null;
20851
20897
  } catch {
20852
20898
  return null;
20853
20899
  }
20854
20900
  }
20855
- function parseFile(filePath, schema, checkout) {
20901
+ async function exists(file) {
20902
+ try {
20903
+ await access(file);
20904
+ return true;
20905
+ } catch {
20906
+ return false;
20907
+ }
20908
+ }
20909
+ async function parseFile(filePath, schema, checkout) {
20856
20910
  let raw;
20857
20911
  try {
20858
- raw = readFileSync2(filePath, "utf-8");
20912
+ raw = await readFile3(filePath, "utf-8");
20859
20913
  } catch (error) {
20860
20914
  if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
20861
- return { kind: "absent", link: danglingLink(filePath) };
20915
+ return { kind: "absent", link: checkout ? null : await danglingLink(filePath) };
20862
20916
  }
20863
20917
  return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
20864
20918
  }
@@ -20886,53 +20940,77 @@ function parseFile(filePath, schema, checkout) {
20886
20940
  }
20887
20941
  var FAILURE_KEPT_MS = 60000;
20888
20942
  var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
20943
+ var COMMAND_RUNS = Symbol.for("legion.envoy-config.command-runs.v1");
20889
20944
  var processGlobal = globalThis;
20890
20945
  var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
20891
20946
  processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
20892
- function runCommand(command, env, cwd) {
20947
+ var commandRuns = processGlobal[COMMAND_RUNS] ?? new Map;
20948
+ processGlobal[COMMAND_RUNS] = commandRuns;
20949
+ async function unnamedFile() {
20950
+ const directory = await mkdtemp(path.join(tmpdir(), "envoy-command-"));
20951
+ try {
20952
+ await chmod(directory, 448);
20953
+ return await open(path.join(directory, "stdout"), "wx+", 384);
20954
+ } finally {
20955
+ await rm(directory, { recursive: true, force: true });
20956
+ }
20957
+ }
20958
+ async function readOutput(file) {
20959
+ const output = Buffer.alloc((await file.stat()).size);
20960
+ let read = 0;
20961
+ while (read < output.length) {
20962
+ const { bytesRead } = await file.read(output, read, output.length - read, read);
20963
+ if (bytesRead === 0)
20964
+ break;
20965
+ read += bytesRead;
20966
+ }
20967
+ return output.toString("utf-8", 0, read);
20968
+ }
20969
+ async function runCommand(command, env, cwd) {
20893
20970
  const timeoutMs = commandTimeoutMs(env);
20894
20971
  const childEnv = {};
20895
20972
  for (const [name, variable] of Object.entries(env)) {
20896
20973
  if (variable !== undefined)
20897
20974
  childEnv[name] = variable;
20898
20975
  }
20899
- const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
20976
+ const file = await unnamedFile();
20900
20977
  try {
20901
- chmodSync(directory, 448);
20902
- const output = path.join(directory, "stdout");
20903
- const fd = openSync(output, "wx", 384);
20904
- let result;
20978
+ let watched;
20905
20979
  try {
20906
- result = Bun.spawnSync(["/bin/sh", "-c", command], {
20980
+ watched = spawnWatched(["/bin/sh", "-c", command], {
20907
20981
  cwd,
20908
20982
  env: childEnv,
20909
- stdin: "ignore",
20910
- stdout: fd,
20911
- stderr: "ignore",
20912
- timeout: timeoutMs,
20913
- detached: true
20983
+ stdout: file.fd,
20984
+ stderr: "ignore"
20914
20985
  });
20915
20986
  } catch (error) {
20916
20987
  return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
20917
- } finally {
20918
- closeSync(fd);
20919
20988
  }
20989
+ const { child, endGroup } = watched;
20990
+ let timedOut = false;
20991
+ const timer = setTimeout(() => {
20992
+ timedOut = true;
20993
+ endGroup();
20994
+ }, timeoutMs);
20920
20995
  try {
20921
- process.kill(-result.pid, "SIGKILL");
20922
- } catch {}
20923
- if (result.exitedDueToTimeout) {
20996
+ await child.exited;
20997
+ } finally {
20998
+ clearTimeout(timer);
20999
+ }
21000
+ endGroup();
21001
+ if (timedOut) {
20924
21002
  return {
20925
21003
  failure: `did not finish within ${timeoutMs / 1000} s, and does not run again in this process`,
20926
21004
  timedOut: true
20927
21005
  };
20928
21006
  }
20929
- if (!result.success) {
21007
+ if (child.exitCode !== 0) {
20930
21008
  return {
20931
- failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
21009
+ failure: `exited with ${child.signalCode ?? `status ${child.exitCode}`}`,
20932
21010
  timedOut: false
20933
21011
  };
20934
21012
  }
20935
- const value = readFileSync2(output, "utf-8").trim();
21013
+ const value = (await readOutput(file)).trim();
20936
21014
  if (value.length === 0)
20937
21015
  return { failure: "printed nothing", timedOut: false };
20938
21016
  if (!sendable(value)) {
@@ -20943,10 +21021,10 @@ function runCommand(command, env, cwd) {
20943
21021
  }
20944
21022
  return { value };
20945
21023
  } finally {
20946
- rmSync(directory, { recursive: true, force: true });
21024
+ await file.close();
20947
21025
  }
20948
21026
  }
20949
- function fileValue(value, field, filePath, env, commands = "run") {
21027
+ async function fileValue(value, field, filePath, env, commands = "run") {
20950
21028
  if (!value.startsWith("!")) {
20951
21029
  if (!sendable(value)) {
20952
21030
  throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
@@ -20962,42 +21040,50 @@ function fileValue(value, field, filePath, env, commands = "run") {
20962
21040
  throw new Error(`${filePath}: ${field}'s command has not run in this process yet, and this read does not run it`);
20963
21041
  }
20964
21042
  } else if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
20965
- outcome = { ...runCommand(command, env, cwd), at: Date.now() };
20966
- commandOutcomes.set(key, outcome);
21043
+ let run = commandRuns.get(key);
21044
+ if (run === undefined) {
21045
+ run = runCommand(command, env, cwd).then((ran) => {
21046
+ const kept = { ...ran, at: Date.now() };
21047
+ commandOutcomes.set(key, kept);
21048
+ return kept;
21049
+ }).finally(() => commandRuns.delete(key));
21050
+ commandRuns.set(key, run);
21051
+ }
21052
+ outcome = await run;
20967
21053
  }
20968
21054
  if ("failure" in outcome)
20969
21055
  throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
20970
21056
  return outcome.value;
20971
21057
  }
20972
- function statDevice(directory) {
21058
+ async function statDevice(directory) {
20973
21059
  try {
20974
- return statSync(directory).dev;
21060
+ return (await stat(directory)).dev;
20975
21061
  } catch {
20976
21062
  return;
20977
21063
  }
20978
21064
  }
20979
- function moveNotice(oldFile, newFile, move, deviceOf) {
20980
- const oldDevice = deviceOf(path.dirname(oldFile));
21065
+ async function moveNotice(oldFile, newFile, move, deviceOf) {
21066
+ const oldDevice = await deviceOf(path.dirname(oldFile));
20981
21067
  let ancestor = path.dirname(newFile);
20982
- let newDevice = deviceOf(ancestor);
21068
+ let newDevice = await deviceOf(ancestor);
20983
21069
  while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
20984
21070
  ancestor = path.dirname(ancestor);
20985
- newDevice = deviceOf(ancestor);
21071
+ newDevice = await deviceOf(ancestor);
20986
21072
  }
20987
21073
  if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
20988
21074
  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`;
20989
21075
  }
20990
21076
  return `${oldFile} is not read: ${move}`;
20991
21077
  }
20992
- function oldUserFileNotice(filePath, env, deviceOf) {
21078
+ async function oldUserFileNotice(filePath, env, deviceOf) {
20993
21079
  const home = nonEmpty(env.HOME) ?? homedir();
20994
21080
  const old = path.join(home, ".config", "opencode", "envoy.json");
20995
- if (!existsSync(old))
21081
+ if (!await exists(old))
20996
21082
  return;
20997
21083
  const selected = path.resolve(filePath);
20998
21084
  const userFile = path.resolve(home, ".config", "legion", "envoy.json");
20999
21085
  if (selected === userFile) {
21000
- return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
21086
+ return await moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
21001
21087
  }
21002
21088
  const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
21003
21089
  if (profileFile) {
@@ -21015,14 +21101,18 @@ function missingConfigNotice(filePath, missing, off) {
21015
21101
  const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
21016
21102
  return `no envoy.json at ${filePath}${link}: ${off}${old}`;
21017
21103
  }
21018
- function readEnvoyConfig(filePath, env, options) {
21104
+ async function readEnvoyConfig(filePath, env, options) {
21019
21105
  const deviceOf = options.deviceOf ?? statDevice;
21020
- const chosen = parseFile(filePath, EnvoyFileSchema, false);
21021
- if (chosen.kind === "invalid")
21022
- return { kind: "failed", path: filePath, error: chosen.reason };
21023
21106
  const resolvedChosen = path.resolve(filePath);
21024
21107
  const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
21025
- const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
21108
+ const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
21109
+ const [chosen, checkoutFile, oldCheckoutThere] = await Promise.all([
21110
+ parseFile(filePath, EnvoyFileSchema, false),
21111
+ checkoutPath === resolvedChosen ? Promise.resolve({ kind: "absent", link: null }) : parseFile(checkoutPath, CheckoutFileSchema, true),
21112
+ oldCheckout === resolvedChosen ? Promise.resolve(false) : exists(oldCheckout)
21113
+ ]);
21114
+ if (chosen.kind === "invalid")
21115
+ return { kind: "failed", path: filePath, error: chosen.reason };
21026
21116
  const own = chosen.kind === "valid" ? chosen.settings : {};
21027
21117
  let checkout = null;
21028
21118
  if (checkoutFile.kind === "invalid") {
@@ -21036,11 +21126,11 @@ function readEnvoyConfig(filePath, env, options) {
21036
21126
  askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
21037
21127
  };
21038
21128
  }
21039
- const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
21040
- const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
21041
- moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
21129
+ const checkoutMissing = checkoutPath === resolvedChosen ? chosen.kind === "absent" : checkoutFile.kind === "absent" || checkoutFile.kind === "invalid" && !await exists(checkoutPath);
21130
+ const warnings = oldCheckout !== resolvedChosen && checkoutMissing && oldCheckoutThere ? [
21131
+ await moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
21042
21132
  ] : [];
21043
- const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
21133
+ const unreadOldUserFile = chosen.kind === "absent" ? await oldUserFileNotice(filePath, env, deviceOf) : undefined;
21044
21134
  return {
21045
21135
  kind: "read",
21046
21136
  path: filePath,
@@ -21068,10 +21158,10 @@ function bearerCredential(token) {
21068
21158
  secret: () => token
21069
21159
  };
21070
21160
  }
21071
- function bearerSource(env, section, written) {
21161
+ async function bearerSource(env, section, written) {
21072
21162
  const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
21073
21163
  if (pointer !== undefined) {
21074
- return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
21164
+ return { kind: "variable", token: await readSecretFile(`${section}_TOKEN_FILE`, pointer) };
21075
21165
  }
21076
21166
  const plain = nonEmpty(env[`${section}_TOKEN`]);
21077
21167
  if (plain !== undefined) {
@@ -21083,7 +21173,7 @@ function bearerSource(env, section, written) {
21083
21173
  const bearer = written();
21084
21174
  return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
21085
21175
  }
21086
- function fileBearer(bearer, url, section, env, commands = "run") {
21176
+ async function fileBearer(bearer, url, section, env, commands = "run") {
21087
21177
  const named = httpUrl2(url)?.origin;
21088
21178
  const paired = httpUrl2(bearer.server)?.origin;
21089
21179
  if (named !== paired) {
@@ -28850,12 +28940,12 @@ async function reviewCommand(context) {
28850
28940
  }
28851
28941
 
28852
28942
  // ../envoy-client/src/session-answers.ts
28853
- import { mkdirSync, readFileSync as readFileSync3 } from "fs";
28943
+ import { mkdirSync, readFileSync } from "fs";
28854
28944
  import { join as join4 } from "path";
28855
28945
 
28856
28946
  // ../envoy-client/src/dispatch-session-directory.ts
28857
28947
  import { randomUUID } from "crypto";
28858
- import { renameSync, rmSync as rmSync2, writeFileSync } from "fs";
28948
+ import { renameSync, rmSync, writeFileSync } from "fs";
28859
28949
  import { homedir as homedir2 } from "os";
28860
28950
  import { join as join3 } from "path";
28861
28951
  var SESSION_ID_PATH_SEGMENT = /^[A-Za-z0-9._-]{1,128}$/;
@@ -28878,7 +28968,7 @@ function writeAtomically(path, text) {
28878
28968
  writeFileSync(temporary, text, { mode: PRIVATE_FILE });
28879
28969
  renameSync(temporary, path);
28880
28970
  } catch (error) {
28881
- rmSync2(temporary, { force: true });
28971
+ rmSync(temporary, { force: true });
28882
28972
  throw error;
28883
28973
  }
28884
28974
  }
@@ -29021,7 +29111,7 @@ processGlobal2[STATE_KEY] = state;
29021
29111
  var CACHE_FILE = "answers.json";
29022
29112
  function readCacheFile(directory, url) {
29023
29113
  try {
29024
- const value = JSON.parse(readFileSync3(join4(directory, CACHE_FILE), "utf-8"));
29114
+ const value = JSON.parse(readFileSync(join4(directory, CACHE_FILE), "utf-8"));
29025
29115
  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)) {
29026
29116
  return {
29027
29117
  dispatch_url: value.dispatch_url,
@@ -29222,13 +29312,29 @@ async function whoamiCommand(context) {
29222
29312
  const service = identity.kind === "agent" ? identity.service ?? null : null;
29223
29313
  const proved = identity.kind === "agent" ? identity.session ?? null : null;
29224
29314
  const project = identity.kind === "agent" ? identity.project ?? null : null;
29315
+ const readOnly = identity.scopes?.includes("read") === true;
29316
+ const cut = identity.kind === "agent" ? identity.cut ?? null : null;
29225
29317
  const session = proved ?? sessionId;
29226
29318
  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.";
29227
29319
  const answered = identity.kind === "agent" ? identity.sign_in_required : undefined;
29228
29320
  const signInNeeded = answered ?? (owner === null && service !== null && proved !== null);
29229
- 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}`;
29230
- 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}.` : "";
29231
- const writable = project !== null ? ` It may write project ${project} and no other.` : "";
29321
+ const who = owner !== null ? `acts for ${owner}` : service !== null ? `runs as service ${serviceSubjectLabel(service)}` : "runs";
29322
+ const named = proved !== null && proved !== sessionId ? ` Your credential names session ${proved}, which is not this host session (${sessionId})` : "";
29323
+ let acting;
29324
+ let elsewhere = named === "" ? "" : `${named}: Dispatch records every write you make as ${proved}.`;
29325
+ if (readOnly) {
29326
+ 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.`}`;
29327
+ elsewhere = named === "" ? "" : `${named}.`;
29328
+ } else if (owner !== null) {
29329
+ acting = `Session ${session} ${who}: issues you create without an assignee are assigned to ${owner}.`;
29330
+ } else if (signInNeeded) {
29331
+ 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.`;
29332
+ } else if (service !== null) {
29333
+ acting = `Session ${session} ${who}: ${unowned}`;
29334
+ } else {
29335
+ acting = `Session ${session} runs under the shared token: ${unowned}`;
29336
+ }
29337
+ const writable = project !== null && !readOnly ? ` It may write project ${project} and no other.` : "";
29232
29338
  return {
29233
29339
  text: acting + elsewhere + writable,
29234
29340
  details: { session, owner, service, project }
@@ -31481,64 +31587,8 @@ async function genericGrantRequest(config, grantType, parameters, options) {
31481
31587
  return result;
31482
31588
  }
31483
31589
 
31484
- // ../cipher-client/src/device-login-file.ts
31485
- import { createPrivateKey, randomUUID as randomUUID3 } from "crypto";
31486
- import { constants as constants2 } from "fs";
31487
- import {
31488
- access,
31489
- lstat as lstat2,
31490
- mkdir,
31491
- open as open2,
31492
- readFile as readFile2,
31493
- readlink,
31494
- rename as rename2,
31495
- rm as rm2,
31496
- stat as stat2
31497
- } from "fs/promises";
31498
- import { userInfo } from "os";
31499
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join6 } from "path";
31500
-
31501
- // ../cipher-client/src/device-login-lock.ts
31502
- import { randomUUID as randomUUID2 } from "crypto";
31503
- import { closeSync as closeSync2, constants, fstatSync, openSync as openSync2, readSync } from "fs";
31504
- import {
31505
- link,
31506
- lstat,
31507
- open,
31508
- readdir as readdir2,
31509
- rename,
31510
- rm,
31511
- stat,
31512
- utimes
31513
- } from "fs/promises";
31514
- import { basename as basename2, dirname as dirname2, join as join5 } from "path";
31515
-
31516
- // ../cipher-client/src/token-client.ts
31517
- var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
31590
+ // ../cipher-client/src/broker-request.ts
31518
31591
  var BROKER_URL_SETTING = "the broker URL";
31519
- var RETRY_FIRST_WAIT_MS = 15000;
31520
- var RETRY_MAX_WAIT_MS = 5 * 60000;
31521
- var PENDING_FIRST_WAIT_MS = 2000;
31522
- var PENDING_MAX_WAIT_MS = 30000;
31523
- var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
31524
- var TRADE_ATTEMPT_MS = 30000;
31525
- function sleep2(ms, signal, holdsProcess = false) {
31526
- const { promise, resolve } = Promise.withResolvers();
31527
- if (signal?.aborted) {
31528
- resolve();
31529
- return promise;
31530
- }
31531
- const done = () => {
31532
- clearTimeout(timer);
31533
- signal?.removeEventListener("abort", done);
31534
- resolve();
31535
- };
31536
- const timer = setTimeout(done, ms);
31537
- if (!holdsProcess)
31538
- timer.unref();
31539
- signal?.addEventListener("abort", done, { once: true });
31540
- return promise;
31541
- }
31542
31592
  function statusOf(error) {
31543
31593
  let cause = error;
31544
31594
  for (let depth = 0;depth < 4; depth += 1) {
@@ -31575,7 +31625,11 @@ function requestInit(options, signal, headers) {
31575
31625
  async function sendWithProof(proved, url, options, signal) {
31576
31626
  const send = async () => {
31577
31627
  const headers = new Headers(options.headers);
31578
- headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
31628
+ const request = { method: options.method, url, nonce: proved.nonce.value };
31629
+ headers.set("DPoP", await proved.key.proof(request));
31630
+ if (proved.holderKey !== undefined) {
31631
+ headers.set(HEADER_DPOP_HOLDER, await proved.holderKey.proof(request));
31632
+ }
31579
31633
  return await proved.fetch(url, requestInit(options, signal, headers));
31580
31634
  };
31581
31635
  let answer = await send();
@@ -31591,14 +31645,82 @@ async function sendWithProof(proved, url, options, signal) {
31591
31645
  return answer;
31592
31646
  }
31593
31647
 
31648
+ // ../cipher-client/src/device-login-file.ts
31649
+ import { createPrivateKey, randomUUID as randomUUID3 } from "crypto";
31650
+ import { constants as constants2 } from "fs";
31651
+ import {
31652
+ access as access2,
31653
+ lstat as lstat3,
31654
+ mkdir,
31655
+ open as open3,
31656
+ readFile as readFile4,
31657
+ readlink as readlink2,
31658
+ rename as rename2,
31659
+ rm as rm3,
31660
+ stat as stat3
31661
+ } from "fs/promises";
31662
+ import { userInfo } from "os";
31663
+ import { dirname as dirname3, isAbsolute as isAbsolute2, join as join6 } from "path";
31664
+
31665
+ // ../cipher-client/src/device-login-lock.ts
31666
+ import { randomUUID as randomUUID2 } from "crypto";
31667
+ import { closeSync, constants, fstatSync, openSync, readSync } from "fs";
31668
+ import {
31669
+ link,
31670
+ lstat as lstat2,
31671
+ open as open2,
31672
+ readdir as readdir2,
31673
+ rename,
31674
+ rm as rm2,
31675
+ stat as stat2,
31676
+ utimes
31677
+ } from "fs/promises";
31678
+ import { basename as basename2, dirname as dirname2, join as join5 } from "path";
31679
+
31680
+ // ../cipher-client/src/token-client.ts
31681
+ var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
31682
+ function renewalAt(expiresAt, now, renewBeforeMs) {
31683
+ const left = expiresAt - now;
31684
+ if (left <= 0)
31685
+ return now;
31686
+ return Math.max(expiresAt - renewBeforeMs, now + left / 2);
31687
+ }
31688
+ var EXPIRES_IN_STEP_MS = 1000;
31689
+ var RETRY_FIRST_WAIT_MS = 15000;
31690
+ var RETRY_MAX_WAIT_MS = 5 * 60000;
31691
+ var PENDING_FIRST_WAIT_MS = 2000;
31692
+ var PENDING_MAX_WAIT_MS = 30000;
31693
+ var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
31694
+ var TRADE_ATTEMPT_MS = 30000;
31695
+ function sleep2(ms, signal, holdsProcess = false) {
31696
+ const { promise, resolve } = Promise.withResolvers();
31697
+ if (signal?.aborted) {
31698
+ resolve();
31699
+ return promise;
31700
+ }
31701
+ const done = () => {
31702
+ clearTimeout(timer);
31703
+ signal?.removeEventListener("abort", done);
31704
+ resolve();
31705
+ };
31706
+ const timer = setTimeout(done, ms);
31707
+ if (!holdsProcess)
31708
+ timer.unref();
31709
+ signal?.addEventListener("abort", done, { once: true });
31710
+ return promise;
31711
+ }
31712
+
31594
31713
  class BrokerTokenClient {
31595
31714
  #brokerUrl;
31596
31715
  #key;
31716
+ #holderKey;
31597
31717
  #subject;
31598
31718
  #actor;
31599
31719
  #session;
31600
31720
  #projects;
31601
31721
  #launcherCredential;
31722
+ #scope;
31723
+ #asOf;
31602
31724
  #renewBeforeMs;
31603
31725
  #now;
31604
31726
  #attemptMs;
@@ -31627,11 +31749,14 @@ class BrokerTokenClient {
31627
31749
  throw new Error("broker client: the broker URL is not an http or https URL");
31628
31750
  this.#brokerUrl = holdUrlUserinfo(brokerUrl);
31629
31751
  this.#key = options.key;
31752
+ this.#holderKey = options.holderKey;
31630
31753
  this.#subject = options.subject;
31631
31754
  this.#actor = options.actor;
31632
31755
  this.#session = options.session ?? "";
31633
31756
  this.#projects = [...options.projects ?? []];
31634
31757
  this.#launcherCredential = options.launcherCredential ?? true;
31758
+ this.#scope = options.scope ?? "";
31759
+ this.#asOf = options.asOf ?? "";
31635
31760
  this.#renewBeforeMs = options.renewBeforeMs ?? DEFAULT_RENEW_BEFORE_MS;
31636
31761
  this.#now = options.now ?? Date.now;
31637
31762
  this.#attemptMs = options.attemptMs ?? TRADE_ATTEMPT_MS;
@@ -31641,7 +31766,7 @@ class BrokerTokenClient {
31641
31766
  this.#random = options.random ?? Math.random;
31642
31767
  }
31643
31768
  get key() {
31644
- return this.#key;
31769
+ return this.#holderKey ?? this.#key;
31645
31770
  }
31646
31771
  describe() {
31647
31772
  return this.#subject.describe();
@@ -31650,10 +31775,11 @@ class BrokerTokenClient {
31650
31775
  const waitForReady = options.waitForReady === true;
31651
31776
  const now = this.#now();
31652
31777
  const held = this.#held;
31653
- if (held !== null && now < held.expiresAt.getTime() - this.#renewBeforeMs)
31654
- return held;
31655
- if (held !== null && now < held.expiresAt.getTime() && this.#last !== null)
31656
- return held;
31778
+ if (held !== null && now < held.renewsAt)
31779
+ return held.token;
31780
+ if (held !== null && now < held.token.expiresAt.getTime() && this.#last !== null) {
31781
+ return held.token;
31782
+ }
31657
31783
  const closed = this.#closed.signal;
31658
31784
  if (closed.aborted)
31659
31785
  throw closed.reason;
@@ -31687,8 +31813,8 @@ class BrokerTokenClient {
31687
31813
  const stop = () => {
31688
31814
  this.#waiters.delete(waiter);
31689
31815
  const held = this.#held;
31690
- if (held !== null && this.#now() < held.expiresAt.getTime())
31691
- resolve(held);
31816
+ if (held !== null && this.#now() < held.token.expiresAt.getTime())
31817
+ resolve(held.token);
31692
31818
  else
31693
31819
  reject(this.#stopped(signal?.reason));
31694
31820
  };
@@ -31728,7 +31854,7 @@ class BrokerTokenClient {
31728
31854
  });
31729
31855
  }
31730
31856
  drop(accessToken) {
31731
- if (accessToken !== undefined && this.#held?.accessToken !== accessToken)
31857
+ if (accessToken !== undefined && this.#held?.token.accessToken !== accessToken)
31732
31858
  return;
31733
31859
  this.#held = null;
31734
31860
  }
@@ -31759,7 +31885,10 @@ class BrokerTokenClient {
31759
31885
  if (this.#pendingSaid !== null && this.#since !== null) {
31760
31886
  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`);
31761
31887
  }
31762
- this.#held = token;
31888
+ this.#held = {
31889
+ token,
31890
+ renewsAt: renewalAt(token.expiresAt.getTime(), this.#now(), this.#renewBeforeMs)
31891
+ };
31763
31892
  this.#last = null;
31764
31893
  this.#since = null;
31765
31894
  this.#failed = 0;
@@ -31799,8 +31928,8 @@ class BrokerTokenClient {
31799
31928
  this.#since ??= now;
31800
31929
  this.#failed += 1;
31801
31930
  const held = this.#held;
31802
- if (held !== null && now < held.expiresAt.getTime()) {
31803
- this.#tell((waiter) => waiter.resolve(held));
31931
+ if (held !== null && now < held.token.expiresAt.getTime()) {
31932
+ this.#tell((waiter) => waiter.resolve(held.token));
31804
31933
  } else {
31805
31934
  this.#held = null;
31806
31935
  if (failure.kind !== "pending") {
@@ -31852,7 +31981,8 @@ class BrokerTokenClient {
31852
31981
  async#trade(signal) {
31853
31982
  const source = this.#subject;
31854
31983
  if (source.spend !== undefined) {
31855
- return await source.spend((subject) => this.#exchange(subject, signal), signal);
31984
+ const leastLifeMs = this.#scope === SCOPE_READ ? this.#renewBeforeMs + EXPIRES_IN_STEP_MS : undefined;
31985
+ return await source.spend((subject) => this.#exchange(subject, signal), signal, leastLifeMs);
31856
31986
  }
31857
31987
  return await this.#exchange(await source.read(signal), signal);
31858
31988
  }
@@ -31866,6 +31996,10 @@ class BrokerTokenClient {
31866
31996
  form[FORM_SESSION] = this.#session;
31867
31997
  if (this.#projects.length > 0)
31868
31998
  form[FORM_PROJECTS] = this.#projects.join(" ");
31999
+ if (this.#scope !== "")
32000
+ form[FORM_SCOPE] = this.#scope;
32001
+ if (this.#asOf !== "")
32002
+ form[FORM_AS_OF] = this.#asOf;
31869
32003
  if (!this.#launcherCredential) {
31870
32004
  form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
31871
32005
  }
@@ -31898,7 +32032,7 @@ class BrokerTokenClient {
31898
32032
  return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
31899
32033
  }
31900
32034
  async#send(url, options, signal, raw) {
31901
- const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
32035
+ const answer = await sendWithProof({ key: this.#key, holderKey: this.#holderKey, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
31902
32036
  raw.body = await answer.clone().json().catch(() => {
31903
32037
  return;
31904
32038
  });
@@ -31956,7 +32090,7 @@ var LOCK_RETRY_MS = 100;
31956
32090
  var STEAL_STALE_MS = 5000;
31957
32091
  async function statOrNone(path, what) {
31958
32092
  try {
31959
- return await lstat(path);
32093
+ return await lstat2(path);
31960
32094
  } catch (error) {
31961
32095
  if (readErrorCode(error) === "ENOENT")
31962
32096
  return null;
@@ -31966,7 +32100,7 @@ async function statOrNone(path, what) {
31966
32100
  async function createOwn(path, value, named) {
31967
32101
  let handle;
31968
32102
  try {
31969
- handle = await open(path, "wx", 384);
32103
+ handle = await open2(path, "wx", 384);
31970
32104
  } catch (error) {
31971
32105
  if (readErrorCode(error) === "EEXIST")
31972
32106
  return false;
@@ -31982,7 +32116,7 @@ async function createOwn(path, value, named) {
31982
32116
  async function look(path, what) {
31983
32117
  let handle;
31984
32118
  try {
31985
- handle = await open(path, LOCK_READ);
32119
+ handle = await open2(path, LOCK_READ);
31986
32120
  } catch (error) {
31987
32121
  if (readErrorCode(error) === "ENOENT")
31988
32122
  return null;
@@ -32019,7 +32153,7 @@ async function removeIfStill(path, isIt, what) {
32019
32153
  const same = took !== null && isIt(took);
32020
32154
  if (!same)
32021
32155
  await link(moved, path).catch(() => {});
32022
- await rm(moved, { force: true }).catch((error) => {
32156
+ await rm2(moved, { force: true }).catch((error) => {
32023
32157
  throw new Error(`remove ${what}, moved aside: ${readErrorCode(error)}`);
32024
32158
  });
32025
32159
  return same;
@@ -32106,7 +32240,7 @@ async function withLoginLock(path, named, work, options = {}) {
32106
32240
  function loginLockHeldBy(path, pid) {
32107
32241
  let fd;
32108
32242
  try {
32109
- fd = openSync2(`${path}.lock`, LOCK_READ);
32243
+ fd = openSync(`${path}.lock`, LOCK_READ);
32110
32244
  } catch {
32111
32245
  return false;
32112
32246
  }
@@ -32120,7 +32254,7 @@ function loginLockHeldBy(path, pid) {
32120
32254
  return false;
32121
32255
  } finally {
32122
32256
  try {
32123
- closeSync2(fd);
32257
+ closeSync(fd);
32124
32258
  } catch {}
32125
32259
  }
32126
32260
  }
@@ -32131,9 +32265,9 @@ async function removeUntouched(dir, left) {
32131
32265
  const names = await readdir2(dir).catch(() => []);
32132
32266
  for (const name of names.filter(left)) {
32133
32267
  const path = join5(dir, name);
32134
- const info = await stat(path).catch(() => null);
32268
+ const info = await stat2(path).catch(() => null);
32135
32269
  if (info !== null && Date.now() - info.mtimeMs > DEVICE_LOGIN_STALE_LOCK_MS) {
32136
- await rm(path, { force: true }).catch(() => {});
32270
+ await rm2(path, { force: true }).catch(() => {});
32137
32271
  }
32138
32272
  }
32139
32273
  }
@@ -32161,6 +32295,10 @@ function member(json, name) {
32161
32295
  const value = json[name];
32162
32296
  return typeof value === "string" ? value : "";
32163
32297
  }
32298
+ function wholeMember(json, name) {
32299
+ const value = json[name];
32300
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
32301
+ }
32164
32302
  function checkPrivate(info, what, forbidden, opens, notOwned) {
32165
32303
  const mode = info.mode & 511;
32166
32304
  if ((mode & forbidden) !== 0) {
@@ -32178,7 +32316,7 @@ var systemFiles = new Map;
32178
32316
  async function systemFile(file) {
32179
32317
  let info;
32180
32318
  try {
32181
- info = await stat2(file);
32319
+ info = await stat3(file);
32182
32320
  } catch {
32183
32321
  return null;
32184
32322
  }
@@ -32186,7 +32324,7 @@ async function systemFile(file) {
32186
32324
  const kept = systemFiles.get(file);
32187
32325
  if (kept?.status === status)
32188
32326
  return kept.text;
32189
- const text = await readFile2(file, "utf8").catch(() => null);
32327
+ const text = await readFile4(file, "utf8").catch(() => null);
32190
32328
  if (text === null)
32191
32329
  systemFiles.delete(file);
32192
32330
  else
@@ -32274,7 +32412,7 @@ async function checkLinkOnTheWay(info, what) {
32274
32412
  }
32275
32413
  async function lstatOnTheWay(path, what) {
32276
32414
  try {
32277
- return await lstat2(path);
32415
+ return await lstat3(path);
32278
32416
  } catch (error) {
32279
32417
  if (readErrorCode(error) === "ENOENT")
32280
32418
  return null;
@@ -32310,7 +32448,7 @@ async function walkTheWay(path, what, meet) {
32310
32448
  throw notARegularFile("a loop of links");
32311
32449
  let target;
32312
32450
  try {
32313
- target = await readlink(next);
32451
+ target = await readlink2(next);
32314
32452
  } catch (error) {
32315
32453
  const code = readErrorCode(error);
32316
32454
  if (code !== "EINVAL" && code !== "ENOENT") {
@@ -32359,7 +32497,7 @@ async function checkDirectoriesOnTheWay(dir, what) {
32359
32497
  async function checkLoginDirectory(dir, absent, what = `the directory of ${DEVICE_LOGIN_FILE_NAMED}`) {
32360
32498
  let info;
32361
32499
  try {
32362
- info = await stat2(dir);
32500
+ info = await stat3(dir);
32363
32501
  } catch (error) {
32364
32502
  if (absent !== undefined && readErrorCode(error) === "ENOENT")
32365
32503
  throw absent();
@@ -32396,14 +32534,14 @@ async function deviceLoginPlace(path) {
32396
32534
  await deviceLoginDirectory(path);
32397
32535
  const dir = dirname3(path);
32398
32536
  try {
32399
- await access(dir, constants2.W_OK | constants2.X_OK);
32537
+ await access2(dir, constants2.W_OK | constants2.X_OK);
32400
32538
  } catch (error) {
32401
32539
  const code = readErrorCode(error);
32402
32540
  throw new Error(`this user cannot enter and write to the directory of ${DEVICE_LOGIN_FILE_NAMED}: ${code}${code === "EACCES" ? "; run chmod 700 on it" : ""}`);
32403
32541
  }
32404
32542
  let info;
32405
32543
  try {
32406
- info = await stat2(path);
32544
+ info = await stat3(path);
32407
32545
  } catch (error) {
32408
32546
  if (readErrorCode(error) === "ENOENT")
32409
32547
  return;
@@ -32424,7 +32562,7 @@ async function checkLinkDirectories(path, absent) {
32424
32562
  }
32425
32563
  let info;
32426
32564
  try {
32427
- info = await lstat2(at);
32565
+ info = await lstat3(at);
32428
32566
  } catch (error) {
32429
32567
  if (readErrorCode(error) === "ENOENT")
32430
32568
  return;
@@ -32436,7 +32574,7 @@ async function checkLinkDirectories(path, absent) {
32436
32574
  throw notARegularFile("a loop of links");
32437
32575
  let target;
32438
32576
  try {
32439
- target = await readlink(at);
32577
+ target = await readlink2(at);
32440
32578
  } catch (error) {
32441
32579
  const code = readErrorCode(error);
32442
32580
  if (code === "EINVAL" || code === "ENOENT")
@@ -32453,7 +32591,7 @@ async function readDeviceLogin(path) {
32453
32591
  await checkLinkDirectories(path, absent);
32454
32592
  let handle;
32455
32593
  try {
32456
- handle = await open2(path, LOGIN_READ);
32594
+ handle = await open3(path, LOGIN_READ);
32457
32595
  } catch (error) {
32458
32596
  throw readErrorCode(error) === "ENOENT" ? absent() : refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
32459
32597
  }
@@ -32518,7 +32656,8 @@ async function readDeviceLogin(path) {
32518
32656
  expiresAt,
32519
32657
  broker,
32520
32658
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
32521
- accessExpiresAt: accessUsable ? accessExpiresAt : null
32659
+ accessExpiresAt: accessUsable ? accessExpiresAt : null,
32660
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
32522
32661
  };
32523
32662
  }
32524
32663
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -32551,7 +32690,8 @@ async function saveDeviceLogin(path, login, held, keep = false) {
32551
32690
  broker: login.broker,
32552
32691
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
32553
32692
  access_token: login.accessToken,
32554
- access_expires_at: login.accessExpiresAt.toISOString()
32693
+ access_expires_at: login.accessExpiresAt.toISOString(),
32694
+ ...login.accessLifeSeconds === null ? {} : { access_life_seconds: login.accessLifeSeconds }
32555
32695
  }
32556
32696
  });
32557
32697
  await deviceLoginPlace(path);
@@ -32562,7 +32702,7 @@ async function saveDeviceLogin(path, login, held, keep = false) {
32562
32702
  let whole = false;
32563
32703
  try {
32564
32704
  try {
32565
- const handle = await open2(temp, "wx", 384);
32705
+ const handle = await open3(temp, "wx", 384);
32566
32706
  try {
32567
32707
  await handle.writeFile(data);
32568
32708
  await handle.sync();
@@ -32581,10 +32721,10 @@ async function saveDeviceLogin(path, login, held, keep = false) {
32581
32721
  } catch (error) {
32582
32722
  throw keep && whole ? await keptCopy(temp, path, error) : error;
32583
32723
  } finally {
32584
- await rm2(temp, { force: true }).catch(() => {});
32724
+ await rm3(temp, { force: true }).catch(() => {});
32585
32725
  }
32586
32726
  try {
32587
- const handle = await open2(dir, "r");
32727
+ const handle = await open3(dir, "r");
32588
32728
  try {
32589
32729
  await handle.sync();
32590
32730
  } finally {
@@ -32673,6 +32813,11 @@ async function importDpopKey(pkcs8Pem, name) {
32673
32813
  // ../cipher-client/src/device-login.ts
32674
32814
  var BROKER_SETTING = "AGENT_SECRETS_URL";
32675
32815
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
32816
+ function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
32817
+ if (leastLifeMs === undefined || lifeSeconds === null)
32818
+ return ACCESS_MARGIN_MS;
32819
+ return Math.max(ACCESS_MARGIN_MS, Math.min(leastLifeMs, lifeSeconds * 1000 / 2));
32820
+ }
32676
32821
  var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
32677
32822
  var DEFAULT_POLL_SECONDS = 5;
32678
32823
  var LEAST_POLL_SECONDS = 1;
@@ -32748,7 +32893,8 @@ function loginOf(key, broker, answered, now) {
32748
32893
  expiresAt,
32749
32894
  broker,
32750
32895
  accessToken: holdSecret(answered.access_token, accessExpiresAt),
32751
- accessExpiresAt
32896
+ accessExpiresAt,
32897
+ accessLifeSeconds: seconds
32752
32898
  };
32753
32899
  }
32754
32900
  async function startDeviceLogin(options) {
@@ -32880,7 +33026,7 @@ class DeviceLoginIdentity {
32880
33026
  }
32881
33027
  return this.#key;
32882
33028
  }
32883
- async spend(trade, signal) {
33029
+ async spend(trade, signal, leastLifeMs) {
32884
33030
  const { thumbprint } = await this.#loaded();
32885
33031
  return await withDeviceLoginLock(this.#path, async (held) => {
32886
33032
  let login = await readDeviceLogin(this.#path);
@@ -32892,7 +33038,8 @@ class DeviceLoginIdentity {
32892
33038
  }
32893
33039
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
32894
33040
  const expires = login.accessExpiresAt?.getTime() ?? 0;
32895
- let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
33041
+ const least = leastAccessLifeMs(leastLifeMs, login.accessLifeSeconds);
33042
+ let refreshed = login.accessToken === "" || expires - Date.now() < least;
32896
33043
  if (refreshed)
32897
33044
  login = await refresh();
32898
33045
  while (true) {
@@ -33224,14 +33371,14 @@ function poolIdentity(options) {
33224
33371
  }
33225
33372
 
33226
33373
  // ../cipher-client/src/projected-token.ts
33227
- import { readFile as readFile3 } from "fs/promises";
33374
+ import { readFile as readFile5 } from "fs/promises";
33228
33375
  function projectedToken(path, variable) {
33229
33376
  const named = `the projected service-account token ${variable} names`;
33230
33377
  return {
33231
33378
  async read(signal) {
33232
33379
  let contents;
33233
33380
  try {
33234
- contents = await readFile3(path, {
33381
+ contents = await readFile5(path, {
33235
33382
  encoding: "utf8",
33236
33383
  ...signal === undefined ? {} : { signal }
33237
33384
  });
@@ -33340,13 +33487,15 @@ function tradeProjects(env) {
33340
33487
  }
33341
33488
  return sorted;
33342
33489
  }
33343
- async function brokerTokenClient(env, own = "") {
33490
+ async function brokerTokenClient(env, own = "", read) {
33344
33491
  const brokerUrl = value(env, BROKER_URL_VAR);
33345
33492
  const machine = machineIdentity(env);
33346
33493
  if (brokerUrl === "" || machine === undefined)
33347
33494
  return;
33348
33495
  if (!isHttpUrl(brokerUrl))
33349
33496
  throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
33497
+ const narrowed = read === undefined ? {} : { scope: SCOPE_READ, asOf: read.asOf };
33498
+ const heldApart = async () => read === undefined ? {} : { ...narrowed, holderKey: await newDpopKey() };
33350
33499
  if (machine instanceof DeviceLoginIdentity) {
33351
33500
  if (personTradeOff(env)) {
33352
33501
  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`);
@@ -33356,7 +33505,8 @@ async function brokerTokenClient(env, own = "") {
33356
33505
  key: await machine.key(),
33357
33506
  subject: machine,
33358
33507
  session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
33359
- projects: tradeProjects(env)
33508
+ projects: tradeProjects(env),
33509
+ ...await heldApart()
33360
33510
  });
33361
33511
  return { client, signIn: undefined };
33362
33512
  }
@@ -33367,7 +33517,8 @@ async function brokerTokenClient(env, own = "") {
33367
33517
  key: await newDpopKey(),
33368
33518
  subject: machine,
33369
33519
  session: tradeSession(env, own),
33370
- launcherCredential: false
33520
+ launcherCredential: false,
33521
+ ...narrowed
33371
33522
  });
33372
33523
  return { client, signIn: undefined };
33373
33524
  }
@@ -33381,7 +33532,8 @@ async function brokerTokenClient(env, own = "") {
33381
33532
  subject: personIdentity(record, flow),
33382
33533
  actor: machine,
33383
33534
  session: own.trim() || signInSessionName(record),
33384
- projects: tradeProjects(env)
33535
+ projects: tradeProjects(env),
33536
+ ...await heldApart()
33385
33537
  });
33386
33538
  return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
33387
33539
  }
@@ -33414,11 +33566,11 @@ function forgetBrokerSession(session) {
33414
33566
  function signInName(record) {
33415
33567
  return `${record.person}\x00${record.thumbprint}`;
33416
33568
  }
33417
- function keyOf(env, own) {
33418
- return {
33419
- session: own.trim(),
33420
- variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
33421
- };
33569
+ function keyOf(env, own, read) {
33570
+ const values = BROKER_VARIABLES.map((name) => env[name]);
33571
+ if (read !== undefined)
33572
+ values.push({ read: true, asOf: read.asOf ?? "" });
33573
+ return { session: own.trim(), variables: JSON.stringify(values) };
33422
33574
  }
33423
33575
  function entryFor(key) {
33424
33576
  let sessions = CLIENTS.get(key.session);
@@ -33433,13 +33585,13 @@ function entryFor(key) {
33433
33585
  }
33434
33586
  return entry;
33435
33587
  }
33436
- async function make(env, own) {
33437
- const made = await brokerTokenClient(env, own);
33588
+ async function make(env, own, read) {
33589
+ const made = await brokerTokenClient(env, own, read);
33438
33590
  const signIn = made?.signIn;
33439
33591
  return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
33440
33592
  }
33441
- async function clientFor(env, own) {
33442
- const key = keyOf(env, own);
33593
+ async function clientFor(env, own, read) {
33594
+ const key = keyOf(env, own, read);
33443
33595
  const entry = entryFor(key);
33444
33596
  if (entry.refused.size > 0) {
33445
33597
  const record = await chooseSignIn(env);
@@ -33454,7 +33606,7 @@ async function clientFor(env, own) {
33454
33606
  }
33455
33607
  let making = entry.making;
33456
33608
  if (making === undefined) {
33457
- const started = make(env, key.session);
33609
+ const started = make(env, key.session, read);
33458
33610
  making = started;
33459
33611
  entry.making = started;
33460
33612
  started.then((made) => {
@@ -33484,13 +33636,13 @@ function untilAborted(promise, signal) {
33484
33636
  });
33485
33637
  });
33486
33638
  }
33487
- async function tradedToken(env, own, signal, waitForReady = false) {
33488
- const { entry, made } = await untilAborted(clientFor(env, own), signal);
33639
+ async function tradedToken(env, own, { signal, waitForReady = false, read }) {
33640
+ const { entry, made } = await untilAborted(clientFor(env, own, read), signal);
33489
33641
  const { client } = made;
33490
33642
  if (client === undefined) {
33491
33643
  throw new LoggableError("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
33492
33644
  }
33493
- const { session, variables } = keyOf(env, own);
33645
+ const { session, variables } = keyOf(env, own, read);
33494
33646
  try {
33495
33647
  return {
33496
33648
  token: await client.token(signal, { waitForReady }),
@@ -33505,7 +33657,7 @@ async function tradedToken(env, own, signal, waitForReady = false) {
33505
33657
  }
33506
33658
  }
33507
33659
  function brokerTokenFor(env, session) {
33508
- return (signal, waitForReady) => tradedToken(env, sessionName(session), signal, waitForReady);
33660
+ return (signal, waitForReady) => tradedToken(env, sessionName(session), { signal, waitForReady });
33509
33661
  }
33510
33662
  function dropHeld(key, token) {
33511
33663
  CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop(token);
@@ -33513,14 +33665,14 @@ function dropHeld(key, token) {
33513
33665
  function dropTradedToken(env, traded) {
33514
33666
  dropHeld(keyOf(env, traded.session), traded.token.accessToken);
33515
33667
  }
33516
- function brokerCredential(env, session) {
33668
+ function brokerCredential(env, session, read) {
33517
33669
  let presented = "";
33518
33670
  const presentedAs = new WeakMap;
33519
33671
  const own = (acting) => (acting ?? "").trim() || sessionName(session);
33520
33672
  return {
33521
33673
  scheme: "DPoP",
33522
33674
  async headers(method, url, acting, signal) {
33523
- const traded = await tradedToken(env, own(acting), signal);
33675
+ const traded = await tradedToken(env, own(acting), { signal, read });
33524
33676
  const { token, key, identity } = traded;
33525
33677
  presented = token.accessToken;
33526
33678
  const headers = {
@@ -33529,7 +33681,7 @@ function brokerCredential(env, session) {
33529
33681
  };
33530
33682
  presentedAs.set(headers, {
33531
33683
  identity,
33532
- key: keyOf(env, traded.session),
33684
+ key: keyOf(env, traded.session, read),
33533
33685
  token: token.accessToken
33534
33686
  });
33535
33687
  return headers;
@@ -33537,12 +33689,65 @@ function brokerCredential(env, session) {
33537
33689
  identity: (headers) => presentedAs.get(headers)?.identity,
33538
33690
  stale(acting, headers) {
33539
33691
  const told = headers === undefined ? undefined : presentedAs.get(headers);
33540
- dropHeld(told?.key ?? keyOf(env, own(acting)), told?.token);
33692
+ dropHeld(told?.key ?? keyOf(env, own(acting), read), told?.token);
33541
33693
  },
33542
33694
  secret: () => presented
33543
33695
  };
33544
33696
  }
33545
33697
 
33698
+ // ../envoy-client/src/file-token-credential.ts
33699
+ import { readFileSync as readFileSync2 } from "fs";
33700
+ var TOKEN_FILE_VAR = "DISPATCH_BROKER_TOKEN_FILE";
33701
+ var DPOP_KEY_FILE_VAR = "DISPATCH_BROKER_DPOP_KEY_FILE";
33702
+ var PKCS8_LABEL = "PRIVATE KEY";
33703
+ var PKCS8_PEM = new RegExp(`^-----BEGIN ${PKCS8_LABEL}-----\\r?\\n(?:[A-Za-z0-9+/=]+\\r?\\n)+-----END ${PKCS8_LABEL}-----$`);
33704
+ function readNamed(variable, filePath) {
33705
+ try {
33706
+ return readFileSync2(filePath, "utf8");
33707
+ } catch (error) {
33708
+ throw new Error(`${variable} names ${filePath}, which could not be read (${readErrorCode(error)})`);
33709
+ }
33710
+ }
33711
+ function tokenIn(filePath) {
33712
+ const token = readNamed(TOKEN_FILE_VAR, filePath).trim();
33713
+ if (token === "") {
33714
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds no token: it is empty or blank`);
33715
+ }
33716
+ if (!sendable(token)) {
33717
+ throw new Error(`${TOKEN_FILE_VAR} names ${filePath}, which holds whitespace or a control character inside its token`);
33718
+ }
33719
+ return holdSecret(token);
33720
+ }
33721
+ async function keyIn(filePath) {
33722
+ const pem = readNamed(DPOP_KEY_FILE_VAR, filePath).trim();
33723
+ if (!PKCS8_PEM.test(pem)) {
33724
+ throw new Error(`${DPOP_KEY_FILE_VAR} names ${filePath}, which does not hold one P-256 private key in PKCS#8 PEM`);
33725
+ }
33726
+ return await importDpopKey(pem, `${DPOP_KEY_FILE_VAR}'s key ${filePath}`);
33727
+ }
33728
+ function fileTokenCredential(files, dispatchUrl) {
33729
+ const origin = httpUrl2(dispatchUrl)?.origin;
33730
+ let presented = "";
33731
+ return {
33732
+ scheme: "DPoP",
33733
+ async headers(method, url) {
33734
+ const target = httpUrl2(url)?.origin;
33735
+ if (origin === undefined || target !== origin) {
33736
+ 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"}`);
33737
+ }
33738
+ const token = tokenIn(files.tokenFile);
33739
+ const key = await keyIn(files.keyFile);
33740
+ presented = token;
33741
+ return {
33742
+ Authorization: `DPoP ${token}`,
33743
+ DPoP: await key.proof({ method, url, accessToken: token })
33744
+ };
33745
+ },
33746
+ stale() {},
33747
+ secret: () => presented
33748
+ };
33749
+ }
33750
+
33546
33751
  // ../envoy-client/src/dispatch-config.ts
33547
33752
  var DEFAULT_SERVER_URL = "http://localhost:8766";
33548
33753
  function checkoutPair(checkout, serverUrl) {
@@ -33586,14 +33791,20 @@ function lostDispatchUrlNotice(env, config) {
33586
33791
  ...old === undefined ? [] : [old]
33587
33792
  ].join("; ");
33588
33793
  }
33589
- function dispatchSettings(env, config, options = {}) {
33590
- const target = dispatchTarget(env, config);
33794
+ async function dispatchSettings(env, config, options = {}) {
33795
+ const target = await dispatchTarget(env, config, options.tokenFiles === true);
33591
33796
  if (!target.enabled)
33592
33797
  return target;
33593
33798
  const { url, urlSetting, source } = target;
33594
33799
  let credential;
33595
33800
  try {
33596
- credential = source.kind === "broker" ? brokerCredential(env, options.session) : bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env, options.commands));
33801
+ if (source.kind === "broker")
33802
+ credential = brokerCredential(env, options.session, source.read);
33803
+ else if (source.kind === "files")
33804
+ credential = fileTokenCredential(source, url);
33805
+ else {
33806
+ credential = bearerCredential(source.kind === "variable" ? source.token : await fileBearer(source, url, "DISPATCH", env, options.commands));
33807
+ }
33597
33808
  } catch (error) {
33598
33809
  return offWithError(messageFor(error));
33599
33810
  }
@@ -33612,10 +33823,67 @@ function dispatchSettings(env, config, options = {}) {
33612
33823
  ...linkNotice === undefined ? {} : { linkNotice }
33613
33824
  };
33614
33825
  }
33615
- function dispatchUrl(env, config) {
33616
- const target = dispatchTarget(env, config);
33826
+ async function dispatchUrl(env, config) {
33827
+ const target = await dispatchTarget(env, config);
33617
33828
  return target.enabled ? target.url : undefined;
33618
33829
  }
33830
+ var BESIDE_TOKEN_FILES = [
33831
+ "DISPATCH_TOKEN_BROKER",
33832
+ "DISPATCH_TOKEN_BROKER_READ",
33833
+ "DISPATCH_TOKEN_BROKER_AS_OF",
33834
+ "DISPATCH_TOKEN",
33835
+ "DISPATCH_TOKEN_FILE",
33836
+ BROKER_URL_VAR,
33837
+ IDENTITY_VAR
33838
+ ];
33839
+ function tokenFilesSet(env) {
33840
+ const set = [
33841
+ ...nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE) === undefined ? [] : [TOKEN_FILE_VAR],
33842
+ ...nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE) === undefined ? [] : [DPOP_KEY_FILE_VAR]
33843
+ ];
33844
+ if (set.length === 0)
33845
+ return;
33846
+ return `${set.join(" and ")} ${set.length === 1 ? "is" : "are"} set`;
33847
+ }
33848
+ function settingsBesideTokenFiles(env) {
33849
+ return BESIDE_TOKEN_FILES.filter((name) => nonEmpty(env[name]) !== undefined).map((name) => `${name} is set`);
33850
+ }
33851
+ function tokenFilesTarget(env, config, taken) {
33852
+ const set = tokenFilesSet(env);
33853
+ if (set === undefined)
33854
+ return;
33855
+ if (!taken) {
33856
+ return offWithError(`${set}, and only the dispatch command reads the token files: Dispatch is off here rather than written with another credential beside them`);
33857
+ }
33858
+ const tokenFile = nonEmpty(env.DISPATCH_BROKER_TOKEN_FILE);
33859
+ const keyFile = nonEmpty(env.DISPATCH_BROKER_DPOP_KEY_FILE);
33860
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
33861
+ const { checkout } = config;
33862
+ const problems = [
33863
+ ...tokenFile === undefined ? [`${TOKEN_FILE_VAR} is not set`] : [],
33864
+ ...keyFile === undefined ? [`${DPOP_KEY_FILE_VAR} is not set`] : [],
33865
+ ...explicitUrl === undefined ? ["DISPATCH_URL is not set"] : [],
33866
+ ...settingsBesideTokenFiles(env),
33867
+ ...config.dispatch.token === undefined ? [] : [`dispatch.token is set in ${config.path}`],
33868
+ ...checkout?.kind === "valid" && checkout.dispatch.token !== undefined ? [`dispatch.token is set in ${checkout.path}`] : [],
33869
+ ...checkout?.kind === "invalid" ? [`${checkout.error}, so whether it sets dispatch.token cannot be told`] : []
33870
+ ];
33871
+ if (problems.length > 0 || tokenFile === undefined || keyFile === undefined || explicitUrl === undefined) {
33872
+ 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("; ")}`);
33873
+ }
33874
+ if (config.dispatch.enabled === false) {
33875
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
33876
+ }
33877
+ if (httpUrl2(explicitUrl) === undefined) {
33878
+ return offWithError("DISPATCH_URL must be an http or https URL");
33879
+ }
33880
+ return {
33881
+ enabled: true,
33882
+ url: withoutTrailingSlashes(explicitUrl),
33883
+ urlSetting: "DISPATCH_URL",
33884
+ source: { kind: "files", tokenFile, keyFile }
33885
+ };
33886
+ }
33619
33887
  function brokerRouteForced(env) {
33620
33888
  const written = (env.DISPATCH_TOKEN_BROKER ?? "").trim();
33621
33889
  if (written === "")
@@ -33624,12 +33892,55 @@ function brokerRouteForced(env) {
33624
33892
  return true;
33625
33893
  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");
33626
33894
  }
33627
- function dispatchTarget(env, config) {
33895
+ var CUT_FORM = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;
33896
+ var ZERO_TIME = Date.parse("0001-01-01T00:00:00.000Z");
33897
+ function isCut(text) {
33898
+ const parts = CUT_FORM.exec(text);
33899
+ if (parts === null)
33900
+ return false;
33901
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = parts.slice(1, 7).map((part) => Number(part ?? "0"));
33902
+ const [zoneHour = 0, zoneMinute = 0] = parts.slice(9, 11).map((part) => Number(part ?? "0"));
33903
+ const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
33904
+ const exists = month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth && hour <= 23 && minute <= 59 && second <= 59 && zoneHour <= 23 && zoneMinute <= 59;
33905
+ if (!exists)
33906
+ return false;
33907
+ const offset = (parts[8] === "-" ? -1 : 1) * (zoneHour * 60 + zoneMinute);
33908
+ const instant = new Date(0);
33909
+ instant.setUTCFullYear(year, month - 1, day);
33910
+ instant.setUTCHours(hour, minute - offset, second, 0);
33911
+ return Number(parts[7] ?? "0") !== 0 || instant.getTime() !== ZERO_TIME;
33912
+ }
33913
+ function readTradeSetting(env) {
33914
+ const read = (env.DISPATCH_TOKEN_BROKER_READ ?? "").trim();
33915
+ const cut = (env.DISPATCH_TOKEN_BROKER_AS_OF ?? "").trim();
33916
+ if (read !== "" && read !== "1") {
33917
+ 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");
33918
+ }
33919
+ if (read === "") {
33920
+ if (cut === "")
33921
+ return;
33922
+ 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");
33923
+ }
33924
+ if (cut === "")
33925
+ return {};
33926
+ if (!isCut(cut)) {
33927
+ 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");
33928
+ }
33929
+ return { asOf: cut };
33930
+ }
33931
+ async function dispatchTarget(env, config, tokenFiles = false) {
33628
33932
  if (config.kind === "failed")
33629
33933
  return offWithError(config.error);
33630
- const forced = brokerRouteForced(env);
33631
- if (typeof forced !== "boolean")
33632
- return forced;
33934
+ const files = tokenFilesTarget(env, config, tokenFiles);
33935
+ if (files !== undefined)
33936
+ return files;
33937
+ const brokerOnly = brokerRouteForced(env);
33938
+ if (typeof brokerOnly !== "boolean")
33939
+ return brokerOnly;
33940
+ const read = readTradeSetting(env);
33941
+ if (read !== undefined && "enabled" in read)
33942
+ return read;
33943
+ const forced = brokerOnly || read !== undefined;
33633
33944
  const explicitUrl = nonEmpty(env.DISPATCH_URL);
33634
33945
  const checkoutFile = explicitUrl === undefined ? config.checkout : null;
33635
33946
  if (checkoutFile?.kind === "invalid")
@@ -33656,7 +33967,7 @@ function dispatchTarget(env, config) {
33656
33967
  let source = { kind: "none" };
33657
33968
  if (!forced) {
33658
33969
  try {
33659
- source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33970
+ source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : await bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33660
33971
  } catch (error) {
33661
33972
  return offWithError(messageFor(error));
33662
33973
  }
@@ -33671,10 +33982,10 @@ function dispatchTarget(env, config) {
33671
33982
  if (route.traded) {
33672
33983
  const brokered = withoutTrailingSlashes(explicitUrl ?? own.serverUrl ?? DEFAULT_SERVER_URL);
33673
33984
  const urlSetting = explicitUrl !== undefined ? "DISPATCH_URL" : own.serverUrl !== undefined ? `dispatch.serverUrl in ${config.path}` : DEFAULT_URL_SETTING;
33674
- return { enabled: true, url: brokered, urlSetting, source: { kind: "broker" } };
33985
+ return { enabled: true, url: brokered, urlSetting, source: { kind: "broker", read } };
33675
33986
  }
33676
33987
  if (forced) {
33677
- 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`);
33988
+ 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`);
33678
33989
  }
33679
33990
  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}`);
33680
33991
  }
@@ -33860,7 +34171,6 @@ function brokerNatsCredential(env, session, source = NATS_AUTH_VAR, tradeDeadlin
33860
34171
  admissions: () => admissions
33861
34172
  };
33862
34173
  }
33863
- var RENEW_FLOOR_MS = 1000;
33864
34174
  var RETRY_FIRST_MS = 2000;
33865
34175
  var RETRY_LAST_MS = 60000;
33866
34176
  var WARN_AGAIN_MS = 30 * 60000;
@@ -33917,11 +34227,7 @@ function warnedEvery(warn) {
33917
34227
  };
33918
34228
  }
33919
34229
  function renewDelay(expiry, now) {
33920
- const remaining = expiry - now;
33921
- if (remaining <= 0)
33922
- return 0;
33923
- const ahead = remaining - Math.min(DEFAULT_RENEW_BEFORE_MS, remaining / 2);
33924
- return Math.max(Math.min(RENEW_FLOOR_MS, remaining / 2), ahead);
34230
+ return renewalAt(expiry, now, DEFAULT_RENEW_BEFORE_MS) - now;
33925
34231
  }
33926
34232
  function keepNatsCredential(connection, credential, warn) {
33927
34233
  let stopped = false;
@@ -34095,13 +34401,13 @@ function resolvedInterval(raw, fallback) {
34095
34401
  return named === undefined ? fallback : Math.min(Math.max(named, MIN_INTERVAL_MS), MAX_INTERVAL_MS);
34096
34402
  }
34097
34403
  var ENVOY_INBOUND_VAR = "ENVOY_INBOUND";
34098
- function natsSeedFromEnvironment(env) {
34404
+ async function natsSeedFromEnvironment(env) {
34099
34405
  const { NATS_NKEY_SEED_FILE: file, NATS_NKEY_SEED: plain } = env;
34100
34406
  if (file !== undefined) {
34101
34407
  if (file === "")
34102
34408
  throw new Error("NATS_NKEY_SEED_FILE is set but empty");
34103
34409
  return {
34104
- value: readSecretFile("NATS_NKEY_SEED_FILE", file),
34410
+ value: await readSecretFile("NATS_NKEY_SEED_FILE", file),
34105
34411
  source: "the file NATS_NKEY_SEED_FILE names"
34106
34412
  };
34107
34413
  }
@@ -34130,23 +34436,23 @@ function requireFileServers(section, namedNatsUrls, filePath, remedy) {
34130
34436
  throw new Error(`ENVOY_NATS_URL names other servers than ${filePath}'s envoy.natsUrls; set ${remedy} for them`);
34131
34437
  }
34132
34438
  }
34133
- function natsSeed(env, section, namedNatsUrls, filePath) {
34134
- const fromEnvironment = natsSeedFromEnvironment(env);
34439
+ async function natsSeed(env, section, namedNatsUrls, filePath) {
34440
+ const fromEnvironment = await natsSeedFromEnvironment(env);
34135
34441
  if (fromEnvironment !== undefined || section.natsSeed === undefined)
34136
34442
  return fromEnvironment;
34137
34443
  requireFileServers(section, namedNatsUrls, filePath, "NATS_NKEY_SEED_FILE");
34138
34444
  return {
34139
- value: fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
34445
+ value: await fileValue(section.natsSeed, "envoy.natsSeed", filePath, env),
34140
34446
  source: `envoy.natsSeed in ${filePath}`
34141
34447
  };
34142
34448
  }
34143
- function natsCredential(env, section, namedNatsUrls, filePath, session) {
34449
+ async function natsCredential(env, section, namedNatsUrls, filePath, session) {
34144
34450
  const named = nonEmpty(env.NATS_AUTH);
34145
34451
  const auth = named !== undefined ? { value: named, source: NATS_AUTH_VAR } : section.natsAuth === undefined ? undefined : { value: section.natsAuth, source: `envoy.natsAuth in ${filePath}` };
34146
34452
  if (auth !== undefined && auth.value !== "broker" && auth.value !== "none") {
34147
34453
  throw new Error(`${auth.source} is neither broker nor none`);
34148
34454
  }
34149
- const seed = natsSeed(env, section, namedNatsUrls, filePath);
34455
+ const seed = await natsSeed(env, section, namedNatsUrls, filePath);
34150
34456
  if (seed !== undefined) {
34151
34457
  if (auth?.value === "broker") {
34152
34458
  throw new Error(`${auth.source} is ${auth.value}, and ${seed.source} names an nkey seed: set one of the two`);
@@ -34191,7 +34497,7 @@ function plainHttpOffMachine(url) {
34191
34497
  const host = URL.canParse(url) ? new URL(url) : undefined;
34192
34498
  return host?.protocol === "http:" && !LOOPBACK_HOST2.test(host.hostname) ? host.hostname : undefined;
34193
34499
  }
34194
- function envoySettings(env, config, options = {}) {
34500
+ async function envoySettings(env, config, options = {}) {
34195
34501
  if (config.kind === "failed")
34196
34502
  return offWithError(config.error);
34197
34503
  const section = config.envoy;
@@ -34222,7 +34528,7 @@ function envoySettings(env, config, options = {}) {
34222
34528
  let credential;
34223
34529
  let noBrokerRoute = "";
34224
34530
  try {
34225
- const source = bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
34531
+ const source = await bearerSource(env, "ENVOY", () => section.token === undefined ? undefined : {
34226
34532
  token: section.token,
34227
34533
  field: "envoy.token",
34228
34534
  path: config.path,
@@ -34235,7 +34541,7 @@ function envoySettings(env, config, options = {}) {
34235
34541
  if (!route.traded)
34236
34542
  noBrokerRoute = route.gap;
34237
34543
  } else {
34238
- credential = bearerCredential(source.kind === "variable" ? source.token : fileBearer(source, url, "ENVOY", env));
34544
+ credential = bearerCredential(source.kind === "variable" ? source.token : await fileBearer(source, url, "ENVOY", env));
34239
34545
  }
34240
34546
  } catch (error) {
34241
34547
  return offWithError(messageFor(error));
@@ -34255,7 +34561,7 @@ function envoySettings(env, config, options = {}) {
34255
34561
  inbound = {
34256
34562
  natsUrls,
34257
34563
  natsServersSetting: natsSetting,
34258
- natsCredential: natsCredential(env, section, namedNatsUrls, config.path, options.session)
34564
+ natsCredential: await natsCredential(env, section, namedNatsUrls, config.path, options.session)
34259
34565
  };
34260
34566
  } catch (error) {
34261
34567
  inbound = error instanceof NoSessionNamedError ? { off: messageFor(error), noSessionNamed: true } : { off: messageFor(error) };
@@ -34339,42 +34645,45 @@ function startNotice(config, dispatch, envoy, nats, lost) {
34339
34645
  }
34340
34646
  return parts.length === 0 ? null : parts.join("; ");
34341
34647
  }
34342
- function sessionSettings(file, env, options) {
34648
+ async function sessionSettings(file, env, options) {
34343
34649
  if (file.path === null) {
34344
34650
  const off = offWithError(file.error);
34345
34651
  return { dispatch: off, envoy: off, notice: `${file.error}: Dispatch and Envoy are off` };
34346
34652
  }
34347
- const config = readEnvoyConfig(file.path, env, options);
34348
- const dispatch = dispatchSettings(env, config, { session: options.session });
34349
- const envoy = envoySettings(env, config, { nats: options.nats, session: options.session });
34653
+ const config = await readEnvoyConfig(file.path, env, options);
34654
+ const [dispatch, envoy] = await Promise.all([
34655
+ dispatchSettings(env, config, { session: options.session }),
34656
+ envoySettings(env, config, { nats: options.nats, session: options.session })
34657
+ ]);
34350
34658
  return {
34351
34659
  dispatch,
34352
34660
  envoy,
34353
34661
  notice: startNotice(config, dispatch, envoy, options.nats !== false, config.kind === "read" ? lostDispatchUrlNotice(env, config) : undefined)
34354
34662
  };
34355
34663
  }
34356
- function sessionDispatchSettings(file, env, options) {
34664
+ async function sessionDispatchSettings(file, env, options) {
34357
34665
  if (file.path === null)
34358
34666
  return { dispatch: offWithError(file.error), warnings: [], missing: null };
34359
- const config = readEnvoyConfig(file.path, env, options);
34667
+ const config = await readEnvoyConfig(file.path, env, options);
34360
34668
  return {
34361
- dispatch: dispatchSettings(env, config, {
34669
+ dispatch: await dispatchSettings(env, config, {
34362
34670
  commands: options.commands,
34363
- session: options.session
34671
+ session: options.session,
34672
+ tokenFiles: options.tokenFiles
34364
34673
  }),
34365
34674
  warnings: config.kind === "read" ? config.warnings : [],
34366
34675
  missing: config.kind === "read" ? config.missing : null
34367
34676
  };
34368
34677
  }
34369
- function sessionDispatchUrl(file, env, options) {
34678
+ async function sessionDispatchUrl(file, env, options) {
34370
34679
  if (file.path === null)
34371
34680
  return;
34372
- return dispatchUrl(env, readEnvoyConfig(file.path, env, options));
34681
+ return dispatchUrl(env, await readEnvoyConfig(file.path, env, options));
34373
34682
  }
34374
- function sessionEnvoySettings(file, env, options) {
34683
+ async function sessionEnvoySettings(file, env, options) {
34375
34684
  if (file.path === null)
34376
34685
  return offWithError(file.error);
34377
- return envoySettings(env, readEnvoyConfig(file.path, env, options), {
34686
+ return envoySettings(env, await readEnvoyConfig(file.path, env, options), {
34378
34687
  nats: options.nats,
34379
34688
  session: options.session
34380
34689
  });
@@ -34399,18 +34708,18 @@ function claudeProjectDirectory(environment, fallback) {
34399
34708
 
34400
34709
  // src/codex/codex-session-record.ts
34401
34710
  import { spawnSync } from "child_process";
34402
- import { readFileSync as readFileSync5, readlinkSync as readlinkSync2, unwatchFile, watchFile } from "fs";
34403
- import { mkdir as mkdir3, readFile as readFile5, rename as rename4, utimes as utimes3, writeFile as writeFile2 } from "fs/promises";
34711
+ import { readFileSync as readFileSync4, readlinkSync, unwatchFile, watchFile } from "fs";
34712
+ import { mkdir as mkdir3, readFile as readFile7, rename as rename4, utimes as utimes3, writeFile as writeFile2 } from "fs/promises";
34404
34713
  import { homedir as homedir3 } from "os";
34405
34714
  import { basename as basename4, dirname as dirname5, join as join9 } from "path";
34406
34715
 
34407
34716
  // src/session-identity.ts
34408
- import { readFile as readFile4 } from "fs/promises";
34717
+ import { readFile as readFile6 } from "fs/promises";
34409
34718
  import { basename as basename3, join as join8 } from "path";
34410
34719
 
34411
34720
  // src/session-state.ts
34412
- import { readFileSync as readFileSync4 } from "fs";
34413
- import { mkdir as mkdir2, readdir as readdir3, rename as rename3, rm as rm3, stat as stat3, utimes as utimes2, writeFile } from "fs/promises";
34721
+ import { readFileSync as readFileSync3 } from "fs";
34722
+ import { mkdir as mkdir2, readdir as readdir3, rename as rename3, rm as rm4, stat as stat4, utimes as utimes2, writeFile } from "fs/promises";
34414
34723
  import { dirname as dirname4, join as join7 } from "path";
34415
34724
  async function writeAtomicStateFile(file, contents) {
34416
34725
  await mkdir2(dirname4(file), { recursive: true, mode: 448 });
@@ -34432,12 +34741,12 @@ async function pruneStateDirectory(directory, isStale) {
34432
34741
  const file = join7(directory, entry);
34433
34742
  if (!await isStale(file))
34434
34743
  continue;
34435
- await rm3(file, { recursive: true, force: true });
34744
+ await rm4(file, { recursive: true, force: true });
34436
34745
  }
34437
34746
  }
34438
34747
  var STATE_FILE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
34439
34748
  async function writtenLongAgo(file) {
34440
- const modified = await stat3(file).then((stats) => stats.mtimeMs, () => {
34749
+ const modified = await stat4(file).then((stats) => stats.mtimeMs, () => {
34441
34750
  return;
34442
34751
  });
34443
34752
  return modified !== undefined && Date.now() - modified > STATE_FILE_MAX_AGE_MS;
@@ -34451,11 +34760,11 @@ async function writeChosenTitle(file, title) {
34451
34760
  `);
34452
34761
  }
34453
34762
  async function removeChosenTitle(file) {
34454
- await rm3(file, { force: true });
34763
+ await rm4(file, { force: true });
34455
34764
  }
34456
34765
  function readChosenTitleSync(file) {
34457
34766
  try {
34458
- return readFileSync4(file, "utf8");
34767
+ return readFileSync3(file, "utf8");
34459
34768
  } catch {
34460
34769
  return;
34461
34770
  }
@@ -34516,7 +34825,7 @@ class UnparseableRoleRecordError extends Error {
34516
34825
  async function readPersistedRole(roleFile) {
34517
34826
  let bytes;
34518
34827
  try {
34519
- bytes = await readFile4(roleFile, "utf8");
34828
+ bytes = await readFile6(roleFile, "utf8");
34520
34829
  } catch (error) {
34521
34830
  if (hasErrnoCode(error, "ENOENT"))
34522
34831
  return;
@@ -34538,7 +34847,7 @@ async function writeSessionHandoff(file, sessionId) {
34538
34847
  }
34539
34848
  async function readSessionHandoff(file) {
34540
34849
  try {
34541
- const id = (await readFile4(file, "utf8")).trim();
34850
+ const id = (await readFile6(file, "utf8")).trim();
34542
34851
  return id.length === 0 ? undefined : id;
34543
34852
  } catch (error) {
34544
34853
  if (hasErrnoCode(error, "ENOENT"))
@@ -34602,7 +34911,7 @@ function watchRecord(file, pid, ended, changed, intervalMs) {
34602
34911
  }
34603
34912
  async function sessionEnded(file) {
34604
34913
  try {
34605
- await readFile5(file);
34914
+ await readFile7(file);
34606
34915
  return true;
34607
34916
  } catch {
34608
34917
  return false;
@@ -34616,7 +34925,7 @@ async function writeCodexSessionRecord(file, value) {
34616
34925
  }
34617
34926
  async function readCodexSessionRecord(file) {
34618
34927
  try {
34619
- const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile5(file, "utf8")));
34928
+ const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile7(file, "utf8")));
34620
34929
  return parsed.success ? parsed.data : undefined;
34621
34930
  } catch {
34622
34931
  return;
@@ -34648,14 +34957,14 @@ function codexProcessId(readComm = procComm, readParent = procParent) {
34648
34957
  }
34649
34958
  function procComm(pid) {
34650
34959
  try {
34651
- return readFileSync5(`/proc/${pid}/comm`, "utf8").trim();
34960
+ return readFileSync4(`/proc/${pid}/comm`, "utf8").trim();
34652
34961
  } catch {
34653
34962
  return;
34654
34963
  }
34655
34964
  }
34656
34965
  function procParent(pid) {
34657
34966
  try {
34658
- const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
34967
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
34659
34968
  const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
34660
34969
  return Number.isInteger(parent) ? parent : undefined;
34661
34970
  } catch {
@@ -34669,7 +34978,7 @@ var PS_OPTIONS = {
34669
34978
  };
34670
34979
  function procStarted(pid) {
34671
34980
  try {
34672
- const stat = readFileSync5(`/proc/${pid}/stat`, "utf8");
34981
+ const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
34673
34982
  return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
34674
34983
  } catch {
34675
34984
  return;
@@ -34690,7 +34999,7 @@ function recordOfProcess(record, pid) {
34690
34999
  function sharedAppServer(pid) {
34691
35000
  let argv;
34692
35001
  try {
34693
- argv = readFileSync5(`/proc/${pid}/cmdline`, "utf8").split("\x00");
35002
+ argv = readFileSync4(`/proc/${pid}/cmdline`, "utf8").split("\x00");
34694
35003
  } catch {
34695
35004
  const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS);
34696
35005
  if (ps.status !== 0)
@@ -34747,7 +35056,7 @@ async function pruneCodexSessionRecords(stateDirectory) {
34747
35056
  }
34748
35057
  function codexExecutable(pid) {
34749
35058
  try {
34750
- return readlinkSync2(`/proc/${pid}/exe`);
35059
+ return readlinkSync(`/proc/${pid}/exe`);
34751
35060
  } catch {
34752
35061
  return;
34753
35062
  }
@@ -34806,7 +35115,7 @@ async function sessionStart(raw) {
34806
35115
  process.stderr.write(`envoy: this session was not recorded, because the start of codex process ${pid} cannot be read; it gets no Envoy messages
34807
35116
  `);
34808
35117
  } else {
34809
- await rm4(codexEndedFile(pluginData, pid, input.session_id), { force: true });
35118
+ await rm5(codexEndedFile(pluginData, pid, input.session_id), { force: true });
34810
35119
  await writeCodexSessionRecord(codexSessionRecordFile(pluginData, pid), {
34811
35120
  codex_executable: codexExecutable(pid) ?? null,
34812
35121
  codex_home: codexHome(process.env),
@@ -34824,7 +35133,7 @@ async function sessionStart(raw) {
34824
35133
  }
34825
35134
  }
34826
35135
  const chosen = sessionConfigFile("codex", process.env);
34827
- const { dispatch, warnings } = sessionDispatchSettings(chosen, process.env, {
35136
+ const { dispatch, warnings } = await sessionDispatchSettings(chosen, process.env, {
34828
35137
  cwd: input.cwd,
34829
35138
  session: input.session_id
34830
35139
  });