@sjawhar/claude-envoy 2.27.0 → 2.28.0

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.
@@ -981,7 +981,7 @@ __export(exports_coerce, {
981
981
 
982
982
  // hooks/session-hook.ts
983
983
  import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
984
- import { join as join7 } from "path";
984
+ import { join as join8 } from "path";
985
985
  // ../../node_modules/.bun/zod@4.3.6/node_modules/zod/v4/core/core.js
986
986
  var NEVER = Object.freeze({
987
987
  status: "aborted"
@@ -14207,6 +14207,14 @@ var handoffValidation = {
14207
14207
  message: HANDOFF_RULE,
14208
14208
  refusal: (value) => handoffProblem(value) ?? HANDOFF_RULE
14209
14209
  };
14210
+ var REVIEW_REASON_RULE = "verdict changes_requested requires reason, a non-empty note saying what must change before the document can be approved.";
14211
+ var reviewValidation = {
14212
+ check: (value) => {
14213
+ const input = value;
14214
+ return input.verdict !== "changes_requested" || typeof input.reason === "string" && input.reason.trim() !== "";
14215
+ },
14216
+ message: REVIEW_REASON_RULE
14217
+ };
14210
14218
  var RESULT_REQUIRED_FIELDS = ["issue", "check", "role", "verdict", "commit"];
14211
14219
  var RESULT_RECORD_FIELDS = [
14212
14220
  ...RESULT_REQUIRED_FIELDS,
@@ -14590,6 +14598,20 @@ var dispatchToolSpecs = [
14590
14598
  version: z.number({ int: true, min: 1 }).describe("The plan version the review read and approved.")
14591
14599
  })
14592
14600
  },
14601
+ {
14602
+ name: "dispatch_review",
14603
+ example: { issue: "DSP-1", version: 2, verdict: "approved" },
14604
+ description: "Approve one version of an issue's document, or request changes on it, as the person your " + "token names: what the document header's Approve and Request changes record. A review " + "records an approval or a changes request in the person's name at that version, so it " + "works only with a token that names a person who holds approve; Dispatch refuses it to " + "any other token, with 403 OAUTH_SCOPE_REQUIRED or 403 SIGN_IN_REQUIRED. --version is the " + "version you read, sent in the review route's path, and it must be the version the review " + "would record: the document's latest settled version, or, while an approval request is " + "open on it, the version that request names for it. Any other is refused 409 " + "REVIEW_VERSION_MOVED, which names the version to read, and nothing is recorded. A " + "Dispatch build without the versioned review route answers no route and records nothing; " + "the command then says so and names /healthz, which names the commit of the build that " + "answers it when that build was stamped with one. With a request open the review answers " + "it, and records the same verdict on every document the " + "request names, each at the version the request names. A later version makes an approval " + "stale. A review is the one browser action this command takes for a person; every other " + "browser action is dispatch://INFRA-910's. " + ISSUE_REFERENCE,
14605
+ arguments: (z) => ({
14606
+ issue: z.string().describe(ISSUE_REFERENCE),
14607
+ artifact: z.string().describe("Document artifact id, slug, or filename; the issue's spec by default.").optional(),
14608
+ version: z.number({ int: true, min: 1 }).describe("The document version you read and review, sent as a segment of the review route's path: the version the review would record, or Dispatch refuses it 409 REVIEW_VERSION_MOVED naming the version to read."),
14609
+ verdict: z.enum(["approved", "changes_requested"]).describe("approved records an approval; changes_requested records a request for changes and requires reason."),
14610
+ reason: z.string().describe("What must change before the document can be approved. changes_requested requires it; an approval may carry one.").optional()
14611
+ }),
14612
+ validation: reviewValidation,
14613
+ strict: true
14614
+ },
14593
14615
  {
14594
14616
  name: "dispatch_result",
14595
14617
  example: {
@@ -18205,6 +18227,9 @@ class DispatchNoRouteError extends DispatchServiceError {
18205
18227
  super("NOT_FOUND", 404, NO_ROUTE_ROLLING_RELEASE_MESSAGE);
18206
18228
  }
18207
18229
  }
18230
+ function reviewNoRouteRefusal(baseUrl, route, version) {
18231
+ return new DispatchServiceError("NOT_FOUND", 404, `Dispatch at ${baseUrl} answered no route for ${route} each time the review was sent, and an ` + "answer of no route records no review. This build is older than that route. No other review " + "route was asked: the review route an older build serves takes no version, and it " + `would record the review at a version that build chooses, which may not be version ${version}. ` + `The no-route answer does not name the build; GET ${baseUrl}/healthz names the commit of the ` + "build that answers it, when that build was stamped with one.");
18232
+ }
18208
18233
  var ISSUE_EVENTS_PAGE_MAX = 200;
18209
18234
  var DISPATCH_TOOL_DEADLINE_MS = 60000;
18210
18235
  function requestSignal(signal) {
@@ -18338,6 +18363,15 @@ async function writeAnswer(response, key) {
18338
18363
  unjudged: !echoed && typeof shape.error === "string"
18339
18364
  };
18340
18365
  }
18366
+ var BROKER_TOKEN_NOT_ACTIVE = "BROKER_TOKEN_NOT_ACTIVE";
18367
+ async function tokenNotLive(response) {
18368
+ if (response.status !== 401 || !isJson(response))
18369
+ return false;
18370
+ const body = await response.clone().json().catch(() => {
18371
+ return;
18372
+ });
18373
+ return asErrorShape(body).code === BROKER_TOKEN_NOT_ACTIVE;
18374
+ }
18341
18375
  function whyNotAPage(answer) {
18342
18376
  if (typeof answer === "string") {
18343
18377
  return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
@@ -18660,6 +18694,18 @@ class DispatchClient {
18660
18694
  async planApprove(artifactID, input) {
18661
18695
  return this.#json("POST", ["api", "v1", "artifacts", artifactID, "plan-reviews"], input);
18662
18696
  }
18697
+ async reviewArtifact(artifactID, version, input) {
18698
+ const path = ["api", "v1", "artifacts", artifactID, "versions", String(version), "reviews"];
18699
+ const body = { state: input.state, reason: input.reason };
18700
+ try {
18701
+ return await this.#json("POST", path, body);
18702
+ } catch (error) {
18703
+ if (!(error instanceof DispatchNoRouteError) && !isNoRoute(error))
18704
+ throw error;
18705
+ const route = `POST /${path.map((segment) => encodeURIComponent(segment)).join("/")}`;
18706
+ throw reviewNoRouteRefusal(this.#baseUrl, route, version);
18707
+ }
18708
+ }
18663
18709
  async recordResult(issue, input) {
18664
18710
  return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "results"], input);
18665
18711
  }
@@ -18895,11 +18941,20 @@ class DispatchClient {
18895
18941
  });
18896
18942
  }
18897
18943
  async#send(method, url, body, accept = "application/json", signal, callerKey) {
18944
+ const key = method === "POST" || method === "PATCH" ? callerKey ?? crypto.randomUUID() : undefined;
18945
+ const send = async () => this.#sendPresenting(method, url, body, accept, signal, key);
18946
+ const answer = await send();
18947
+ if (this.#credential.stale === undefined || !await tokenNotLive(answer))
18948
+ return answer;
18949
+ this.#credential.stale();
18950
+ return await send();
18951
+ }
18952
+ async#sendPresenting(method, url, body, accept, signal, key) {
18898
18953
  const headers = { Accept: accept };
18899
18954
  let presented = await this.#credential.headers(method, url);
18900
18955
  if (body !== undefined)
18901
18956
  headers["Content-Type"] = body.type;
18902
- if (method !== "POST" && method !== "PATCH") {
18957
+ if (key === undefined) {
18903
18958
  return this.fetchImpl(url, {
18904
18959
  method,
18905
18960
  headers: { ...headers, ...presented },
@@ -18907,7 +18962,6 @@ class DispatchClient {
18907
18962
  ...body === undefined ? {} : { body: body.content }
18908
18963
  });
18909
18964
  }
18910
- const key = callerKey ?? crypto.randomUUID();
18911
18965
  headers[IDEMPOTENCY_KEY_HEADER] = key;
18912
18966
  const { pausesMs, withinMs, silenceMs, inFlightPauseMs, inFlightWithinMs } = this.writeRetry;
18913
18967
  const pause = this.writeRetry.pause ?? pauseFor;
@@ -24355,6 +24409,41 @@ async function readCommand(context) {
24355
24409
  };
24356
24410
  }
24357
24411
 
24412
+ // ../envoy-client/src/dispatch-commands/reviews.ts
24413
+ async function reviewCommand(context) {
24414
+ const { args, client, documentOwner, resolveDocument } = context;
24415
+ const resolved = await resolveDocument(documentOwner(), optionalString(args, "artifact"));
24416
+ const { artifact } = resolved;
24417
+ let review;
24418
+ try {
24419
+ review = await client.reviewArtifact(artifact.id, numberArg(args, "version"), {
24420
+ state: stringArg(args, "verdict"),
24421
+ ...defined("reason", optionalString(args, "reason"))
24422
+ });
24423
+ } catch (error) {
24424
+ throw refusalWithCode(error);
24425
+ }
24426
+ const issue = resolved.issue?.key;
24427
+ const answered = review.ask_id === null ? [] : [
24428
+ `It also answered the open approval request (ask ${review.ask_id}), so Dispatch recorded the same verdict on every document that request named, each at the version the request named for it. Dispatch answered with the review of ${artifact.name} alone, so no other document's review is shown here; ${commandLine("dispatch_doc_read", { issue })} --artifact <document> prints the approval each of them now reads.`
24429
+ ];
24430
+ return {
24431
+ text: [
24432
+ `Recorded the review of ${artifact.name} (document id ${artifact.id}): ${review.state} at version ${review.version}, by ${actorText(review.actor)}.`,
24433
+ ...review.reason === null ? [] : [`Reason: ${JSON.stringify(review.reason)}`],
24434
+ ...answered
24435
+ ].join(`
24436
+ `),
24437
+ details: {
24438
+ issue,
24439
+ artifact: artifact.id,
24440
+ version: review.version,
24441
+ state: review.state,
24442
+ ...review.ask_id === null ? {} : { ask: review.ask_id }
24443
+ }
24444
+ };
24445
+ }
24446
+
24358
24447
  // ../envoy-client/src/session-answers.ts
24359
24448
  import { mkdirSync, readFileSync } from "fs";
24360
24449
  import { join as join2 } from "path";
@@ -24914,6 +25003,7 @@ var dispatchCommands = {
24914
25003
  dispatch_doc_read: acting(docReadCommand),
24915
25004
  dispatch_request_approval: acting(requestApprovalCommand),
24916
25005
  dispatch_plan_approve: acting(planApproveCommand),
25006
+ dispatch_review: acting(reviewCommand),
24917
25007
  dispatch_result: acting(resultCommand),
24918
25008
  dispatch_results: acting(resultsCommand),
24919
25009
  dispatch_artifact: acting(artifactCommand),
@@ -25446,6 +25536,9 @@ function fileBearer(bearer, url, section, env, commands = "run") {
25446
25536
  return fileValue(bearer.token, bearer.field, bearer.path, env, commands);
25447
25537
  }
25448
25538
 
25539
+ // ../broker-client/src/dpop.ts
25540
+ import { createPrivateKey, createPublicKey } from "crypto";
25541
+
25449
25542
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
25450
25543
  var encoder2 = new TextEncoder;
25451
25544
  var decoder = new TextDecoder;
@@ -26292,6 +26385,112 @@ function keyAlgorithm(alg, source) {
26292
26385
  return (typeof alg === "string" ? JWS[alg] ?? JWE[alg] : undefined) ?? unsupportedAlg(source);
26293
26386
  }
26294
26387
 
26388
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/asn1.js
26389
+ var bytesEqual = (a, b) => {
26390
+ if (a.byteLength !== b.length)
26391
+ return false;
26392
+ for (let i = 0;i < a.byteLength; i++) {
26393
+ if (a[i] !== b[i])
26394
+ return false;
26395
+ }
26396
+ return true;
26397
+ };
26398
+ var createASN1State = (data) => ({ data, pos: 0 });
26399
+ var readByte = (state) => {
26400
+ const byte = state.data[state.pos++];
26401
+ if (byte === undefined) {
26402
+ throw new Error("Unexpected end of ASN.1 input");
26403
+ }
26404
+ return byte;
26405
+ };
26406
+ var parseLength = (state) => {
26407
+ const first = readByte(state);
26408
+ if (first & 128) {
26409
+ const lengthOfLen = first & 127;
26410
+ let length = 0;
26411
+ for (let i = 0;i < lengthOfLen; i++) {
26412
+ length = length << 8 | readByte(state);
26413
+ }
26414
+ return length;
26415
+ }
26416
+ return first;
26417
+ };
26418
+ var expectTag = (state, expectedTag, errorMessage) => {
26419
+ if (readByte(state) !== expectedTag) {
26420
+ throw new Error(errorMessage);
26421
+ }
26422
+ };
26423
+ var getSubarray = (state, length) => {
26424
+ if (length < 0 || state.pos + length > state.data.length) {
26425
+ throw new Error("Unexpected end of ASN.1 input");
26426
+ }
26427
+ const result = state.data.subarray(state.pos, state.pos + length);
26428
+ state.pos += length;
26429
+ return result;
26430
+ };
26431
+ var parseAlgorithmOID = (state) => {
26432
+ expectTag(state, 6, "Expected algorithm OID");
26433
+ const oidLen = parseLength(state);
26434
+ return getSubarray(state, oidLen);
26435
+ };
26436
+ function parseKeyHeader(state, keyFormat) {
26437
+ expectTag(state, 48, `Invalid ${keyFormat === "spki" ? "SPKI" : "PKCS#8"} structure`);
26438
+ parseLength(state);
26439
+ if (keyFormat === "pkcs8") {
26440
+ expectTag(state, 2, "Expected version field");
26441
+ const length = parseLength(state);
26442
+ state.pos += length;
26443
+ }
26444
+ expectTag(state, 48, "Expected algorithm identifier");
26445
+ parseLength(state);
26446
+ }
26447
+ var parseECAlgorithmIdentifier = (state) => {
26448
+ const algOid = parseAlgorithmOID(state);
26449
+ if (bytesEqual(algOid, [43, 101, 110])) {
26450
+ return "X25519";
26451
+ }
26452
+ if (!bytesEqual(algOid, [42, 134, 72, 206, 61, 2, 1])) {
26453
+ throw new Error("Unsupported key algorithm");
26454
+ }
26455
+ expectTag(state, 6, "Expected curve OID");
26456
+ const curveOidLen = parseLength(state);
26457
+ const curveOid = getSubarray(state, curveOidLen);
26458
+ if (bytesEqual(curveOid, [42, 134, 72, 206, 61, 3, 1, 7]))
26459
+ return "P-256";
26460
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 34]))
26461
+ return "P-384";
26462
+ if (bytesEqual(curveOid, [43, 129, 4, 0, 35]))
26463
+ return "P-521";
26464
+ throw new Error("Unsupported named curve");
26465
+ };
26466
+ var genericImport = async (keyFormat, keyData, alg, options) => {
26467
+ const entry = keyAlgorithm(alg, algArgument);
26468
+ if (entry.secret) {
26469
+ unsupportedAlg(algArgument);
26470
+ }
26471
+ const isPublic = keyFormat === "spki";
26472
+ let algorithm;
26473
+ if (entry.resolve) {
26474
+ try {
26475
+ const state = createASN1State(keyData);
26476
+ parseKeyHeader(state, keyFormat);
26477
+ algorithm = entry.resolve({ crv: parseECAlgorithmIdentifier(state) });
26478
+ } catch {
26479
+ throw new JOSENotSupported("Invalid or unsupported key format");
26480
+ }
26481
+ } else {
26482
+ algorithm = entry.subtle;
26483
+ }
26484
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);
26485
+ };
26486
+ var processPEMData = (pem, pattern) => {
26487
+ return decodeBase64(pem.replace(pattern, ""));
26488
+ };
26489
+ var fromPKCS8 = (pem, alg, options) => {
26490
+ const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g);
26491
+ return genericImport("pkcs8", keyData, alg, options);
26492
+ };
26493
+
26295
26494
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
26296
26495
  function omitUndefinedProperties(jwk) {
26297
26496
  return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
@@ -26325,6 +26524,13 @@ async function keyToJWK(key) {
26325
26524
  function exportJWK(key) {
26326
26525
  return keyToJWK(key);
26327
26526
  }
26527
+ // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/import.js
26528
+ async function importPKCS8(pkcs8, alg, options) {
26529
+ if (typeof pkcs8 !== "string" || pkcs8.indexOf("-----BEGIN PRIVATE KEY-----") !== 0) {
26530
+ throw new TypeError('"pkcs8" must be PKCS#8 formatted string');
26531
+ }
26532
+ return fromPKCS8(pkcs8, alg, options);
26533
+ }
26328
26534
  // ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/generate_key_pair.js
26329
26535
  function getModulusLengthOption(options) {
26330
26536
  const modulusLength = options?.modulusLength ?? 2048;
@@ -26368,6 +26574,11 @@ async function generateKeyPair(alg, options) {
26368
26574
  ...entry.usages[0]
26369
26575
  ]);
26370
26576
  }
26577
+ // ../broker-client/src/error-text.ts
26578
+ function messageOf(error) {
26579
+ return error instanceof Error ? error.message : String(error);
26580
+ }
26581
+
26371
26582
  // ../broker-client/src/dpop.ts
26372
26583
  var ALGORITHM = "ES256";
26373
26584
  function targetUri(url) {
@@ -26380,9 +26591,7 @@ async function accessTokenHash(accessToken) {
26380
26591
  const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(accessToken));
26381
26592
  return Buffer.from(digest).toString("base64url");
26382
26593
  }
26383
- async function newDpopKey() {
26384
- const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
26385
- const publicJwk = await exportJWK(publicKey);
26594
+ function dpopKey(privateKey, publicJwk) {
26386
26595
  return {
26387
26596
  publicJwk,
26388
26597
  async proof(request) {
@@ -26401,6 +26610,30 @@ async function newDpopKey() {
26401
26610
  }
26402
26611
  };
26403
26612
  }
26613
+ async function newDpopKey() {
26614
+ const { privateKey, publicKey } = await generateKeyPair(ALGORITHM, { extractable: false });
26615
+ return dpopKey(privateKey, await exportJWK(publicKey));
26616
+ }
26617
+ async function importDpopKey(pkcs8Pem, name) {
26618
+ const unreadable = (error) => new Error(`read ${name}: ${messageOf(error)}`, { cause: error });
26619
+ let exported;
26620
+ try {
26621
+ exported = createPublicKey(createPrivateKey(pkcs8Pem)).export({ format: "jwk" });
26622
+ } catch (error) {
26623
+ throw unreadable(error);
26624
+ }
26625
+ const { kty, crv, x, y } = exported;
26626
+ if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
26627
+ throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
26628
+ }
26629
+ let privateKey;
26630
+ try {
26631
+ privateKey = await importPKCS8(pkcs8Pem, ALGORITHM, { extractable: false });
26632
+ } catch (error) {
26633
+ throw unreadable(error);
26634
+ }
26635
+ return dpopKey(privateKey, { kty, crv, x, y });
26636
+ }
26404
26637
 
26405
26638
  // ../broker-client/src/metadata-identity.ts
26406
26639
  import { Agent, request } from "http";
@@ -26414,6 +26647,7 @@ var FORM_LAUNCHER_CREDENTIAL = "launcher_credential";
26414
26647
  var FORM_LAUNCHER_CREDENTIAL_DECLINED = "false";
26415
26648
  var SUBJECT_TOKEN_TYPE_KUBERNETES = "urn:envoy:params:oauth:token-type:kubernetes-service-account";
26416
26649
  var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identity";
26650
+ var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
26417
26651
  var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
26418
26652
  var TOKEN_TYPE_DPOP = "DPoP";
26419
26653
 
@@ -26475,29 +26709,6 @@ function metadataIdentity(audience, env = process.env) {
26475
26709
  };
26476
26710
  }
26477
26711
 
26478
- // ../broker-client/src/projected-token.ts
26479
- import { readFile } from "fs/promises";
26480
- function projectedToken(path) {
26481
- return {
26482
- async read(signal) {
26483
- let contents;
26484
- try {
26485
- contents = await readFile(path, {
26486
- encoding: "utf8",
26487
- ...signal === undefined ? {} : { signal }
26488
- });
26489
- } catch (error) {
26490
- throw new Error(`read the projected service-account token ${path}: ${error.message}`);
26491
- }
26492
- const token = contents.trim();
26493
- if (token === "")
26494
- throw new Error(`the projected service-account token ${path} is empty`);
26495
- return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
26496
- },
26497
- describe: () => `the projected service-account token ${path}`
26498
- };
26499
- }
26500
-
26501
26712
  // ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
26502
26713
  var USER_AGENT;
26503
26714
  if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
@@ -26643,6 +26854,56 @@ function signal(url, value) {
26643
26854
  }
26644
26855
  return;
26645
26856
  }
26857
+ function replaceDoubleSlash(pathname) {
26858
+ if (pathname.includes("//")) {
26859
+ return pathname.replace("//", "/");
26860
+ }
26861
+ return pathname;
26862
+ }
26863
+ function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
26864
+ if (url.pathname === "/") {
26865
+ url.pathname = wellKnown;
26866
+ } else {
26867
+ url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")}`);
26868
+ }
26869
+ return url;
26870
+ }
26871
+ function appendWellKnown(url, wellKnown) {
26872
+ url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
26873
+ return url;
26874
+ }
26875
+ async function performDiscovery(input, urlName, transform, options) {
26876
+ if (!(input instanceof URL)) {
26877
+ throw CodedTypeError(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE);
26878
+ }
26879
+ checkProtocol(input, options?.[allowInsecureRequests] !== true);
26880
+ const url = transform(new URL(input.href));
26881
+ const headers = prepareHeaders(options?.headers);
26882
+ headers.set("accept", "application/json");
26883
+ return (options?.[customFetch] || fetch)(url.href, {
26884
+ body: undefined,
26885
+ headers: Object.fromEntries(headers.entries()),
26886
+ method: "GET",
26887
+ redirect: "manual",
26888
+ signal: signal(url, options?.signal)
26889
+ });
26890
+ }
26891
+ async function discoveryRequest(issuerIdentifier, options) {
26892
+ return performDiscovery(issuerIdentifier, "issuerIdentifier", (url) => {
26893
+ switch (options?.algorithm) {
26894
+ case undefined:
26895
+ case "oidc":
26896
+ appendWellKnown(url, ".well-known/openid-configuration");
26897
+ break;
26898
+ case "oauth2":
26899
+ prependWellKnown(url, ".well-known/oauth-authorization-server");
26900
+ break;
26901
+ default:
26902
+ throw CodedTypeError('"options.algorithm" must be "oidc" (default), or "oauth2"', ERR_INVALID_ARG_VALUE);
26903
+ }
26904
+ return url;
26905
+ }, options);
26906
+ }
26646
26907
  function assertNumber(input, allow0, it, code, cause) {
26647
26908
  try {
26648
26909
  if (typeof input !== "number" || !Number.isFinite(input)) {
@@ -26679,6 +26940,25 @@ function assertString(input, it, code, cause) {
26679
26940
  throw err;
26680
26941
  }
26681
26942
  }
26943
+ async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
26944
+ const expected = expectedIssuerIdentifier;
26945
+ if (!(expected instanceof URL) && expected !== _nodiscoverycheck) {
26946
+ throw CodedTypeError('"expectedIssuerIdentifier" must be an instance of URL', ERR_INVALID_ARG_TYPE);
26947
+ }
26948
+ if (!looseInstanceOf(response, Response)) {
26949
+ throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
26950
+ }
26951
+ if (response.status !== 200) {
26952
+ throw OPE('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)', RESPONSE_IS_NOT_CONFORM, response);
26953
+ }
26954
+ assertReadableResponse(response);
26955
+ const json = await getResponseJsonBody(response);
26956
+ assertString(json.issuer, '"response" body "issuer" property', INVALID_RESPONSE, { body: json });
26957
+ if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) {
26958
+ throw OPE('"response" body "issuer" property does not match the expected value', JSON_ATTRIBUTE_COMPARISON, { expected: expected.href, body: json, attribute: "issuer" });
26959
+ }
26960
+ return json;
26961
+ }
26682
26962
  function assertApplicationJson(response) {
26683
26963
  assertContentType(response, "application/json");
26684
26964
  }
