@sjawhar/claude-envoy 6.22.1 → 6.23.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.
@@ -36519,6 +36519,8 @@ var ActorOriginSchema = strictObject({
36519
36519
  session_title: string2().optional()
36520
36520
  }).readonly();
36521
36521
  var DISPATCH_SCOPES = ["person", "approve", "p0"];
36522
+ var DISPATCH_SIGN_IN_SCOPES = ["person", "p0"];
36523
+ var BROKER_REQUEST_REASON_MAX = 400;
36522
36524
  var ActorActSchema = strictObject({
36523
36525
  session: string2().optional(),
36524
36526
  session_proven: literal(true).optional(),
@@ -38096,7 +38098,7 @@ var dispatchToolSpecs = [
38096
38098
  {
38097
38099
  name: "dispatch_whoami",
38098
38100
  example: {},
38099
- description: "Who Dispatch takes this session for: {session, owner, service, project, project_scope}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token and under a broker token that names a service and no person. With a null owner, a create with no assignee falls back to the parent's assignee, when the parent is in the issue's own project, and then to the project's default assignee, which every project names, so every issue you create has an assignee. A question on an issue reaches the person it was handed to, else the issue's assignee, else the project's default assignee. service is the subject of the verified service-account token that authenticated you, or the service a broker token naming no person names: a job's identity as its job entry lists it, the Kubernetes account an exchange entry lists, or the fleet of a machine nobody has signed in on; else null. project_scope is a broker token's project scope, and null for every other credential. A job's broker token has the project scope named or public, holds no OAuth scope and writes as its service: a route that needs an OAuth scope refuses it with 403 OAUTH_SCOPE_REQUIRED before Dispatch's project check runs. named names one project, and that check judges its writes as it judges a person's named token's for the same project: it refuses a write that belongs to the deployment, such as a project create, with 403 PROJECT_SCOPE_DEPLOYMENT. public names no one project, so it may write wherever a token that names no project may. An exchange entry's broker token that names its account has the project scope named and no project, and writes as that account wherever a token that names no project may. A machine's broker token that names a service has the project scope person; it may read and is refused every write with SIGN_IN_REQUIRED, which names the command a person signs in on that machine with. project is the project your credential's token names, or null when it names none. A token that names a project also writes other projects' objects, as a credential that names none does. The one exception is a private project that the token does not name.",
38101
+ description: "Who Dispatch takes this session for: {session, owner, service, project, project_scope, scopes}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token and under a broker token that names a service and no person. With a null owner, a create with no assignee falls back to the parent's assignee, when the parent is in the issue's own project, and then to the project's default assignee, which every project names, so every issue you create has an assignee. A question on an issue reaches the person it was handed to, else the issue's assignee, else the project's default assignee. service is the subject of the verified service-account token that authenticated you, or the service a broker token naming no person names: a job's identity as its job entry lists it, the Kubernetes account an exchange entry lists, or the fleet of a machine nobody has signed in on; else null. project_scope is a broker token's project scope, and null for every other credential. A job's broker token has the project scope named or public, holds no OAuth scope and writes as its service: a route that needs an OAuth scope refuses it with 403 OAUTH_SCOPE_REQUIRED before Dispatch's project check runs. named names one project, and that check judges its writes as it judges a person's named token's for the same project: it refuses a write that belongs to the deployment, such as a project create, with 403 PROJECT_SCOPE_DEPLOYMENT. public names no one project, so it may write wherever a token that names no project may. An exchange entry's broker token that names its account has the project scope named and no project, and writes as that account wherever a token that names no project may. A machine's broker token that names a service has the project scope person; it may read and is refused every write with SIGN_IN_REQUIRED, which names the command a person signs in on that machine with. project is the project your credential's token names, or null when it names none. A token that names a project also writes other projects' objects, as a credential that names none does. The one exception is a private project that the token does not name. scopes is the OAuth scopes your credential holds, such as those a Dispatch sign-in's person approved, and [] for none; the tool's text names them, and scopes is null where Dispatch names none.",
38100
38102
  arguments: () => ({}),
38101
38103
  strict: true
38102
38104
  },
@@ -38732,6 +38734,9 @@ function inboxThreadRow(row) {
38732
38734
  function awaitsDecision(row) {
38733
38735
  return row.state !== "expired";
38734
38736
  }
38737
+ function signInScopes(row) {
38738
+ return Array.isArray(row.dispatch_scopes) ? row.dispatch_scopes : null;
38739
+ }
38735
38740
  // ../contracts/src/dispatch-api-messages.ts
38736
38741
  var messageDeliveryFields = {
38737
38742
  message_id: string2(),
@@ -40015,7 +40020,12 @@ var DISPATCH_READING_SURFACES = [
40015
40020
  surface: "change-view-diff"
40016
40021
  },
40017
40022
  {
40018
- files: ["packages/dispatch/web/src/features/credentials/CredentialRecordFacts.tsx"],
40023
+ files: [
40024
+ "packages/dispatch/web/src/features/credentials/CredentialRecordFacts.tsx",
40025
+ "packages/dispatch/web/src/features/credentials/CredentialRequestsSection.tsx",
40026
+ "packages/dispatch/web/src/features/credentials/MachineLoginPage.tsx",
40027
+ "packages/dispatch/web/src/features/credentials/MachineLoginsSection.tsx"
40028
+ ],
40019
40029
  reach: "/credentials/machine, a machine login request's reason",
40020
40030
  reason: `A credential request's reason is what the asking agent typed for it. ${ONE_LINE_FIELD_REASON}`,
40021
40031
  record: false,
@@ -44499,6 +44509,7 @@ var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
44499
44509
  var GRANT_TYPE_REFRESH = "refresh_token";
44500
44510
  var MACHINE_LOGIN_CLIENT_ID = "agent-secrets-helper";
44501
44511
  var MACHINE_LOGIN_SCOPE = "machine";
44512
+ var DISPATCH_LOGIN_SCOPE = "dispatch";
44502
44513
  var REQUEST_OBJECT_TYPE = "agent-secrets-request+jwt";
44503
44514
  var LAUNCHER_CREDENTIAL_DETAIL = "launcher_credential";
44504
44515
  var REQUEST_OBJECT_LIFETIME_SECONDS = 600;
@@ -44531,6 +44542,8 @@ var INSTANCE_PATTERN = "[A-Za-z0-9*?._\\[\\]-]{1,100}";
44531
44542
  var NUMBER = "[0-9]{1,6}";
44532
44543
  var CLAIM = "[A-Za-z0-9_.:-]{1,64}";
44533
44544
  var URI = "[A-Za-z0-9:/._-]{1,200}";
44545
+ var SCOPE_WORD = "[a-z][a-z0-9_-]{0,63}";
44546
+ var SCOPE_LIST = `${SCOPE_WORD}(?:, ${SCOPE_WORD}){0,7}`;
44534
44547
  var SESSION_RULE = "a session name is printable, carries no whitespace, '\\*' or '>', and is at most [0-9]{1,4} bytes";
44535
44548
  function escapeRegExp(text) {
44536
44549
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -44557,7 +44570,8 @@ var POLICY_SENTINELS = {
44557
44570
  sessionFixed: "exchange: the entry fixes the session name its tokens carry",
44558
44571
  projectsFixed: "exchange: the request names projects other than the one its entry gives",
44559
44572
  projectsNoPerson: "exchange: a token that names no person names no project",
44560
- restrictedOneProject: "exchange: a restricted member's machine login names exactly one project"
44573
+ restrictedOneProject: "exchange: a restricted member's machine login names exactly one project",
44574
+ restrictedSignIn: "exchange: a restricted member's Dispatch sign-in is given no token"
44561
44575
  };
44562
44576
  function policy(sentinel, format, ...slots) {
44563
44577
  return `${escapeRegExp(`The subject token was refused: ${POLICY_SENTINELS[sentinel]}: `)}${formatPattern(format, slots)}\\.`;
@@ -44596,6 +44610,7 @@ var POLICY_REFUSAL_PATTERNS = [
44596
44610
  policy("projectsFixed", "%s writes the project %s that its entry names, and the request named %s", IDENTITY, PROJECT_SLOT, PROJECT_LIST),
44597
44611
  policy("projectsFixed", "%s's entry gives its token the projects %s, and the request named %s, which that list does not name", IDENTITY, JOB_LIST, PROJECT_SLOT),
44598
44612
  policy("restrictedOneProject", "%s is a restricted member, who sees only the projects that name them, and the trade asked for %d; set AGENT_SECRETS_PROJECTS to the one project this session works on", PERSON_SLOT, NUMBER),
44613
+ policy("restrictedSignIn", "%s is a restricted member, whose machine's token is held to one project, and a Dispatch sign-in acts in every project its person may reach; sign in to Dispatch in a browser instead", PERSON_SLOT),
44599
44614
  `${escapeRegExp("The subject token was refused: ")}${formatPattern("the subject token was not minted for %s, which is the audience this broker accepts from %s", [URI, URI])}\\.`
44600
44615
  ];
44601
44616
  var KNOWN_BROKER_REFUSAL_PATTERNS = [
@@ -44627,6 +44642,7 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
44627
44642
  "The 'as_of' parameter names the zero time, which is no cut: a trade that reads the present names no cut\\.",
44628
44643
  "The 'as_of' parameter names a time later than this trade, and a cut is a time that has passed\\.",
44629
44644
  "The scope 'read' narrows a token to reading, and a job entry's token is minted whole, with no scope: ask for it without that scope\\.",
44645
+ "A Dispatch sign-in is minted whole with its approved scopes and cannot trade for 'read'\\.",
44630
44646
  "A read trade makes or moves no launcher credential, so it cannot send launcher_credential=true\\. Trade for read without the parameter\\.",
44631
44647
  `${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\\.`,
44632
44648
  `${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\\.`,
@@ -44636,6 +44652,10 @@ var KNOWN_BROKER_REFUSAL_PATTERNS = [
44636
44652
  "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\\.",
44637
44653
  "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\\.",
44638
44654
  "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\\.",
44655
+ "this broker serves no Dispatch sign-in: BROKER_DISPATCH_SIGNIN is off",
44656
+ `the scope "${SCOPE_WORD}" is not consentable; a Dispatch sign-in may approve only ${SCOPE_LIST}`,
44657
+ "a machine login's launcher_credential detail carries no actions member, not even an empty list",
44658
+ "a device login names exactly one scope, machine or dispatch",
44639
44659
  ...POLICY_REFUSAL_PATTERNS
44640
44660
  ].map((source) => new RegExp(`^${source}$`));
44641
44661
  var LIBRARY_DESCRIPTIONS = [
@@ -44924,14 +44944,26 @@ class SignInEndedError extends Error {
44924
44944
  }
44925
44945
  }
44926
44946
  var DEVICE_LOGIN_COMMAND = "dispatch login --device";
44947
+ function deviceLoginCommand(dispatchScopes) {
44948
+ if (dispatchScopes === null)
44949
+ return DEVICE_LOGIN_COMMAND;
44950
+ return `${DEVICE_LOGIN_COMMAND} --scope ${dispatchScopes.join(",") || "none"}`;
44951
+ }
44927
44952
 
44928
44953
  class DeviceLoginEndedError extends Error {
44929
- constructor(login) {
44930
- super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${DEVICE_LOGIN_COMMAND}`);
44954
+ constructor(login, command) {
44955
+ super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${command}`);
44931
44956
  this.name = "DeviceLoginEndedError";
44932
44957
  }
44933
44958
  }
44934
44959
 
44960
+ class DeviceLoginReplacedError extends Error {
44961
+ constructor(file, command) {
44962
+ super(`${file} holds another login than the one this process started with, since ${command} ran again; start a new session to trade the new one: the secrets broker keeps a session's name for the principal that wrote under it, and each Dispatch sign-in is a principal of its own, as is each person's machine login, so this session started again is refused, except where a machine login replaced the same person's machine login, which this process cannot tell, since the login file names no person`);
44963
+ this.name = "DeviceLoginReplacedError";
44964
+ }
44965
+ }
44966
+
44935
44967
  class LockHeldError extends Error {
44936
44968
  constructor(lock, options) {
44937
44969
  super(`another process of this machine held ${lock} for all of this trade's time, so nothing was sent to the secrets broker`, options);
@@ -44939,7 +44971,7 @@ class LockHeldError extends Error {
44939
44971
  }
44940
44972
  }
44941
44973
  function isFinalRefusal(error) {
44942
- return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
44974
+ return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError || error instanceof DeviceLoginReplacedError;
44943
44975
  }
44944
44976
 
44945
44977
  // ../cipher-client/src/broker-request.ts
@@ -45724,6 +45756,16 @@ function wholeMember(json, name) {
45724
45756
  const value = json[name];
45725
45757
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
45726
45758
  }
45759
+ function scopesMember(json, name) {
45760
+ if (!Object.hasOwn(json, name))
45761
+ return null;
45762
+ const value = json[name];
45763
+ const consentable = DISPATCH_SIGN_IN_SCOPES;
45764
+ if (!Array.isArray(value) || new Set(value).size !== value.length || value.some((scope) => !consentable.includes(scope))) {
45765
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: ${name}, where it is given, is a list of distinct Dispatch scopes a sign-in may hold (${DISPATCH_SIGN_IN_SCOPES.join(", ")}); make the Dispatch sign-in again with: ${DEVICE_LOGIN_COMMAND} --scope <list>`);
45766
+ }
45767
+ return value;
45768
+ }
45727
45769
  function checkPrivate(info, what, forbidden, opens, notOwned) {
45728
45770
  const mode = info.mode & 511;
45729
45771
  if ((mode & forbidden) !== 0) {
@@ -46070,6 +46112,7 @@ async function readDeviceLogin(path) {
46070
46112
  if (key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
46071
46113
  throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a P-256 key`);
46072
46114
  }
46115
+ const dispatchScopes = scopesMember(json, "dispatch_scopes");
46073
46116
  const accessToken = member(json, "access_token");
46074
46117
  const accessText = member(json, "access_expires_at");
46075
46118
  const accessExpiresAt = accessToken === "" || accessText === "" ? null : new Date(accessText);
@@ -46082,7 +46125,8 @@ async function readDeviceLogin(path) {
46082
46125
  broker,
46083
46126
  accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
46084
46127
  accessExpiresAt: accessUsable ? accessExpiresAt : null,
46085
- accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null
46128
+ accessLifeSeconds: accessUsable ? wholeMember(json, "access_life_seconds") : null,
46129
+ dispatchScopes
46086
46130
  };
46087
46131
  }
46088
46132
  function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
@@ -46113,6 +46157,7 @@ async function saveDeviceLogin(path, login, held, keep = false) {
46113
46157
  refresh_token: login.refreshToken,
46114
46158
  expires_at: login.expiresAt.toISOString(),
46115
46159
  broker: login.broker,
46160
+ ...login.dispatchScopes === null ? {} : { dispatch_scopes: login.dispatchScopes },
46116
46161
  ...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
46117
46162
  access_token: login.accessToken,
46118
46163
  access_expires_at: login.accessExpiresAt.toISOString(),
@@ -46218,6 +46263,28 @@ function unpollableAnswer(answered, intervalSeconds, lifetimeSeconds, left) {
46218
46263
  return `${answer}: ${lapses}; ${verdict} ${remedy}`;
46219
46264
  }
46220
46265
 
46266
+ // ../cipher-client/src/device-login-scopes.ts
46267
+ function signInScopes2(scopes) {
46268
+ const consentable = DISPATCH_SIGN_IN_SCOPES;
46269
+ const unique = [...new Set(scopes)].sort();
46270
+ if (unique.some((scope) => !consentable.includes(scope))) {
46271
+ throw new RangeError(`a Dispatch sign-in may ask only for these scopes: ${DISPATCH_SIGN_IN_SCOPES.join(", ")}`);
46272
+ }
46273
+ return unique;
46274
+ }
46275
+ function signInScopesOf(answered, asked, exact) {
46276
+ const named = answered["dispatch_scopes"];
46277
+ if (answered.scope !== DISPATCH_LOGIN_SCOPE || !Array.isArray(named))
46278
+ return;
46279
+ const askedFor = asked;
46280
+ if (new Set(named).size !== named.length || named.some((scope) => !askedFor.includes(scope))) {
46281
+ return;
46282
+ }
46283
+ if (exact && named.length !== asked.length)
46284
+ return;
46285
+ return named;
46286
+ }
46287
+
46221
46288
  // ../cipher-client/src/dpop.ts
46222
46289
  import {
46223
46290
  createHash,
@@ -46312,6 +46379,7 @@ function endsGrant(error) {
46312
46379
 
46313
46380
  // ../cipher-client/src/device-login.ts
46314
46381
  var BROKER_SETTING = "AGENT_SECRETS_URL";
46382
+ var NO_DISPATCH_SIGN_IN = "this broker serves no Dispatch sign-in: it predates them, or BROKER_DISPATCH_SIGNIN is off";
46315
46383
  var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
46316
46384
  function leastAccessLifeMs(leastLifeMs, lifeSeconds) {
46317
46385
  if (leastLifeMs === undefined || lifeSeconds === null)
@@ -46396,6 +46464,11 @@ async function startDeviceLogin(options) {
46396
46464
  const brokerUrl = deviceLoginBroker(options.brokerUrl);
46397
46465
  const endpoint = brokerUrl + DEVICE_AUTHORIZATION_PATH;
46398
46466
  const person = options.person.trim();
46467
+ const dispatchScopes = options.dispatchScopes === undefined ? null : signInScopes2(options.dispatchScopes);
46468
+ if (options.reason !== undefined && Array.from(options.reason).length > BROKER_REQUEST_REASON_MAX) {
46469
+ throw new RangeError(`a device login's reason has at most ${BROKER_REQUEST_REASON_MAX} characters`);
46470
+ }
46471
+ const describe = dispatchScopes === null ? "this machine's device login" : "this Dispatch sign-in";
46399
46472
  const { privateKey } = generateKeyPairSync2("ec", { namedCurve: "P-256" });
46400
46473
  const jwk = loginDpopKey(privateKey).publicJwk;
46401
46474
  const thumbprint = await calculateJwkThumbprint(jwk);
@@ -46406,20 +46479,31 @@ async function startDeviceLogin(options) {
46406
46479
  jti: randomUUID4(),
46407
46480
  iat,
46408
46481
  exp: iat + REQUEST_OBJECT_LIFETIME_SECONDS,
46409
- authorization_details: [{ type: LAUNCHER_CREDENTIAL_DETAIL, identifier: options.host }],
46410
- login_hint: person
46482
+ authorization_details: [
46483
+ {
46484
+ type: LAUNCHER_CREDENTIAL_DETAIL,
46485
+ identifier: options.host,
46486
+ ...dispatchScopes === null ? {} : { actions: dispatchScopes }
46487
+ }
46488
+ ],
46489
+ login_hint: person,
46490
+ ...options.reason === undefined ? {} : { reason: options.reason }
46411
46491
  };
46412
46492
  const request = await new CompactSign(new TextEncoder().encode(JSON.stringify(claims))).setProtectedHeader({ alg: "ES256", typ: REQUEST_OBJECT_TYPE, jwk }).sign(privateKey);
46413
46493
  const config = brokerConfiguration(brokerUrl, options.fetch ?? fetch);
46414
46494
  let answered;
46415
46495
  try {
46416
46496
  answered = await initiateDeviceAuthorization(config, {
46417
- scope: MACHINE_LOGIN_SCOPE,
46497
+ scope: dispatchScopes === null ? MACHINE_LOGIN_SCOPE : DISPATCH_LOGIN_SCOPE,
46418
46498
  dpop_jkt: thumbprint,
46419
46499
  request
46420
46500
  });
46421
46501
  } catch (error) {
46422
- throw brokerRefusal("ask for a code for", "this machine's device login", endpoint, error);
46502
+ const refusal = brokerRefusal("ask for a code for", describe, endpoint, error);
46503
+ if (dispatchScopes !== null && refusal instanceof BrokerRefusedError && refusal.status === 400 && refusal.code === "invalid_scope" && (refusal.said === "" || refusal.said === REFUSAL_TEXT_WITHHELD)) {
46504
+ throw new Error(`the secrets broker refused ${describe}: HTTP 400 invalid_scope: ${NO_DISPATCH_SIGN_IN}`);
46505
+ }
46506
+ throw refusal;
46423
46507
  }
46424
46508
  const intervalSeconds = Math.max(answered.interval ?? DEFAULT_POLL_SECONDS, LEAST_POLL_SECONDS);
46425
46509
  const lifetimeSeconds = Math.min(answered.expires_in, MOST_LIFETIME_SECONDS);
@@ -46439,7 +46523,9 @@ async function startDeviceLogin(options) {
46439
46523
  expiresAt,
46440
46524
  intervalSeconds,
46441
46525
  deviceCode: holdSecret(answered.device_code, expiresAt),
46442
- key: privateKey
46526
+ key: privateKey,
46527
+ dispatchScopes,
46528
+ describe
46443
46529
  };
46444
46530
  }
46445
46531
  function retryAfterMs2(error) {
@@ -46460,9 +46546,11 @@ async function finishDeviceLogin(started, options) {
46460
46546
  nonce: { value: "" }
46461
46547
  });
46462
46548
  const endpoint = started.brokerUrl + TOKEN_PATH;
46549
+ const again = deviceLoginCommand(started.dispatchScopes);
46550
+ const revoke = `Machine logins on ${started.verificationUri}`;
46463
46551
  const expired = (outages) => {
46464
46552
  const unreached = outages === 0 ? "" : `; the broker was unreachable or busy for the last ${outages === 1 ? "poll" : `${outages} polls`}`;
46465
- return new Error(`the code ${started.userCode} expired before ${started.person} approved this machine${unreached}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
46553
+ return new Error(`the code ${started.userCode} expired before ${started.person} approved ${started.describe}${unreached}; ask again with: ${again}`);
46466
46554
  };
46467
46555
  let interval = started.intervalSeconds;
46468
46556
  let outages = 0;
@@ -46471,7 +46559,7 @@ async function finishDeviceLogin(started, options) {
46471
46559
  if (!reached) {
46472
46560
  const first = `its first poll, ${seconds(pastTheMillisecond(interval) ? waitMs / 1000 : interval)} s on`;
46473
46561
  const lapse = leftAtStart <= 0 ? `had lapsed before ${first}` : named > leftAtStart ? `would lapse here before ${first}, as this machine polls a device code for an hour at most` : `lapses in ${seconds(leftAtStart / 1000)} s, no later than ${first}`;
46474
- throw new Error(`the code ${started.userCode} ${lapse}, so no poll could reach it; ask again with: ${DEVICE_LOGIN_COMMAND}`);
46562
+ throw new Error(`the code ${started.userCode} ${lapse}, so no poll could reach it; ask again with: ${again}`);
46475
46563
  }
46476
46564
  const endsAt = clock() + leftAtStart;
46477
46565
  while (true) {
@@ -46491,7 +46579,7 @@ async function finishDeviceLogin(started, options) {
46491
46579
  } catch (error) {
46492
46580
  const code = refusalCode(error);
46493
46581
  if (code === "access_denied") {
46494
- throw new Error(`this machine's device login was denied, not approved as ${started.person}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
46582
+ throw new Error(`${started.describe} was denied, not approved as ${started.person}; ask again with: ${again}`);
46495
46583
  }
46496
46584
  if (code === "expired_token" || code === "invalid_grant")
46497
46585
  throw expired(0);
@@ -46502,14 +46590,23 @@ async function finishDeviceLogin(started, options) {
46502
46590
  interval += 5;
46503
46591
  const pollAgain = code === "authorization_pending" || code === "slow_down" || unanswered;
46504
46592
  if (!pollAgain) {
46505
- const refusal = brokerRefusal("poll the code of", "this machine's device login", endpoint, error);
46506
- throw new Error(`${refusal.message}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
46593
+ const refusal = brokerRefusal("poll the code of", started.describe, endpoint, error);
46594
+ throw new Error(`${refusal.message}; ask again with: ${again}`);
46507
46595
  }
46508
46596
  const asked = unanswered ? retryAfterMs2(error) : 0;
46509
46597
  waitMs = Math.max(waitMillisecondsOf(interval), asked);
46510
46598
  continue;
46511
46599
  }
46512
- const login = loginOf(started.key, started.brokerUrl, answered, Date.now());
46600
+ const issued = loginOf(started.key, started.brokerUrl, answered, Date.now());
46601
+ let dispatchScopes = null;
46602
+ if (started.dispatchScopes !== null) {
46603
+ const approved = signInScopesOf(answered, started.dispatchScopes, false);
46604
+ if (approved === undefined) {
46605
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered ${started.describe} with no scope dispatch, or with dispatch_scopes that are not distinct scopes it asked for, as a broker too old for Dispatch sign-ins does. It may hold the sign-in live as launcher credential ${issued.credentialId}; revoke it in ${revoke}, then log in again with: ${again}`);
46606
+ }
46607
+ dispatchScopes = approved;
46608
+ }
46609
+ const login = { ...issued, dispatchScopes };
46513
46610
  let replaced = "";
46514
46611
  let saved = false;
46515
46612
  try {
@@ -46523,8 +46620,7 @@ async function finishDeviceLogin(started, options) {
46523
46620
  const lockLeft = `this process could not let go of the lock beside ${DEVICE_LOGIN_FILE_NAMED} (${messageOf(error)}); another process takes it over once it is ${DEVICE_LOGIN_STALE_LOCK_MS / 1000} s old`;
46524
46621
  return { ...login, replaced, lockLeft };
46525
46622
  }
46526
- const revoke = `Machine logins on ${started.verificationUri}`;
46527
- throw new Error(error instanceof KeptCopyError ? `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it in its place: ${messageOf(error)}, which then needs no revoke. Where the copy is not used, delete it, since it holds the login's key and refresh token, and revoke the credential in ${revoke}: it stays live until it lapses or is revoked` : `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it: ${messageOf(error)}. The credential stays live until it lapses or is revoked: revoke it in ${revoke}, and log in again with: ${DEVICE_LOGIN_COMMAND}`, { cause: error });
46623
+ throw new Error(error instanceof KeptCopyError ? `${started.person} approved ${started.describe}, launcher credential ${login.credentialId}, but this machine could not keep it in its place: ${messageOf(error)}, which then needs no revoke. Where the copy is not used, delete it, since it holds the login's key and refresh token, and revoke the credential in ${revoke}: it stays live until it lapses or is revoked` : `${started.person} approved ${started.describe}, launcher credential ${login.credentialId}, but this machine could not keep it: ${messageOf(error)}. The credential stays live until it lapses or is revoked: revoke it in ${revoke}, and log in again with: ${again}`, { cause: error });
46528
46624
  }
46529
46625
  return { ...login, replaced, lockLeft: "" };
46530
46626
  }
@@ -46566,10 +46662,10 @@ class DeviceLoginIdentity {
46566
46662
  return await withDeviceLoginLock(this.#path, async (held) => {
46567
46663
  let login = await readDeviceLogin(this.#path);
46568
46664
  if (withoutTrailingSlashes(login.broker) !== this.#brokerUrl) {
46569
- throw new Error(`${DEVICE_LOGIN_FILE_NAMED} was made at another secrets broker than ${BROKER_SETTING} names; log this machine in at this one with: ${DEVICE_LOGIN_COMMAND}`);
46665
+ throw new Error(`${DEVICE_LOGIN_FILE_NAMED} was made at another secrets broker than ${BROKER_SETTING} names; log in at this one again with: ${deviceLoginCommand(login.dispatchScopes)}`);
46570
46666
  }
46571
46667
  if (await calculateJwkThumbprint(loginDpopKey(login.key).publicJwk) !== thumbprint) {
46572
- throw new Error(`${DEVICE_LOGIN_FILE_NAMED} holds another login than the one this process started with, since ${DEVICE_LOGIN_COMMAND} ran again; start this session again to trade the new one`);
46668
+ throw new DeviceLoginReplacedError(DEVICE_LOGIN_FILE_NAMED, DEVICE_LOGIN_COMMAND);
46573
46669
  }
46574
46670
  const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
46575
46671
  const expires = login.accessExpiresAt?.getTime() ?? 0;
@@ -46612,14 +46708,30 @@ async function refreshDeviceLogin(path, login, options) {
46612
46708
  refresh_token: login.refreshToken
46613
46709
  });
46614
46710
  } catch (error) {
46615
- if (endsGrant(error))
46616
- throw new DeviceLoginEndedError(options.describe);
46711
+ if (endsGrant(error)) {
46712
+ throw new DeviceLoginEndedError(options.describe, deviceLoginCommand(login.dispatchScopes));
46713
+ }
46617
46714
  if (sent === 0 && statusOf(error) === 0)
46618
46715
  continue;
46619
46716
  throw brokerRefusal("refresh", options.describe, endpoint, error);
46620
46717
  }
46621
46718
  }
46622
- const next = loginOf(login.key, login.broker, answered, Date.now());
46719
+ const issued = loginOf(login.key, login.broker, answered, Date.now());
46720
+ let dispatchScopes = null;
46721
+ if (login.dispatchScopes !== null) {
46722
+ const kept = signInScopesOf(answered, login.dispatchScopes, true);
46723
+ if (kept === undefined) {
46724
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered the refresh of a Dispatch sign-in without the scope dispatch and the scopes its person approved (${login.dispatchScopes.join(", ") || "none"}). The sign-in stays live; revoke it in Dispatch's Machine logins page, then log in again with: ${deviceLoginCommand(login.dispatchScopes)}`);
46725
+ }
46726
+ dispatchScopes = kept;
46727
+ } else if (answered.scope === DISPATCH_LOGIN_SCOPE) {
46728
+ const kept = signInScopesOf(answered, DISPATCH_SIGN_IN_SCOPES, false);
46729
+ if (kept === undefined) {
46730
+ throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered the refresh under the scope dispatch, so this is a Dispatch sign-in, with dispatch_scopes that are not distinct scopes a sign-in may hold, and ${DEVICE_LOGIN_FILE_NAMED} names none its person approved. The sign-in stays live; revoke it in Dispatch's Machine logins page, then log in again with: ${DEVICE_LOGIN_COMMAND} --scope <the scopes to approve>`);
46731
+ }
46732
+ dispatchScopes = kept;
46733
+ }
46734
+ const next = { ...issued, dispatchScopes };
46623
46735
  await saveDeviceLogin(path, next, options.held);
46624
46736
  return next;
46625
46737
  }
@@ -50790,21 +50902,25 @@ var LOGIN_COMMAND = "login";
50790
50902
  var LOGIN_SENTENCE = "Logs this machine in at the secrets broker, once per machine, for a machine with no identity of its own, such as a laptop.";
50791
50903
  function loginHelp() {
50792
50904
  return [
50793
- "Usage: dispatch login --device [--person <address>]",
50905
+ "Usage: dispatch login --device [--person <address>] [--scope <list>] [--reason <text>]",
50794
50906
  "",
50795
- `${LOGIN_SENTENCE} It prints a code and the page to type it into; the person the login names approves it there, signed in to Dispatch. The login is then kept in the file AGENT_SECRETS_DEVICE_LOGIN_FILE names (default ~/.config/legion/device-login.json), mode 0600, and every session that sets AGENT_SECRETS_MACHINE_IDENTITY=device-login trades it for its broker token.`,
50907
+ `${LOGIN_SENTENCE} With --scope, it makes a Dispatch sign-in for a session or tool instead: the person approves the scopes it asks for, ticking some or all of them, and its tokens hold those scopes alone, never approve; it enrolls no session and reads no secret. Whatever is ticked, the session writes in Dispatch and works on Envoy as its own session within its person's projects; the scope person adds acting as the person, the scope p0, which the page shows unticked until the person ticks it, adds making an issue's own priority 0, and --scope none asks for no scope. A broker serves Dispatch sign-ins only where its deployment turns them on. It prints a code and the page to type it into; the person the login names approves it there, signed in to Dispatch. The login is then kept in the file AGENT_SECRETS_DEVICE_LOGIN_FILE names (default ~/.config/legion/device-login.json), mode 0600, in place of any login that file held, and every session started after that sets AGENT_SECRETS_MACHINE_IDENTITY=device-login trades it for its broker token. A session already running refuses to trade a new login, a scope change included: start a new session to trade it, since the broker keeps a session's name for the principal that wrote under it, and each Dispatch sign-in is a principal of its own, as is each person's machine login, so that session started again is refused, except where a machine login replaced the same person's machine login, which the client cannot tell, since the login file names no person. To keep a machine login and a Dispatch sign-in on one machine, name another file for one of them.`,
50796
50908
  "",
50797
50909
  "Flags:",
50798
50910
  " --device",
50799
50911
  " Log in with the broker's device grant: the only way there is, and required.",
50800
50912
  " --person <address>",
50801
50913
  " The person who approves the login, by the address they sign in to Dispatch with; else AGENT_SECRETS_PERSON.",
50914
+ " --scope <list>",
50915
+ " Create a Dispatch sign-in for the comma-separated scopes person, p0, or none. Omit it for a machine login.",
50916
+ " --reason <text>",
50917
+ " Name the session or tool. It may have at most 400 characters.",
50802
50918
  "",
50803
50919
  "It reads AGENT_SECRETS_URL, the broker, and needs no Dispatch host or session.",
50804
50920
  "",
50805
50921
  "It exits 0 once the login is kept; 1 when the broker could not be reached or refused it, the person denied it, its code expired, or the login could not be kept; and 2 on a usage error, before any request.",
50806
50922
  "",
50807
- "Example: dispatch login --device --person ada@example.com",
50923
+ "Example: dispatch login --device --person ada@example.com --scope person",
50808
50924
  ""
50809
50925
  ].join(`
50810
50926
  `);
@@ -60976,6 +61092,7 @@ async function whoamiCommand(context) {
60976
61092
  const projectScope = identity.kind === "agent" ? identity.project_scope ?? null : null;
60977
61093
  const readOnly = identity.scopes?.includes("read") === true;
60978
61094
  const cut = identity.kind === "agent" ? identity.cut ?? null : null;
61095
+ const scopes = identity.scopes ?? null;
60979
61096
  const session = proved ?? sessionId;
60980
61097
  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.";
60981
61098
  const brokerService = owner === null && service !== null && proved !== null;
@@ -61001,9 +61118,10 @@ async function whoamiCommand(context) {
61001
61118
  acting = `Session ${session} runs under the shared token: ${unowned}`;
61002
61119
  }
61003
61120
  const projectSentence = readOnly ? "" : project !== null ? ` Its token names project ${project}.` : writesAsService ? " It names no one project, so it may write wherever a token that names no project may." : "";
61121
+ const holds = scopes === null ? "" : scopes.length === 0 ? " Its credential holds no scope." : ` Its credential holds the ${scopes.length === 1 ? "scope" : "scopes"} ${scopes.join(", ")}.`;
61004
61122
  return {
61005
- text: acting + elsewhere + projectSentence,
61006
- details: { session, owner, service, project, project_scope: projectScope }
61123
+ text: acting + elsewhere + projectSentence + holds,
61124
+ details: { session, owner, service, project, project_scope: projectScope, scopes }
61007
61125
  };
61008
61126
  }
61009
61127
  async function limitsCommand(context) {
@@ -61090,12 +61208,17 @@ function inboxThreadLine(row, now) {
61090
61208
  function credentialRequestLine(request) {
61091
61209
  const session = request.session ?? null;
61092
61210
  const pending = awaitsDecision(request);
61211
+ const asked = signInScopes(request);
61212
+ const reason = request.reason ?? "";
61093
61213
  return [
61094
- `- ${request.kind}`,
61214
+ asked === null ? `- ${request.kind}` : "- Dispatch sign-in",
61095
61215
  (request.identifiers ?? []).join(", "),
61216
+ ...asked === null ? [] : [`asks for ${asked.join(", ") || "no scope"}`],
61096
61217
  request.requested_at,
61097
61218
  ...pending ? [] : [request.expires_at === undefined ? "expired" : `expired ${request.expires_at}`],
61098
- ...session === null ? [] : [`session request=${session.request ?? "-"}, enrollment=${session.enrollment ?? "-"}`],
61219
+ ...asked !== null ? [
61220
+ reason === "" ? "gives no reason" : `requester's words (unchecked): ${JSON.stringify(reason)}`
61221
+ ] : session === null ? [] : [`session request=${session.request ?? "-"}, enrollment=${session.enrollment ?? "-"}`],
61099
61222
  ...!pending || request.approve_url === undefined ? [] : [request.approve_url]
61100
61223
  ].join(" \xB7 ");
61101
61224
  }
@@ -61466,6 +61589,10 @@ function tradeFailureReason(error) {
61466
61589
  return error.message;
61467
61590
  if (error instanceof SignInEndedError)
61468
61591
  return `the issuer no longer honours the sign-in on this machine; run: ${SIGNIN_COMMAND}`;
61592
+ if (error instanceof DeviceLoginEndedError)
61593
+ return scrub(error.message);
61594
+ if (error instanceof DeviceLoginReplacedError)
61595
+ return scrub(error.message);
61469
61596
  return natsFailureReason(error);
61470
61597
  }
61471
61598
  function isDeadline(error) {
@@ -61633,18 +61760,22 @@ function brokerTokenRefusals(token) {
61633
61760
  }
61634
61761
  };
61635
61762
  }
61636
- function warnedEvery(warn) {
61763
+ function warnedEvery(warn, options = {}) {
61637
61764
  let warnedAt;
61765
+ let warnedText;
61638
61766
  return {
61639
61767
  warn: (text) => {
61640
61768
  const now = Date.now();
61641
- if (warnedAt !== undefined && now - warnedAt < WARN_AGAIN_MS)
61769
+ const held = options.newTextAtOnce !== true || text === warnedText;
61770
+ if (held && warnedAt !== undefined && now - warnedAt < WARN_AGAIN_MS)
61642
61771
  return;
61643
61772
  warnedAt = now;
61773
+ warnedText = text;
61644
61774
  warn(text);
61645
61775
  },
61646
61776
  reset: () => {
61647
61777
  warnedAt = undefined;
61778
+ warnedText = undefined;
61648
61779
  }
61649
61780
  };
61650
61781
  }
@@ -61658,6 +61789,7 @@ function keepNatsCredential(connection, credential, warn) {
61658
61789
  let renewing = false;
61659
61790
  let renewAgain = false;
61660
61791
  const renewal = warnedEvery((why) => warn(`the NATS connection's broker token ${why}; it is tried again, and the connection reconnects once a token is live`));
61792
+ const ended = warnedEvery((why) => warn(`the NATS connection's broker token ${why}; no renewal cures it, so once the token in hand lapses the NATS server refuses each redial of the connection while the refusal lasts`), { newTextAtOnce: true });
61661
61793
  const refusal = warnedEvery(warn);
61662
61794
  const statuses = connection.status();
61663
61795
  const stop = () => {
@@ -61692,7 +61824,7 @@ function keepNatsCredential(connection, credential, warn) {
61692
61824
  schedule(0);
61693
61825
  return;
61694
61826
  }
61695
- renewal.warn(`could not be renewed (${tradeFailureReason(error)})`);
61827
+ (isFinalRefusal(error) ? ended : renewal).warn(`could not be renewed (${tradeFailureReason(error)})`);
61696
61828
  retry();
61697
61829
  return;
61698
61830
  }
@@ -61703,6 +61835,7 @@ function keepNatsCredential(connection, credential, warn) {
61703
61835
  }
61704
61836
  retries = 0;
61705
61837
  renewal.reset();
61838
+ ended.reset();
61706
61839
  schedule(renewDelay(credential.expiresAt().getTime(), Date.now()));
61707
61840
  };
61708
61841
  const tick = async () => {
@@ -67868,7 +68001,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
67868
68001
 
67869
68002
  // package.json
67870
68003
  var name2 = "@sjawhar/claude-envoy";
67871
- var version2 = "6.22.1";
68004
+ var version2 = "6.23.0";
67872
68005
  var package_default = {
67873
68006
  name: name2,
67874
68007
  version: version2,