@@ -26958,6 +27238,14 @@ async function tokenEndpointRequest(as, client, clientAuthentication, grantType,
26958
27238
  options?.DPoP?.cacheNonce(response, url);
26959
27239
  return response;
26960
27240
  }
27241
+ async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
27242
+ assertAs(as);
27243
+ assertClient(client);
27244
+ assertString(refreshToken, '"refreshToken"');
27245
+ const parameters = new URLSearchParams(options?.additionalParameters);
27246
+ parameters.set("refresh_token", refreshToken);
27247
+ return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
27248
+ }
26961
27249
  var idTokenClaims = new WeakMap;
26962
27250
  var jwtRefs = new WeakMap;
26963
27251
  function getValidatedIdTokenClaims(ref) {
@@ -27035,6 +27323,9 @@ function checkAuthenticationChallenges(response) {
27035
27323
  throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", { cause: challenges, response });
27036
27324
  }
27037
27325
  }
27326
+ async function processRefreshTokenResponse(as, client, response, options) {
27327
+ return processGenericAccessTokenResponse(as, client, response, undefined, options?.[jweDecrypt], options?.recognizedTokenTypes);
27328
+ }
27038
27329
  function validateAudience(expected, result) {
27039
27330
  if (Array.isArray(result.claims.aud)) {
27040
27331
  if (!result.claims.aud.includes(expected)) {
@@ -27387,6 +27678,73 @@ function errorHandler(err) {
27387
27678
  }
27388
27679
  throw new ClientError("something went wrong", { cause: err });
27389
27680
  }
27681
+ function handleEntraId(server, as, options) {
27682
+ if (server.origin === "https://login.microsoftonline.com" && (!options?.algorithm || options.algorithm === "oidc")) {
27683
+ as[kEntraId] = true;
27684
+ return true;
27685
+ }
27686
+ return false;
27687
+ }
27688
+ function handleB2Clogin(server, options) {
27689
+ if (server.hostname.endsWith(".b2clogin.com") && (!options?.algorithm || options.algorithm === "oidc")) {
27690
+ return true;
27691
+ }
27692
+ return false;
27693
+ }
27694
+ async function discovery(server, clientId, metadata, clientAuthentication, options) {
27695
+ const as = await performDiscovery2(server, options);
27696
+ const instance = new Configuration(as, clientId, metadata, clientAuthentication);
27697
+ let internals = int2(instance);
27698
+ if (options?.[customFetch2]) {
27699
+ internals.fetch = options[customFetch2];
27700
+ }
27701
+ if (options?.timeout) {
27702
+ internals.timeout = options.timeout;
27703
+ }
27704
+ if (options?.execute) {
27705
+ for (const extension of options.execute) {
27706
+ extension(instance);
27707
+ }
27708
+ }
27709
+ return instance;
27710
+ }
27711
+ async function performDiscovery2(server, options) {
27712
+ if (!(server instanceof URL)) {
27713
+ throw CodedTypeError2('"server" must be an instance of URL', ERR_INVALID_ARG_TYPE2);
27714
+ }
27715
+ const resolve = !server.href.includes("/.well-known/");
27716
+ const timeout = options?.timeout ?? 30;
27717
+ const signal = AbortSignal.timeout(timeout * 1000);
27718
+ const as = await (resolve ? discoveryRequest(server, {
27719
+ algorithm: options?.algorithm,
27720
+ [customFetch]: options?.[customFetch2],
27721
+ [allowInsecureRequests]: options?.execute?.includes(allowInsecureRequests2),
27722
+ signal,
27723
+ headers: new Headers(headers)
27724
+ }) : (options?.[customFetch2] || fetch)((() => {
27725
+ checkProtocol(server, options?.execute?.includes(allowInsecureRequests2) ? false : true);
27726
+ return server.href;
27727
+ })(), {
27728
+ headers: Object.fromEntries(new Headers({ accept: "application/json", ...headers }).entries()),
27729
+ body: undefined,
27730
+ method: "GET",
27731
+ redirect: "manual",
27732
+ signal
27733
+ })).then((response) => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
27734
+ if (resolve && new URL(as.issuer).href !== server.href) {
27735
+ handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
27736
+ throw new ClientError("discovered metadata issuer does not match the expected issuer", {
27737
+ code: JSON_ATTRIBUTE_COMPARISON,
27738
+ cause: {
27739
+ expected: server.href,
27740
+ body: as,
27741
+ attribute: "issuer"
27742
+ }
27743
+ });
27744
+ })();
27745
+ }
27746
+ return as;
27747
+ }
27390
27748
  function getServerHelpers(metadata) {
27391
27749
  return {
27392
27750
  supportsPKCE: {
@@ -27503,6 +27861,37 @@ function addHelpers(response) {
27503
27861
  function allowInsecureRequests2(config) {
27504
27862
  int2(config).tlsOnly = false;
27505
27863
  }
27864
+ async function refreshTokenGrant(config, refreshToken, parameters, options) {
27865
+ checkConfig(config);
27866
+ parameters = new URLSearchParams(parameters);
27867
+ const { as, c, auth, fetch: fetch2, tlsOnly, nonRepudiation, timeout, decrypt } = int2(config);
27868
+ const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
27869
+ [customFetch]: fetch2,
27870
+ [allowInsecureRequests]: !tlsOnly,
27871
+ additionalParameters: parameters,
27872
+ DPoP: options?.DPoP,
27873
+ headers: new Headers(headers),
27874
+ signal: signal2(timeout)
27875
+ }).catch(errorHandler);
27876
+ const p = processRefreshTokenResponse(as, c, response, {
27877
+ [jweDecrypt]: decrypt
27878
+ });
27879
+ let result;
27880
+ try {
27881
+ result = await p;
27882
+ } catch (err) {
27883
+ if (retryable(err, options)) {
27884
+ return refreshTokenGrant(config, refreshToken, parameters, {
27885
+ ...options,
27886
+ flag: retry
27887
+ });
27888
+ }
27889
+ errorHandler(err);
27890
+ }
27891
+ result.id_token && await nonRepudiation?.(response);
27892
+ addHelpers(result);
27893
+ return result;
27894
+ }
27506
27895
  function checkConfig(input) {
27507
27896
  if (!(input instanceof Configuration)) {
27508
27897
  throw CodedTypeError2('"config" must be an instance of Configuration', ERR_INVALID_ARG_TYPE2);
@@ -27556,6 +27945,136 @@ async function genericGrantRequest(config, grantType, parameters, options) {
27556
27945
  return result;
27557
27946
  }
27558
27947
 
27948
+ // ../broker-client/src/signins.ts
27949
+ import { readdir, readFile } from "fs/promises";
27950
+ import { join as join5 } from "path";
27951
+ var SIGNIN_DIR_VAR = "AGENT_SECRETS_SIGNIN_DIR";
27952
+ var PERSON_VAR = "AGENT_SECRETS_PERSON";
27953
+ var PERSON_TRADE_VAR = "PERSON_SIGNIN_TRADE";
27954
+ var SIGNIN_ISSUER_VAR = "AGENT_SECRETS_SIGNIN_ISSUER";
27955
+ var SIGNIN_CLIENT_ID_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_ID";
27956
+ var SIGNIN_CLIENT_SECRET_FILE_VAR = "AGENT_SECRETS_SIGNIN_CLIENT_SECRET_FILE";
27957
+ var DEFAULT_SIGNIN_ISSUER = "https://accounts.google.com";
27958
+ var SIGNIN_COMMAND = "agent-secrets login";
27959
+ var SIGNINS_DIR = "signins";
27960
+ var RECORD_MEMBERS = [
27961
+ "person",
27962
+ "issuer",
27963
+ "client_id",
27964
+ "refresh_token",
27965
+ "box_key",
27966
+ "thumbprint",
27967
+ "enrollment_id",
27968
+ "signed_in_at"
27969
+ ];
27970
+ function signInDirectory(env) {
27971
+ const named = env[SIGNIN_DIR_VAR] ?? "";
27972
+ if (named !== "")
27973
+ return named;
27974
+ const state = env.XDG_STATE_HOME ?? "";
27975
+ const base = state !== "" ? state : join5(env.HOME ?? "", ".local", "state");
27976
+ return join5(base, "agent-secrets", SIGNINS_DIR);
27977
+ }
27978
+ async function readSignIn(path) {
27979
+ let text;
27980
+ try {
27981
+ text = await readFile(path, "utf8");
27982
+ } catch (error) {
27983
+ throw new Error(`read the sign-in at ${path}: ${messageOf(error)}`, { cause: error });
27984
+ }
27985
+ let parsed;
27986
+ try {
27987
+ parsed = JSON.parse(text);
27988
+ } catch {
27989
+ throw new Error(`read the sign-in at ${path}: it is not JSON; run: ${SIGNIN_COMMAND}`);
27990
+ }
27991
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
27992
+ throw new Error(`read the sign-in at ${path}: it holds no JSON object; run: ${SIGNIN_COMMAND}`);
27993
+ }
27994
+ const fields = parsed;
27995
+ const record = {};
27996
+ for (const member of RECORD_MEMBERS) {
27997
+ const given = fields[member] ?? "";
27998
+ if (typeof given !== "string") {
27999
+ throw new Error(`read the sign-in at ${path}: its ${member} is not a string; run: ${SIGNIN_COMMAND}`);
28000
+ }
28001
+ record[member] = given;
28002
+ }
28003
+ const read = record;
28004
+ if (read.person === "" || read.refresh_token === "" || read.box_key === "") {
28005
+ throw new Error(`the sign-in at ${path} names no person, no refresh token or no box key; run: ${SIGNIN_COMMAND}`);
28006
+ }
28007
+ return read;
28008
+ }
28009
+ async function listSignIns(dir) {
28010
+ let entries;
28011
+ try {
28012
+ entries = await readdir(dir, { withFileTypes: true });
28013
+ } catch (error) {
28014
+ if (error.code === "ENOENT")
28015
+ return [];
28016
+ throw new Error(`read this machine's sign-ins: ${messageOf(error)}`, { cause: error });
28017
+ }
28018
+ const names = entries.filter((entry) => !entry.isDirectory() && entry.name.endsWith(".json")).map((entry) => entry.name).sort();
28019
+ const records = [];
28020
+ for (const name of names)
28021
+ records.push(await readSignIn(join5(dir, name)));
28022
+ return records.sort((a, b) => a.person < b.person ? -1 : a.person > b.person ? 1 : 0);
28023
+ }
28024
+ function namesOf(records) {
28025
+ return records.map((record) => record.person).join(", ");
28026
+ }
28027
+ function personTradeOff(env) {
28028
+ const written = (env[PERSON_TRADE_VAR] ?? "").trim();
28029
+ if (written === "")
28030
+ return false;
28031
+ if (written === "off")
28032
+ return true;
28033
+ throw new Error(`${PERSON_TRADE_VAR} is "${written}" and takes off or nothing: set it to off where this process's own credentials trade this machine and never a person signed in on it, and leave it unset where they trade the person signed in here`);
28034
+ }
28035
+ async function chooseSignIn(env) {
28036
+ if (personTradeOff(env))
28037
+ return;
28038
+ const records = await listSignIns(signInDirectory(env));
28039
+ const person = (env[PERSON_VAR] ?? "").trim().toLowerCase();
28040
+ if (records.length === 0)
28041
+ return;
28042
+ if (person !== "") {
28043
+ const named = records.find((record) => record.person.toLowerCase() === person);
28044
+ if (named !== undefined)
28045
+ return named;
28046
+ throw new Error(`${PERSON_VAR} names ${person}, who is not signed in on this machine; signed in here: ${namesOf(records)}; run: ${SIGNIN_COMMAND}`);
28047
+ }
28048
+ if (records.length === 1)
28049
+ return records[0];
28050
+ throw new Error(`${records.length} people are signed in on this machine (${namesOf(records)}), so this session must say which one it acts for: set ${PERSON_VAR} to one of them`);
28051
+ }
28052
+ function signInSessionName(record) {
28053
+ const name = `signin-${record.person}`;
28054
+ return record.thumbprint === "" ? name : `${name}-${record.thumbprint.slice(0, 12)}`;
28055
+ }
28056
+ async function signInFlow(env) {
28057
+ const clientId = (env[SIGNIN_CLIENT_ID_VAR] ?? "").trim();
28058
+ const secretFile = (env[SIGNIN_CLIENT_SECRET_FILE_VAR] ?? "").trim();
28059
+ if (clientId === "" && secretFile === "")
28060
+ return;
28061
+ if (clientId === "" || secretFile === "") {
28062
+ throw new Error(`a person's sign-in needs both ${SIGNIN_CLIENT_ID_VAR} and ${SIGNIN_CLIENT_SECRET_FILE_VAR}; this machine has one of them`);
28063
+ }
28064
+ let secret;
28065
+ try {
28066
+ secret = await readFile(secretFile, "utf8");
28067
+ } catch (error) {
28068
+ throw new Error(`read the sign-in client's secret (${SIGNIN_CLIENT_SECRET_FILE_VAR}): ${messageOf(error)}`, { cause: error });
28069
+ }
28070
+ const issuer = (env[SIGNIN_ISSUER_VAR] ?? "").trim();
28071
+ return {
28072
+ issuer: withoutTrailingSlashes(issuer === "" ? DEFAULT_SIGNIN_ISSUER : issuer),
28073
+ clientId,
28074
+ clientSecret: secret.trim()
28075
+ };
28076
+ }
28077
+
27559
28078
  // ../broker-client/src/token-client.ts
27560
28079
  var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
27561
28080
  var TOO_MANY_REQUESTS = 429;
@@ -27566,8 +28085,8 @@ class BrokerRefusedError extends Error {
27566
28085
  status;
27567
28086
  code;
27568
28087
  description;
27569
- constructor(status, code, description) {
27570
- super(description === "" ? `the secrets broker refused this machine's identity: HTTP ${status} ${code}` : `the secrets broker refused this machine's identity: HTTP ${status} ${code}: ${description}`);
28088
+ constructor(status, code, description, refused) {
28089
+ super(description === "" ? `the secrets broker refused ${refused}: HTTP ${status} ${code}` : `the secrets broker refused ${refused}: HTTP ${status} ${code}: ${description}`);
27571
28090
  this.status = status;
27572
28091
  this.code = code;
27573
28092
  this.description = description;
@@ -27577,6 +28096,20 @@ class BrokerRefusedError extends Error {
27577
28096
  return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE;
27578
28097
  }
27579
28098
  }
28099
+
28100
+ class SignInEndedError extends Error {
28101
+ issuer;
28102
+ person;
28103
+ constructor(issuer, person, options) {
28104
+ super(`${issuer} no longer honours ${person}'s sign-in on this machine; run: ${SIGNIN_COMMAND}`, options);
28105
+ this.issuer = issuer;
28106
+ this.person = person;
28107
+ this.name = "SignInEndedError";
28108
+ }
28109
+ }
28110
+ function isFinalRefusal(error) {
28111
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError;
28112
+ }
27580
28113
  function statusOf(error) {
27581
28114
  let cause = error;
27582
28115
  for (let depth = 0;depth < 4; depth += 1) {
@@ -27588,6 +28121,16 @@ function statusOf(error) {
27588
28121
  }
27589
28122
  return 0;
27590
28123
  }
28124
+ function requestInit(options, signal, headers) {
28125
+ const signals = [options.signal, signal].filter((one) => one !== undefined);
28126
+ return {
28127
+ method: options.method,
28128
+ headers,
28129
+ body: options.body,
28130
+ redirect: options.redirect,
28131
+ ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
28132
+ };
28133
+ }
27591
28134
 
27592
28135
  class BrokerTokenClient {
27593
28136
  #brokerUrl;
@@ -27636,6 +28179,9 @@ class BrokerTokenClient {
27636
28179
  this.#trading = null;
27637
28180
  }
27638
28181
  }
28182
+ drop() {
28183
+ this.#held = null;
28184
+ }
27639
28185
  async#renew(signal) {
27640
28186
  try {
27641
28187
  const token = await this.#trade(signal);
@@ -27643,7 +28189,7 @@ class BrokerTokenClient {
27643
28189
  return token;
27644
28190
  } catch (error) {
27645
28191
  const held = this.#held;
27646
- if (!(error instanceof BrokerRefusedError && error.permanent) && held !== null && this.#now() < held.expiresAt.getTime()) {
28192
+ if (!isFinalRefusal(error) && held !== null && this.#now() < held.expiresAt.getTime()) {
27647
28193
  return held;
27648
28194
  }
27649
28195
  this.#held = null;
@@ -27666,8 +28212,9 @@ class BrokerTokenClient {
27666
28212
  try {
27667
28213
  actor = await this.#actor.read(signal);
27668
28214
  } catch (error) {
27669
- const said = error instanceof Error ? error.message : String(error);
27670
- throw new Error(`read the machine this person signed in on: ${said}`, { cause: error });
28215
+ throw new Error(`read the machine this person signed in on: ${messageOf(error)}`, {
28216
+ cause: error
28217
+ });
27671
28218
  }
27672
28219
  form["actor_token"] = actor.token;
27673
28220
  form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
@@ -27687,10 +28234,10 @@ class BrokerTokenClient {
27687
28234
  }
27688
28235
  #refusal(endpoint, error) {
27689
28236
  if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
27690
- return new BrokerRefusedError(error.status, error.error, error.error_description ?? "");
28237
+ return new BrokerRefusedError(error.status, error.error, error.error_description ?? "", this.#subject.describe());
27691
28238
  }
27692
28239
  const status = statusOf(error);
27693
- const message = error instanceof Error ? error.message : String(error);
28240
+ const message = messageOf(error);
27694
28241
  const said = status === 0 ? message : `HTTP ${status}: ${message}`;
27695
28242
  return new Error(`trade ${this.#subject.describe()} at ${endpoint}: ${said}`, {
27696
28243
  cause: error
@@ -27700,15 +28247,7 @@ class BrokerTokenClient {
27700
28247
  const send = async () => {
27701
28248
  const headers = new Headers(options.headers);
27702
28249
  headers.set("DPoP", await this.#key.proof({ method: options.method, url, nonce: this.#nonce }));
27703
- const signals = [options.signal, signal].filter((one) => one !== undefined);
27704
- const body = options.body;
27705
- return await this.#fetch(url, {
27706
- method: options.method,
27707
- headers,
27708
- body,
27709
- redirect: options.redirect,
27710
- ...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
27711
- });
28250
+ return await this.#fetch(url, requestInit(options, signal, headers));
27712
28251
  };
27713
28252
  let answer = await send();
27714
28253
  const given = answer.headers.get("DPoP-Nonce") ?? "";
@@ -27756,15 +28295,241 @@ class BrokerTokenClient {
27756
28295
  }
27757
28296
  }
27758
28297
 
28298
+ // ../broker-client/src/person-identity.ts
28299
+ var ISSUER_TIMEOUT_SECONDS = 30;
28300
+ var INVALID_GRANT = "invalid_grant";
28301
+ function issuerSaid(error) {
28302
+ if (error instanceof ResponseBodyError) {
28303
+ const description = error.error_description ?? "";
28304
+ return `HTTP ${error.status} ${error.error}${description === "" ? "" : `: ${description}`}`;
28305
+ }
28306
+ let message = messageOf(error);
28307
+ const cause = error instanceof Error ? error.cause : undefined;
28308
+ if (cause instanceof Error && cause.message !== message)
28309
+ message += `: ${cause.message}`;
28310
+ const status = statusOf(error);
28311
+ return status === 0 ? message : `HTTP ${status}: ${message}`;
28312
+ }
28313
+ function personIdentity(record, flow, options = {}) {
28314
+ const { person, refresh_token: refreshToken, client_id: clientId } = record;
28315
+ if (clientId !== "" && clientId !== flow.clientId) {
28316
+ throw new Error(`${person} signed in with another client than this machine now has (${clientId}), so their sign-in cannot be renewed; run: ${SIGNIN_COMMAND}`);
28317
+ }
28318
+ const send = options.fetch ?? fetch;
28319
+ const insecure = flow.issuer.startsWith("http:");
28320
+ let discovered = null;
28321
+ const through = (signal) => (url, init) => send(url, requestInit(init, signal, init.headers));
28322
+ const discover = async (signal) => {
28323
+ try {
28324
+ const config = await discovery(new URL(flow.issuer), flow.clientId, undefined, undefined, {
28325
+ [customFetch2]: through(signal),
28326
+ timeout: ISSUER_TIMEOUT_SECONDS,
28327
+ ...insecure ? { execute: [allowInsecureRequests2] } : {}
28328
+ });
28329
+ return config.serverMetadata();
28330
+ } catch (error) {
28331
+ throw new Error(`read the sign-in issuer ${flow.issuer}: ${issuerSaid(error)}`, {
28332
+ cause: error
28333
+ });
28334
+ }
28335
+ };
28336
+ return {
28337
+ async read(signal) {
28338
+ discovered ??= discover(signal);
28339
+ const discovering = discovered;
28340
+ let metadata;
28341
+ try {
28342
+ metadata = await discovering;
28343
+ } catch (error) {
28344
+ if (discovered === discovering)
28345
+ discovered = null;
28346
+ throw error;
28347
+ }
28348
+ let answered;
28349
+ try {
28350
+ const config = new Configuration(metadata, flow.clientId, undefined, ClientSecretPost2(flow.clientSecret));
28351
+ if (insecure)
28352
+ allowInsecureRequests2(config);
28353
+ config.timeout = ISSUER_TIMEOUT_SECONDS;
28354
+ config[customFetch2] = through(signal);
28355
+ answered = await refreshTokenGrant(config, refreshToken);
28356
+ } catch (error) {
28357
+ if (error instanceof ResponseBodyError && error.error === INVALID_GRANT) {
28358
+ throw new SignInEndedError(flow.issuer, person, { cause: error });
28359
+ }
28360
+ throw new Error(`renew ${person}'s sign-in at ${flow.issuer}: ${issuerSaid(error)}`);
28361
+ }
28362
+ const idToken = answered.id_token ?? "";
28363
+ if (idToken === "") {
28364
+ throw new Error(`${flow.issuer} answered no id_token: the sign-in asked for the "openid" scope and must be answered one`);
28365
+ }
28366
+ return { token: idToken, tokenType: SUBJECT_TOKEN_TYPE_PERSON };
28367
+ },
28368
+ describe: () => `${person}'s sign-in on this machine`
28369
+ };
28370
+ }
28371
+
28372
+ // ../broker-client/src/pool-identity.ts
28373
+ var DEFAULT_SECURITY_TOKEN_SERVICE_URL = "https://sts.googleapis.com/v1/token";
28374
+ var DEFAULT_IAM_CREDENTIALS_URL = "https://iamcredentials.googleapis.com";
28375
+ var REQUESTED_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
28376
+ var SCOPE = "https://www.googleapis.com/auth/cloud-platform";
28377
+ var SUBJECT_TOKEN_TYPE_JWT = "urn:ietf:params:oauth:token-type:jwt";
28378
+ var POOL_TIMEOUT_MS = 20000;
28379
+ var MAX_ANSWER_BYTES2 = 1 << 20;
28380
+ function poolSubjectTokenType(brokerType) {
28381
+ return brokerType === SUBJECT_TOKEN_TYPE_KUBERNETES ? SUBJECT_TOKEN_TYPE_JWT : brokerType;
28382
+ }
28383
+ function pathEscape(segment) {
28384
+ return encodeURIComponent(segment).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(?:24|26|2B|3A|3D|40)/g, decodeURIComponent);
28385
+ }
28386
+ async function answerText(answer) {
28387
+ const reader = answer.body?.getReader();
28388
+ if (reader === undefined)
28389
+ return "";
28390
+ const chunks = [];
28391
+ let read = 0;
28392
+ while (read < MAX_ANSWER_BYTES2) {
28393
+ const { done, value } = await reader.read();
28394
+ if (done)
28395
+ break;
28396
+ const kept = value.subarray(0, MAX_ANSWER_BYTES2 - read);
28397
+ chunks.push(kept);
28398
+ read += kept.length;
28399
+ }
28400
+ await reader.cancel().catch(() => {
28401
+ return;
28402
+ });
28403
+ return Buffer.concat(chunks).toString("utf8");
28404
+ }
28405
+ function poolIdentity(options) {
28406
+ const securityTokenService = options.securityTokenServiceUrl ?? DEFAULT_SECURITY_TOKEN_SERVICE_URL;
28407
+ const iamCredentials = (options.iamCredentialsUrl ?? DEFAULT_IAM_CREDENTIALS_URL).replace(/\/$/, "");
28408
+ const account = pathEscape(options.serviceAccount);
28409
+ const mintEndpoint = `${iamCredentials}/v1/projects/-/serviceAccounts/${account}:generateIdToken`;
28410
+ const call = async (endpoint, bearer, body, member, signal) => {
28411
+ const signals = [AbortSignal.timeout(POOL_TIMEOUT_MS), signal].filter((one) => one !== undefined);
28412
+ const answer = await fetch(endpoint, {
28413
+ method: "POST",
28414
+ headers: {
28415
+ "Content-Type": "application/json",
28416
+ ...bearer === "" ? {} : { Authorization: `Bearer ${bearer}` }
28417
+ },
28418
+ body: JSON.stringify(body),
28419
+ signal: AbortSignal.any(signals)
28420
+ });
28421
+ const text = await answerText(answer);
28422
+ if (answer.status < 200 || answer.status > 299) {
28423
+ throw new Error(`HTTP ${answer.status}: ${text.trim()}`);
28424
+ }
28425
+ let parsed;
28426
+ try {
28427
+ parsed = JSON.parse(text);
28428
+ } catch {
28429
+ throw new Error(`HTTP ${answer.status}: the answer is not JSON`);
28430
+ }
28431
+ const value = typeof parsed === "object" && parsed !== null ? parsed[member] : undefined;
28432
+ return typeof value === "string" ? value : "";
28433
+ };
28434
+ const federate = async (subject, signal) => {
28435
+ let federated;
28436
+ try {
28437
+ federated = await call(securityTokenService, "", {
28438
+ audience: options.audience,
28439
+ grantType: GRANT_TYPE_TOKEN_EXCHANGE,
28440
+ requestedTokenType: REQUESTED_TOKEN_TYPE,
28441
+ scope: SCOPE,
28442
+ subjectTokenType: poolSubjectTokenType(subject.tokenType),
28443
+ subjectToken: subject.token
28444
+ }, "access_token", signal);
28445
+ } catch (error) {
28446
+ throw new Error(`trade this machine's credential at the security token service ${securityTokenService}: ${messageOf(error)}`, { cause: error });
28447
+ }
28448
+ if (federated === "") {
28449
+ throw new Error(`the security token service ${securityTokenService} answered no access_token`);
28450
+ }
28451
+ return federated;
28452
+ };
28453
+ const generateIdToken = async (federated, signal) => {
28454
+ let token;
28455
+ try {
28456
+ token = await call(mintEndpoint, federated, { audience: options.tokenAudience, includeEmail: true }, "token", signal);
28457
+ } catch (error) {
28458
+ throw new Error(`mint this machine's identity token at ${mintEndpoint}: ${messageOf(error)}`, { cause: error });
28459
+ }
28460
+ if (token === "")
28461
+ throw new Error(`generateIdToken at ${mintEndpoint} answered no token`);
28462
+ return token;
28463
+ };
28464
+ return {
28465
+ async read(signal) {
28466
+ let subject;
28467
+ try {
28468
+ subject = await options.subject.read(signal);
28469
+ } catch (error) {
28470
+ throw new Error(`read the credential the workload identity pool federates: ${messageOf(error)}`, { cause: error });
28471
+ }
28472
+ const federated = await federate(subject, signal);
28473
+ return {
28474
+ token: await generateIdToken(federated, signal),
28475
+ tokenType: SUBJECT_TOKEN_TYPE_GOOGLE
28476
+ };
28477
+ },
28478
+ describe: () => `a Google identity token for ${options.tokenAudience} minted through the workload identity pool ${options.audience} as ${options.serviceAccount}`
28479
+ };
28480
+ }
28481
+
28482
+ // ../broker-client/src/projected-token.ts
28483
+ import { readFile as readFile2 } from "fs/promises";
28484
+ function projectedToken(path) {
28485
+ return {
28486
+ async read(signal) {
28487
+ let contents;
28488
+ try {
28489
+ contents = await readFile2(path, {
28490
+ encoding: "utf8",
28491
+ ...signal === undefined ? {} : { signal }
28492
+ });
28493
+ } catch (error) {
28494
+ throw new Error(`read the projected service-account token ${path}: ${error.message}`);
28495
+ }
28496
+ const token = contents.trim();
28497
+ if (token === "")
28498
+ throw new Error(`the projected service-account token ${path} is empty`);
28499
+ return { token, tokenType: SUBJECT_TOKEN_TYPE_KUBERNETES };
28500
+ },
28501
+ describe: () => `the projected service-account token ${path}`
28502
+ };
28503
+ }
28504
+
27759
28505
  // ../broker-client/src/environment.ts
27760
28506
  var BROKER_URL_VAR = "AGENT_SECRETS_URL";
27761
28507
  var IDENTITY_VAR = "AGENT_SECRETS_MACHINE_IDENTITY";
27762
28508
  var MACHINE_TOKEN_FILE_VAR = "AGENT_SECRETS_MACHINE_TOKEN_FILE";
27763
28509
  var MACHINE_AUDIENCE_VAR = "AGENT_SECRETS_MACHINE_AUDIENCE";
27764
28510
  var SESSION_VAR = "AGENT_SECRETS_SESSION";
28511
+ var POOL_AUDIENCE_VAR = "AGENT_SECRETS_POOL_AUDIENCE";
28512
+ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
27765
28513
  var IDENTITY_KUBERNETES = "kubernetes";
27766
28514
  var IDENTITY_METADATA = "metadata";
27767
28515
  var IDENTITY_POOL = "pool";
28516
+ var BROKER_VARIABLES = [
28517
+ BROKER_URL_VAR,
28518
+ IDENTITY_VAR,
28519
+ MACHINE_TOKEN_FILE_VAR,
28520
+ MACHINE_AUDIENCE_VAR,
28521
+ SESSION_VAR,
28522
+ POOL_AUDIENCE_VAR,
28523
+ POOL_ACCOUNT_VAR,
28524
+ SIGNIN_DIR_VAR,
28525
+ "XDG_STATE_HOME",
28526
+ "HOME",
28527
+ PERSON_VAR,
28528
+ PERSON_TRADE_VAR,
28529
+ SIGNIN_ISSUER_VAR,
28530
+ SIGNIN_CLIENT_ID_VAR,
28531
+ SIGNIN_CLIENT_SECRET_FILE_VAR
28532
+ ];
27768
28533
  function value(env, name) {
27769
28534
  return (env[name] ?? "").trim();
27770
28535
  }
@@ -27783,10 +28548,20 @@ function machineIdentity(env) {
27783
28548
  return projectedToken(required2(env, MACHINE_TOKEN_FILE_VAR, kind));
27784
28549
  case IDENTITY_METADATA:
27785
28550
  return metadataIdentity(required2(env, MACHINE_AUDIENCE_VAR, kind));
27786
- case IDENTITY_POOL:
27787
- throw new Error(`${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), which federates at the workload identity pool; this process can prove ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
28551
+ case IDENTITY_POOL: {
28552
+ const subject = required2(env, MACHINE_TOKEN_FILE_VAR, kind);
28553
+ const tokenAudience = required2(env, MACHINE_AUDIENCE_VAR, kind);
28554
+ const audience = required2(env, POOL_AUDIENCE_VAR, kind);
28555
+ const serviceAccount = required2(env, POOL_ACCOUNT_VAR, kind);
28556
+ return poolIdentity({
28557
+ subject: projectedToken(subject),
28558
+ audience,
28559
+ serviceAccount,
28560
+ tokenAudience
28561
+ });
28562
+ }
27788
28563
  default:
27789
- throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES} or ${IDENTITY_METADATA}`);
28564
+ throw new Error(`${IDENTITY_VAR}="${kind}" names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA} or ${IDENTITY_POOL}`);
27790
28565
  }
27791
28566
  }
27792
28567
  function tradeSession(env, own = "") {
@@ -27795,16 +28570,32 @@ function tradeSession(env, own = "") {
27795
28570
  }
27796
28571
  async function brokerTokenClient(env, own = "") {
27797
28572
  const brokerUrl = value(env, BROKER_URL_VAR);
27798
- const subject = machineIdentity(env);
27799
- if (brokerUrl === "" || subject === undefined)
28573
+ const machine = machineIdentity(env);
28574
+ if (brokerUrl === "" || machine === undefined)
27800
28575
  return;
27801
- return new BrokerTokenClient({
28576
+ const record = await chooseSignIn(env);
28577
+ if (record === undefined) {
28578
+ const client = new BrokerTokenClient({
28579
+ brokerUrl,
28580
+ key: await newDpopKey(),
28581
+ subject: machine,
28582
+ session: tradeSession(env, own),
28583
+ launcherCredential: false
28584
+ });
28585
+ return { client, signIn: undefined };
28586
+ }
28587
+ const flow = await signInFlow(env);
28588
+ if (flow === undefined) {
28589
+ throw new Error(`${record.person} is signed in on this machine, and this machine configures no sign-in client to renew that sign-in with: set ${SIGNIN_CLIENT_ID_VAR} and ${SIGNIN_CLIENT_SECRET_FILE_VAR}`);
28590
+ }
28591
+ const client = new BrokerTokenClient({
27802
28592
  brokerUrl,
27803
- key: await newDpopKey(),
27804
- subject,
27805
- session: tradeSession(env, own),
27806
- launcherCredential: false
28593
+ key: await importDpopKey(record.box_key, `${record.person}'s box key`),
28594
+ subject: personIdentity(record, flow),
28595
+ actor: machine,
28596
+ session: own.trim() || signInSessionName(record)
27807
28597
  });
28598
+ return { client, signIn: { person: record.person, thumbprint: record.thumbprint } };
27808
28599
  }
27809
28600
 
27810
28601
  // ../envoy-client/src/broker-credential.ts
@@ -27817,12 +28608,6 @@ function brokerRouteConfigured(env) {
27817
28608
  if ((env[BROKER_URL_VAR] ?? "").trim() === "") {
27818
28609
  return { traded: false, gap: `${BROKER_URL_VAR} names no secrets broker to trade it at` };
27819
28610
  }
27820
- if ((env[IDENTITY_VAR] ?? "").trim() === IDENTITY_POOL) {
27821
- return {
27822
- traded: false,
27823
- gap: `${IDENTITY_VAR}=${IDENTITY_POOL} is traded by the Go client alone (agent-secrets), never by this process`
27824
- };
27825
- }
27826
28611
  if (machineIdentity(env) === undefined) {
27827
28612
  return { traded: false, gap: `${IDENTITY_VAR} names no identity this machine proves` };
27828
28613
  }
@@ -27832,37 +28617,91 @@ var CLIENTS = new Map;
27832
28617
  function forgetBrokerSession(session) {
27833
28618
  CLIENTS.delete(session.trim());
27834
28619
  }
27835
- function clientFor(env, own) {
27836
- const session = tradeSession(env, own);
27837
- const key = JSON.stringify([
27838
- env.AGENT_SECRETS_URL,
27839
- env.AGENT_SECRETS_MACHINE_IDENTITY,
27840
- env.AGENT_SECRETS_MACHINE_TOKEN_FILE,
27841
- env.AGENT_SECRETS_MACHINE_AUDIENCE
27842
- ]);
27843
- const held = CLIENTS.get(session) ?? new Map;
27844
- CLIENTS.set(session, held);
27845
- const made = held.get(key) ?? brokerTokenClient(env, session);
27846
- held.set(key, made);
27847
- return made;
28620
+ function signInName(record) {
28621
+ return `${record.person}\x00${record.thumbprint}`;
28622
+ }
28623
+ function keyOf(env, own) {
28624
+ return {
28625
+ session: own.trim(),
28626
+ variables: JSON.stringify(BROKER_VARIABLES.map((name) => env[name]))
28627
+ };
28628
+ }
28629
+ function entryFor(key) {
28630
+ let sessions = CLIENTS.get(key.session);
28631
+ if (sessions === undefined) {
28632
+ sessions = new Map;
28633
+ CLIENTS.set(key.session, sessions);
28634
+ }
28635
+ let entry = sessions.get(key.variables);
28636
+ if (entry === undefined) {
28637
+ entry = { making: undefined, made: undefined, refused: new Map };
28638
+ sessions.set(key.variables, entry);
28639
+ }
28640
+ return entry;
28641
+ }
28642
+ async function make(env, own) {
28643
+ const made = await brokerTokenClient(env, own);
28644
+ const signIn = made?.signIn;
28645
+ return { client: made?.client, signIn: signIn === undefined ? "" : signInName(signIn) };
28646
+ }
28647
+ async function clientFor(env, own) {
28648
+ const key = keyOf(env, own);
28649
+ const entry = entryFor(key);
28650
+ if (entry.refused.size > 0) {
28651
+ const record = await chooseSignIn(env);
28652
+ const chosen = record === undefined ? "" : signInName(record);
28653
+ if (entry.refused.has(chosen))
28654
+ throw entry.refused.get(chosen);
28655
+ if (entry.made !== undefined && entry.made.signIn !== chosen) {
28656
+ entry.making = undefined;
28657
+ entry.made = undefined;
28658
+ }
28659
+ }
28660
+ let making = entry.making;
28661
+ if (making === undefined) {
28662
+ const started = make(env, key.session);
28663
+ making = started;
28664
+ entry.making = started;
28665
+ started.then((made) => {
28666
+ if (entry.making === started)
28667
+ entry.made = made;
28668
+ }, () => {
28669
+ if (entry.making === started)
28670
+ entry.making = undefined;
28671
+ });
28672
+ }
28673
+ return { entry, made: await making };
27848
28674
  }
27849
28675
  function brokerCredential(env, session) {
27850
- let held = "";
28676
+ let presented = "";
28677
+ const own = (acting) => (acting ?? "").trim() || sessionName(session);
27851
28678
  return {
27852
28679
  scheme: "DPoP",
27853
28680
  async headers(method, url, acting) {
27854
- const client = await clientFor(env, (acting ?? "").trim() || sessionName(session));
28681
+ const { entry, made } = await clientFor(env, own(acting));
28682
+ const { client } = made;
27855
28683
  if (client === undefined) {
27856
28684
  throw new Error("AGENT_SECRETS_URL and AGENT_SECRETS_MACHINE_IDENTITY no longer name a broker and an identity to trade");
27857
28685
  }
27858
- const token = await client.token();
27859
- held = token.accessToken;
28686
+ let token;
28687
+ try {
28688
+ token = await client.token();
28689
+ } catch (error) {
28690
+ if (made.signIn !== "" && isFinalRefusal(error))
28691
+ entry.refused.set(made.signIn, error);
28692
+ throw error;
28693
+ }
28694
+ presented = token.accessToken;
27860
28695
  return {
27861
28696
  Authorization: `DPoP ${token.accessToken}`,
27862
28697
  DPoP: await client.key.proof({ method, url, accessToken: token.accessToken })
27863
28698
  };
27864
28699
  },
27865
- secret: () => held
28700
+ stale(acting) {
28701
+ const key = keyOf(env, own(acting));
28702
+ CLIENTS.get(key.session)?.get(key.variables)?.made?.client?.drop();
28703
+ },
28704
+ secret: () => presented
27866
28705
  };
27867
28706
  }
27868
28707
 
@@ -27942,7 +28781,7 @@ function brokerRouteForced(env) {
27942
28781
  return false;
27943
28782
  if (written === "1")
27944
28783
  return true;
27945
- return offWithError(`DISPATCH_TOKEN_BROKER is "${written}" and takes 1: set it to 1 where this session's Dispatch credential is this machine's own identity traded at the secrets broker, and leave it unset where a bearer is read as usual`);
28784
+ return offWithError(`DISPATCH_TOKEN_BROKER is "${written}" and 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`);
27946
28785
  }
27947
28786
  function dispatchTarget(env, config) {
27948
28787
  if (config.kind === "failed")
@@ -27993,7 +28832,7 @@ function dispatchTarget(env, config) {
27993
28832
  return { enabled: true, url: brokered, source: { kind: "broker" } };
27994
28833
  }
27995
28834
  if (forced) {
27996
- return offWithError(`DISPATCH_TOKEN_BROKER is set, so this session's Dispatch credential is this machine's own identity traded at the secrets broker, and ${route.gap}: Dispatch is off rather than written with whatever bearer this box holds`);
28835
+ 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`);
27997
28836
  }
27998
28837
  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}`);
27999
28838
  }
@@ -28416,13 +29255,13 @@ function claudeProjectDirectory(environment, fallback) {
28416
29255
  }
28417
29256
 
28418
29257
  // src/session-identity.ts
28419
- import { readFile as readFile2 } from "fs/promises";
28420
- import { basename as basename2, join as join6 } from "path";
29258
+ import { readFile as readFile3 } from "fs/promises";
29259
+ import { basename as basename2, join as join7 } from "path";
28421
29260
 
28422
29261
  // src/session-state.ts
28423
29262
  import { readFileSync as readFileSync5 } from "fs";
28424
- import { mkdir as mkdir2, readdir, rename as rename2, rm, stat, utimes, writeFile as writeFile2 } from "fs/promises";
28425
- import { dirname as dirname2, join as join5 } from "path";
29263
+ import { mkdir as mkdir2, readdir as readdir2, rename as rename2, rm, stat, utimes, writeFile as writeFile2 } from "fs/promises";
29264
+ import { dirname as dirname2, join as join6 } from "path";
28426
29265
  async function writeAtomicStateFile(file, contents) {
28427
29266
  await mkdir2(dirname2(file), { recursive: true, mode: 448 });
28428
29267
  const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
@@ -28434,13 +29273,13 @@ async function touchStateFile(file) {
28434
29273
  await utimes(file, now, now);
28435
29274
  }
28436
29275
  async function pruneStateDirectory(directory, isStale) {
28437
- const entries = await readdir(directory).catch((error) => {
29276
+ const entries = await readdir2(directory).catch((error) => {
28438
29277
  if (hasErrnoCode(error, "ENOENT"))
28439
29278
  return [];
28440
29279
  throw error;
28441
29280
  });
28442
29281
  for (const entry of entries) {
28443
- const file = join5(directory, entry);
29282
+ const file = join6(directory, entry);
28444
29283
  if (!await isStale(file))
28445
29284
  continue;
28446
29285
  await rm(file, { recursive: true, force: true });
@@ -28455,7 +29294,7 @@ async function writtenLongAgo(file) {
28455
29294
  }
28456
29295
  var TITLES_DIRECTORY = "titles";
28457
29296
  function sessionTitleFile(stateDirectory, sessionId) {
28458
- return join5(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
29297
+ return join6(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
28459
29298
  }
28460
29299
  async function writeChosenTitle(file, title) {
28461
29300
  await writeAtomicStateFile(file, `${title}
@@ -28483,7 +29322,7 @@ async function recordChosenTitle(sessionId, title) {
28483
29322
  await writeChosenTitle(file, chosen);
28484
29323
  }
28485
29324
  async function pruneStaleSessionTitles(stateDirectory) {
28486
- await pruneStateDirectory(join5(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
29325
+ await pruneStateDirectory(join6(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
28487
29326
  }
28488
29327
 
28489
29328
  // src/session-identity.ts
@@ -28508,14 +29347,14 @@ class SessionIdentity {
28508
29347
  }
28509
29348
  }
28510
29349
  function sessionHandoffDirectory(stateDirectory, claudePid) {
28511
- return join6(stateDirectory, "sessions", String(claudePid));
29350
+ return join7(stateDirectory, "sessions", String(claudePid));
28512
29351
  }
28513
29352
  function sessionHandoffFile(stateDirectory, claudePid) {
28514
- return join6(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
29353
+ return join7(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
28515
29354
  }
28516
29355
  var ROLES_DIRECTORY = "roles";
28517
29356
  function roleStateFile(stateDirectory, sessionId) {
28518
- return join6(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
29357
+ return join7(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
28519
29358
  }
28520
29359
 
28521
29360
  class UnparseableRoleRecordError extends Error {
@@ -28527,7 +29366,7 @@ class UnparseableRoleRecordError extends Error {
28527
29366
  async function readPersistedRole(roleFile) {
28528
29367
  let bytes;
28529
29368
  try {
28530
- bytes = await readFile2(roleFile, "utf8");
29369
+ bytes = await readFile3(roleFile, "utf8");
28531
29370
  } catch (error) {
28532
29371
  if (hasErrnoCode(error, "ENOENT"))
28533
29372
  return;
@@ -28549,7 +29388,7 @@ async function writeSessionHandoff(file, sessionId) {
28549
29388
  }
28550
29389
  async function readSessionHandoff(file) {
28551
29390
  try {
28552
- const id = (await readFile2(file, "utf8")).trim();
29391
+ const id = (await readFile3(file, "utf8")).trim();
28553
29392
  return id.length === 0 ? undefined : id;
28554
29393
  } catch (error) {
28555
29394
  if (hasErrnoCode(error, "ENOENT"))
@@ -28566,14 +29405,14 @@ function processExists(pid) {
28566
29405
  }
28567
29406
  }
28568
29407
  async function pruneStaleSessionHandoffs(stateDirectory) {
28569
- await pruneStateDirectory(join6(stateDirectory, "sessions"), (file) => {
29408
+ await pruneStateDirectory(join7(stateDirectory, "sessions"), (file) => {
28570
29409
  const pid = basename2(file);
28571
29410
  return /^\d+$/.test(pid) && !processExists(Number(pid));
28572
29411
  });
28573
29412
  }
28574
29413
  async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
28575
29414
  const own = roleStateFile(stateDirectory, currentSessionId);
28576
- await pruneStateDirectory(join6(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
29415
+ await pruneStateDirectory(join7(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
28577
29416
  }
28578
29417
 
28579
29418
  // hooks/session-hook.ts
@@ -28728,7 +29567,7 @@ function dispatchFirst(raw) {
28728
29567
  process.stdout.write(JSON.stringify({
28729
29568
  hookSpecificOutput: {
28730
29569
  hookEventName: input.hook_event_name,
28731
- additionalContext: readDispatchFirstContext(dispatchFirstSkillFile(join7(pluginRoot, "skills")))
29570
+ additionalContext: readDispatchFirstContext(dispatchFirstSkillFile(join8(pluginRoot, "skills")))
28732
29571
  }
28733
29572
  }));
28734
29573
  }
@@ -28790,7 +29629,7 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
28790
29629
  } catch (error) {
28791
29630
  return { reason: messageFor(error) };
28792
29631
  }
28793
- const lock = join7(directory, REFRESH_LOCK);
29632
+ const lock = join8(directory, REFRESH_LOCK);
28794
29633
  if (!refreshLockHeld(lock)) {
28795
29634
  Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd], {
28796
29635
  stdin: "ignore",
@@ -28799,7 +29638,7 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
28799
29638
  detached: true
28800
29639
  }).unref();
28801
29640
  }
28802
- const file = join7(directory, REFRESH_OUTCOME);
29641
+ const file = join8(directory, REFRESH_OUTCOME);
28803
29642
  for (;; ) {
28804
29643
  const outcome = refreshOutcome(file, startedAt);
28805
29644
  if (outcome !== undefined) {
@@ -28884,7 +29723,7 @@ async function answers(text) {
28884
29723
  async function answersRefresh(session, cwd) {
28885
29724
  const directory = sessionDirectory(process.env, session);
28886
29725
  mkdirSync2(directory, { recursive: true, mode: 448 });
28887
- const lock = join7(directory, REFRESH_LOCK);
29726
+ const lock = join8(directory, REFRESH_LOCK);
28888
29727
  if (takeRefreshLock(lock)) {
28889
29728
  try {
28890
29729
  const file = sessionConfigFile("claude", process.env);
@@ -28902,7 +29741,7 @@ async function answersRefresh(session, cwd) {
28902
29741
  text: read.text ?? null,
28903
29742
  notice: read.notice ?? null
28904
29743
  };
28905
- writeAtomically(join7(directory, REFRESH_OUTCOME), JSON.stringify(outcome));
29744
+ writeAtomically(join8(directory, REFRESH_OUTCOME), JSON.stringify(outcome));
28906
29745
  } finally {
28907
29746
  rmSync3(lock, { force: true });
28908
29747
  }