@duyquangnvx/create-agent-cli 0.30.1 → 0.31.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.
package/dist/bin.js CHANGED
@@ -6,6 +6,7 @@ import { parseArgs, parseEnv } from "node:util";
6
6
  import { constants as constants$1, existsSync, readFileSync, realpathSync } from "node:fs";
7
7
  import { access, chmod, link, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
8
8
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
9
+ import { createHash } from "node:crypto";
9
10
  import { fileURLToPath } from "node:url";
10
11
  //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
11
12
  function getEnumValues(entries) {
@@ -418,7 +419,7 @@ function hide(inst, key, value) {
418
419
  }
419
420
  /** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */
420
421
  /* @__NO_SIDE_EFFECTS__ */
421
- function derived(computes, table) {
422
+ function derived$1(computes, table) {
422
423
  for (const key in computes) {
423
424
  const compute = computes[key];
424
425
  Object.defineProperty(table, key, {
@@ -1075,7 +1076,7 @@ function timeSource(args) {
1075
1076
  function time(args) {
1076
1077
  return new RegExp(`^${timeSource(args)}$`);
1077
1078
  }
1078
- function datetime(args) {
1079
+ function datetime$1(args) {
1079
1080
  const opts = ["Z"];
1080
1081
  if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
1081
1082
  const qualified = `${timeSource({
@@ -1087,7 +1088,7 @@ function datetime(args) {
1087
1088
  }
1088
1089
  const anyString = /^[\s\S]{0,}$/;
1089
1090
  const integer = /^-?\d+$/;
1090
- const number$1 = /^-?\d+(?:\.\d+)?$/;
1091
+ const number$2 = /^-?\d+(?:\.\d+)?$/;
1091
1092
  const boolean$1 = /^(?:true|false)$/i;
1092
1093
  const lowercase = /^[^A-Z]*$/;
1093
1094
  const uppercase = /^[^a-z]*$/;
@@ -1725,7 +1726,7 @@ const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
1725
1726
  $ZodStringFormat.init(inst, def);
1726
1727
  });
1727
1728
  const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
1728
- def.pattern ?? (def.pattern = datetime(def));
1729
+ def.pattern ?? (def.pattern = datetime$1(def));
1729
1730
  $ZodStringFormat.init(inst, def);
1730
1731
  });
1731
1732
  const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
@@ -1870,7 +1871,7 @@ const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
1870
1871
  });
1871
1872
  const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
1872
1873
  $ZodType.init(inst, def);
1873
- inst._zod.pattern = number$1;
1874
+ inst._zod.pattern = number$2;
1874
1875
  inst._zod.parse = (payload, _ctx) => {
1875
1876
  if (def.coerce) try {
1876
1877
  payload.value = Number(payload.value);
@@ -2507,7 +2508,7 @@ const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
2507
2508
  issues: []
2508
2509
  }, ctx);
2509
2510
  if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2510
- if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) {
2511
+ if (typeof key === "string" && number$2.test(key) && keyResult.issues.length) {
2511
2512
  const retryResult = def.keyType._zod.run({
2512
2513
  value: Number(key),
2513
2514
  issues: []
@@ -3497,6 +3498,15 @@ function _number(Class, params) {
3497
3498
  }));
3498
3499
  }
3499
3500
  // @__NO_SIDE_EFFECTS__
3501
+ function _coercedNumber(Class, params) {
3502
+ return new Class(snapshotChecks({
3503
+ type: "number",
3504
+ coerce: true,
3505
+ checks: [],
3506
+ ...normalizeParams(params)
3507
+ }));
3508
+ }
3509
+ // @__NO_SIDE_EFFECTS__
3500
3510
  function _int(Class, params) {
3501
3511
  return new Class({
3502
3512
  type: "number",
@@ -4572,7 +4582,7 @@ function stringifyKeyNames(bySchema, json, visited) {
4572
4582
  else if (typeof rest.const === "number") rest.const = String(rest.const);
4573
4583
  if (!numericType) return rest;
4574
4584
  rest.type = "string";
4575
- if (!values) rest.pattern = (types.includes("number") ? number$1 : integer).source;
4585
+ if (!values) rest.pattern = (types.includes("number") ? number$2 : integer).source;
4576
4586
  return rest;
4577
4587
  }
4578
4588
  /** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
@@ -5053,7 +5063,7 @@ const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
5053
5063
  $ZodString.init(inst, def);
5054
5064
  ZodType.init(inst, def);
5055
5065
  inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
5056
- }, /*@__PURE__*/ derived({
5066
+ }, /*@__PURE__*/ derived$1({
5057
5067
  format: (inst) => aggregateChecks(inst).format ?? null,
5058
5068
  minLength: (inst) => aggregateChecks(inst).minimum ?? null,
5059
5069
  maxLength: (inst) => aggregateChecks(inst).maximum ?? null
@@ -5299,7 +5309,7 @@ const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
5299
5309
  ZodType.init(inst, def);
5300
5310
  inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
5301
5311
  inst.isFinite = true;
5302
- }, /*@__PURE__*/ derived({
5312
+ }, /*@__PURE__*/ derived$1({
5303
5313
  minValue: (inst) => {
5304
5314
  const { minimum, exclusiveMinimum } = aggregateChecks(inst);
5305
5315
  return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);
@@ -5360,7 +5370,7 @@ const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
5360
5370
  return this;
5361
5371
  }
5362
5372
  }));
5363
- function number(params) {
5373
+ function number$1(params) {
5364
5374
  return /* @__PURE__ */ _number(ZodNumber, params);
5365
5375
  }
5366
5376
  const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => {
@@ -5728,6 +5738,16 @@ function superRefine(fn, params) {
5728
5738
  return /* @__PURE__ */ _superRefine(fn, params);
5729
5739
  }
5730
5740
  //#endregion
5741
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/iso.js
5742
+ function datetime(params) {
5743
+ return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
5744
+ }
5745
+ //#endregion
5746
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/coerce.js
5747
+ function number(params) {
5748
+ return /* @__PURE__ */ _coercedNumber(ZodNumber, params);
5749
+ }
5750
+ //#endregion
5731
5751
  //#region ../agent-cli/dist/abort.js
5732
5752
  /** Never resolves; rejects with the signal's reason once it aborts. */
5733
5753
  function untilAborted(signal) {
@@ -5741,6 +5761,7 @@ function untilAborted(signal) {
5741
5761
  }
5742
5762
  //#endregion
5743
5763
  //#region ../agent-cli/dist/clock.js
5764
+ const MS_PER_S = 1e3;
5744
5765
  const realClock = {
5745
5766
  now: () => Date.now(),
5746
5767
  sleep: (ms, signal) => new Promise((resolve, reject) => {
@@ -6098,12 +6119,152 @@ function lastLines(output, count) {
6098
6119
  return output.trim().split("\n").slice(-count).join("\n");
6099
6120
  }
6100
6121
  //#endregion
6122
+ //#region ../agent-cli/dist/context/fetch.js
6123
+ const UNREACHABLE = "UNREACHABLE";
6124
+ const UNAVAILABLE = "UNAVAILABLE";
6125
+ const UNANSWERED = "UNANSWERED";
6126
+ /** How long a request may take, body included, when the Command gives no `timeoutMs`. */
6127
+ const FETCH_TIMEOUT_MS = 3e4;
6128
+ const HTTP_REQUEST_TIMEOUT = 408;
6129
+ const HTTP_TOO_MANY_REQUESTS = 429;
6130
+ const HTTP_SERVER_ERROR = 500;
6131
+ const HTTP_SERVICE_UNAVAILABLE = 503;
6132
+ const NOT_SENT_CODES = /* @__PURE__ */ new Set([
6133
+ "ECONNREFUSED",
6134
+ "ENOTFOUND",
6135
+ "EAI_AGAIN",
6136
+ "EHOSTUNREACH",
6137
+ "ENETUNREACH",
6138
+ "UND_ERR_CONNECT_TIMEOUT"
6139
+ ]);
6140
+ const ONCE_METHODS = /* @__PURE__ */ new Set(["POST", "PATCH"]);
6141
+ function headersOf(input, init) {
6142
+ return new Headers(init.headers ?? (input instanceof Request ? input.headers : void 0));
6143
+ }
6144
+ function methodOf(input, init) {
6145
+ return (init.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
6146
+ }
6147
+ /** The `check` of a request that must not be resent, or `undefined` for one that may be. */
6148
+ function onceOf(method, once) {
6149
+ if (once === false) return void 0;
6150
+ return once ?? (ONCE_METHODS.has(method) ? {} : void 0);
6151
+ }
6152
+ function originOf$1(input) {
6153
+ return new URL(input instanceof Request ? input.url : input).origin;
6154
+ }
6155
+ /** 5xx, 408 and 429: the server cannot answer now, whatever the request. */
6156
+ function isUnavailable(status) {
6157
+ return status === HTTP_REQUEST_TIMEOUT || status === HTTP_TOO_MANY_REQUESTS || status >= HTTP_SERVER_ERROR;
6158
+ }
6159
+ /** 408 and every 5xx but 503: the server or a gateway failed on a request it may have applied. */
6160
+ function isUnanswered(status) {
6161
+ return status === HTTP_REQUEST_TIMEOUT || status >= HTTP_SERVER_ERROR && status !== HTTP_SERVICE_UNAVAILABLE;
6162
+ }
6163
+ function retryAtOf(header, clock) {
6164
+ const value = header?.trim();
6165
+ if (value === void 0 || value === "") return void 0;
6166
+ const at = /^\d+$/.test(value) ? clock.now() + Number(value) * MS_PER_S : Date.parse(value);
6167
+ return Number.isNaN(at) ? void 0 : new Date(at).toISOString();
6168
+ }
6169
+ function reasonOf(error) {
6170
+ return error instanceof Error && error.cause instanceof Error ? error.cause : error;
6171
+ }
6172
+ function wasNotSent(error) {
6173
+ const reason = reasonOf(error);
6174
+ return reason instanceof Error && "code" in reason && NOT_SENT_CODES.has(reason.code);
6175
+ }
6176
+ function unreachable(origin, error, rerun) {
6177
+ return new CliError({
6178
+ code: UNREACHABLE,
6179
+ message: `could not reach ${origin}: ${messageOf(reasonOf(error))}`,
6180
+ hint: `check the network and that ${origin} is up, then run the Next step`,
6181
+ details: { origin },
6182
+ next: [rerun]
6183
+ }, { cause: error });
6184
+ }
6185
+ function unavailable(origin, response, scope) {
6186
+ const { status } = response;
6187
+ const retryAt = retryAtOf(response.headers.get("retry-after"), scope.clock);
6188
+ const when = retryAt === void 0 ? "in a minute" : "at retryAt";
6189
+ return new CliError({
6190
+ code: UNAVAILABLE,
6191
+ message: `${origin} answered ${status}: it cannot take requests now`,
6192
+ hint: `${origin} is down or busy, not your request: run the Next step ${when}`,
6193
+ details: {
6194
+ origin,
6195
+ status
6196
+ },
6197
+ retryAt,
6198
+ next: [scope.rerun]
6199
+ });
6200
+ }
6201
+ function unanswered({ origin, method, once }, status, cause) {
6202
+ const check = once?.check;
6203
+ const what = `a ${method} request it may have applied`;
6204
+ return new CliError({
6205
+ code: UNANSWERED,
6206
+ message: status === void 0 ? `${origin} gave no answer to ${what}` : `${origin} answered ${status} to ${what}`,
6207
+ hint: check === void 0 ? `${origin} may have applied it: ask whoever runs ${origin} whether it took before sending it again` : `${origin} may have applied it: run the Next step to see whether it took before sending it again`,
6208
+ details: {
6209
+ origin,
6210
+ status
6211
+ },
6212
+ next: check === void 0 ? [] : [check]
6213
+ }, { cause });
6214
+ }
6215
+ /** What a request that got no answer fails with; `bound` is the Runtime's part of `signal`. */
6216
+ function noAnswer(error, sent, { bound, signal }, rerun) {
6217
+ if (sent.once !== void 0 && bound.aborted) return unanswered(sent, void 0, error);
6218
+ if (signal.aborted) return error;
6219
+ if (sent.once !== void 0 && !wasNotSent(error)) return unanswered(sent, void 0, error);
6220
+ return unreachable(sent.origin, error, rerun);
6221
+ }
6222
+ /** What an answer the Command must not get fails with, or `undefined` for one it gets. */
6223
+ function refusal$1(response, sent, scope) {
6224
+ if (sent.once !== void 0 && isUnanswered(response.status)) return unanswered(sent, response.status);
6225
+ return isUnavailable(response.status) ? unavailable(sent.origin, response, scope) : void 0;
6226
+ }
6227
+ function contextFetch(scope) {
6228
+ return async (input, { timeoutMs = FETCH_TIMEOUT_MS, once, ignoreStop, ...init } = {}) => {
6229
+ const method = methodOf(input, init);
6230
+ const sent = {
6231
+ origin: originOf$1(input),
6232
+ method,
6233
+ once: onceOf(method, once)
6234
+ };
6235
+ const headers = headersOf(input, init);
6236
+ if (!headers.has("user-agent")) headers.set("user-agent", scope.userAgent);
6237
+ const bound = scope.deadline(timeoutMs, ignoreStop === true ? { ignoreStop } : {});
6238
+ const signal = init.signal == null ? bound : AbortSignal.any([bound, init.signal]);
6239
+ signal.throwIfAborted();
6240
+ let response;
6241
+ try {
6242
+ response = await scope.fetch(input, {
6243
+ ...init,
6244
+ headers,
6245
+ signal
6246
+ });
6247
+ } catch (error) {
6248
+ throw noAnswer(error, sent, {
6249
+ bound,
6250
+ signal
6251
+ }, scope.rerun);
6252
+ }
6253
+ const failure = refusal$1(response, sent, scope);
6254
+ if (failure === void 0) return response;
6255
+ await response.body?.cancel();
6256
+ throw failure;
6257
+ };
6258
+ }
6259
+ //#endregion
6101
6260
  //#region ../agent-cli/dist/context/interrupts.js
6102
6261
  const INTERRUPTED = "INTERRUPTED";
6103
6262
  const DEADLINE_EXCEEDED = "DEADLINE_EXCEEDED";
6104
6263
  /** How long an interrupted Command may take to settle before the run ends without it. */
6105
6264
  const GRACE_MS = 3e3;
6106
6265
  const GRACE_OVER = Symbol("grace over");
6266
+ /** The codes a run ends with although it was stopped, since they say more than the stop does. */
6267
+ const OUTRANKS_STOP = /* @__PURE__ */ new Set([INTERRUPTED, UNANSWERED]);
6107
6268
  function interruptedError(rerun) {
6108
6269
  return new CliError({
6109
6270
  code: INTERRUPTED,
@@ -6203,12 +6364,13 @@ var RunControl = class {
6203
6364
  }
6204
6365
  /**
6205
6366
  * The error a run ends with: an interrupt or the run deadline outranks what the Command threw,
6206
- * unless the Command threw its own `INTERRUPTED`, saying what it finished before it stopped.
6367
+ * unless the Command threw its own `INTERRUPTED`, saying what it finished before it stopped, or
6368
+ * `ctx.fetch` threw `UNANSWERED`, since a rerun would send its request twice.
6207
6369
  * Otherwise each leaf that is not a `CliError` and whose cause chain holds a deadline's abort is
6208
6370
  * reported as that abort, so a declared error keeps its own code.
6209
6371
  */
6210
6372
  errorAfter(error) {
6211
- if (this.signal.aborted) return error instanceof CliError && error.code === "INTERRUPTED" ? error : this.signal.reason;
6373
+ if (this.signal.aborted) return error instanceof CliError && OUTRANKS_STOP.has(error.code) ? error : this.signal.reason;
6212
6374
  const leaves = errorsOf(error).map((leaf) => this.#abortIn(leaf) ?? leaf);
6213
6375
  return leaves.length === 1 ? leaves[0] : new AggregateError(leaves);
6214
6376
  }
@@ -6868,7 +7030,7 @@ const SEPARATOR = ",";
6868
7030
  const COLUMN_SEPARATOR = " ";
6869
7031
  const UNSAFE_IN_COLUMN = /[\t\n\r]/;
6870
7032
  const PAGE_INPUT = object({
6871
- limit: number().int().positive().default(DEFAULT_PAGE_LIMIT),
7033
+ limit: number$1().int().positive().default(DEFAULT_PAGE_LIMIT),
6872
7034
  cursor: string().min(1).optional()
6873
7035
  });
6874
7036
  var Page = class {
@@ -7029,6 +7191,17 @@ const FORCE_FLAG = standardFlag("--force", {
7029
7191
  takes: "nothing",
7030
7192
  schema: boolean()
7031
7193
  });
7194
+ const WAIT_SECONDS = number().int().nonnegative();
7195
+ const WAIT_FLAG = standardFlag("--wait", {
7196
+ placeholder: "<seconds>",
7197
+ description: "seconds to wait for a pending Approval to be approved",
7198
+ takes: "value",
7199
+ schema: WAIT_SECONDS
7200
+ });
7201
+ /** Whether `--wait` is a Standard flag of the Command: it is of one that declares a Login. */
7202
+ function takesWait(command) {
7203
+ return (command.logins ?? []).length > 0;
7204
+ }
7032
7205
  const EFFECT_FLAGS = {
7033
7206
  read: [JSON_FLAG],
7034
7207
  act: [JSON_FLAG],
@@ -7048,7 +7221,7 @@ const RESERVED = new Map([
7048
7221
  ...LIST_FLAGS
7049
7222
  ].map((flag) => [nameOf$1(flag), flag]));
7050
7223
  /** The Standard flags of a Command with this Effect and declarations, and of a List Command. */
7051
- function standardFlagsFor(effect, { outputs, force, cost }, list) {
7224
+ function standardFlagsFor(effect, { outputs, force, cost, wait }, list) {
7052
7225
  const forceFlag = force === void 0 ? FORCE_FLAG : {
7053
7226
  ...FORCE_FLAG,
7054
7227
  description: force
@@ -7057,19 +7230,22 @@ function standardFlagsFor(effect, { outputs, force, cost }, list) {
7057
7230
  ...EFFECT_FLAGS[effect],
7058
7231
  ...outputs || force !== void 0 ? [forceFlag] : [],
7059
7232
  ...cost ? [YES_FLAG] : [],
7233
+ ...wait ? [WAIT_FLAG] : [],
7060
7234
  ...list?.standardFlags ?? []
7061
7235
  ];
7062
7236
  }
7063
7237
  /** Throws when the Command declares an arg or option under a Standard flag's name. */
7064
7238
  function checkNoStandardFlags(command, label) {
7065
- const lines = [...argFields(command.args).map(({ key }) => ({
7239
+ const declared = [...argFields(command.args).map(({ key }) => ({
7066
7240
  kind: "arg",
7067
7241
  key
7068
7242
  })), ...optionFields(command.options).map(({ key }) => ({
7069
7243
  kind: "option",
7070
7244
  key
7071
- }))].flatMap(({ kind, key }) => {
7072
- const flag = RESERVED.get(kebab(key));
7245
+ }))];
7246
+ const wait = takesWait(command);
7247
+ const lines = declared.flatMap(({ kind, key }) => {
7248
+ const flag = RESERVED.get(kebab(key)) ?? (wait && kebab(key) === nameOf$1(WAIT_FLAG.flag) ? WAIT_FLAG.flag : void 0);
7073
7249
  return flag === void 0 ? [] : [` ${kind} '${key}' is the Standard flag ${flag}`];
7074
7250
  });
7075
7251
  if (lines.length > 0) throw new Error([`Command '${label}' declares Standard flags the Runtime adds; rename them:`, ...lines].join("\n"));
@@ -7508,7 +7684,7 @@ function readText(path, fileError) {
7508
7684
  });
7509
7685
  }
7510
7686
  }
7511
- function parsed(path, text, schema, rerun) {
7687
+ function parsed$1(path, text, schema, rerun) {
7512
7688
  let json;
7513
7689
  try {
7514
7690
  json = JSON.parse(text);
@@ -7524,7 +7700,7 @@ function projectFrom(projectFile, folder, scope) {
7524
7700
  const text = readText(path, scope.fileError);
7525
7701
  if (text !== void 0) return {
7526
7702
  root: folder,
7527
- settings: parsed(path, text, projectFile.schema, scope.rerun)
7703
+ settings: parsed$1(path, text, projectFile.schema, scope.rerun)
7528
7704
  };
7529
7705
  const parent = dirname(folder);
7530
7706
  return parent === folder ? void 0 : projectFrom(projectFile, parent, scope);
@@ -7633,6 +7809,70 @@ function secretRows(secrets, commands) {
7633
7809
  }];
7634
7810
  }
7635
7811
  //#endregion
7812
+ //#region ../agent-cli/dist/login/errors.js
7813
+ const LOGIN_REQUIRED = "LOGIN_REQUIRED";
7814
+ const APPROVAL_PENDING = "APPROVAL_PENDING";
7815
+ const APPROVAL_DENIED = "APPROVAL_DENIED";
7816
+ const APPROVAL_EXPIRED = "APPROVAL_EXPIRED";
7817
+ const LOGIN_REJECTED = "LOGIN_REJECTED";
7818
+ function loginStep(name) {
7819
+ return ["login", name];
7820
+ }
7821
+ /** Fails a Command whose Logins are found neither as a Secret nor stored. */
7822
+ function loginRequired(names, rerun) {
7823
+ const listed = names.join(", ");
7824
+ return new CliError({
7825
+ code: LOGIN_REQUIRED,
7826
+ message: `not signed in to ${listed}`,
7827
+ hint: "run the Next steps in order: the person who runs this CLI approves a code in a browser, then the Command runs again",
7828
+ details: { logins: names },
7829
+ next: [...names.map(loginStep), rerun]
7830
+ });
7831
+ }
7832
+ /** The wait ran out before the person approved: the same Approval stays pending for the rerun. */
7833
+ function approvalPending(name, approval, rerun) {
7834
+ const { verificationUri, userCode, verificationUriComplete } = approval;
7835
+ return new CliError({
7836
+ code: APPROVAL_PENDING,
7837
+ message: `signing in to ${name} waits for the code ${userCode} to be approved at ${verificationUriComplete ?? verificationUri}`,
7838
+ hint: "the person sees only your reply: write the link and the code in it, then run the Next step, which waits for the approval",
7839
+ details: {
7840
+ verificationUri,
7841
+ userCode,
7842
+ ...verificationUriComplete === void 0 ? {} : { verificationUriComplete }
7843
+ },
7844
+ next: [rerun]
7845
+ });
7846
+ }
7847
+ function approvalDenied(name) {
7848
+ return new CliError({
7849
+ code: APPROVAL_DENIED,
7850
+ message: `the person refused to sign in to ${name}`,
7851
+ hint: "ask the person whether to sign in, and run the Next step only if they agree",
7852
+ next: [loginStep(name)]
7853
+ });
7854
+ }
7855
+ /** A Command's `LOGIN_REJECTED` of a token from a Secret, which only the operator can replace. */
7856
+ function secretRejected(name, secret, rejected) {
7857
+ return new CliError({
7858
+ code: LOGIN_REJECTED,
7859
+ message: rejected.message,
7860
+ hint: `the server refused the token in ${secret.name}: ask the person who runs this CLI to set ${secret.name} to a valid token from ${secret.get}, or to unset it so the CLI signs in through a browser`,
7861
+ details: {
7862
+ login: name,
7863
+ secret: secret.name
7864
+ }
7865
+ }, { cause: rejected });
7866
+ }
7867
+ function approvalExpired(name) {
7868
+ return new CliError({
7869
+ code: APPROVAL_EXPIRED,
7870
+ message: `the code to sign in to ${name} expired before it was approved`,
7871
+ hint: "run the Next step for a new code, and pass its link and code to the person",
7872
+ next: [loginStep(name)]
7873
+ });
7874
+ }
7875
+ //#endregion
7636
7876
  //#region ../agent-cli/dist/runtime-codes.js
7637
7877
  const DOCTOR_PROBLEMS = "DOCTOR_PROBLEMS";
7638
7878
  const NOT_GLOBAL_INSTALL = "NOT_GLOBAL_INSTALL";
@@ -7642,6 +7882,7 @@ const REGISTRY_AUTH = "REGISTRY_AUTH";
7642
7882
  const INSTALL_FAILED = "INSTALL_FAILED";
7643
7883
  const NPM_FAILED = "NPM_FAILED";
7644
7884
  const NO_LATEST = "NO_LATEST";
7885
+ const RELEASE_TOO_OLD = "RELEASE_TOO_OLD";
7645
7886
  /** The Runtime codes any Command can meet, which no Command declares. */
7646
7887
  const anyCommandErrors = {
7647
7888
  [INVALID_INPUT]: { class: "caller" },
@@ -7665,7 +7906,16 @@ const anyCommandErrors = {
7665
7906
  [TOOL_FAILED]: { class: "operator" },
7666
7907
  [TOOL_MISSING]: { class: "operator" },
7667
7908
  [SECRET_MISSING]: { class: "operator" },
7668
- [PROJECT_INVALID]: { class: "operator" }
7909
+ [PROJECT_INVALID]: { class: "operator" },
7910
+ [UNREACHABLE]: { class: "wait" },
7911
+ [UNAVAILABLE]: { class: "wait" },
7912
+ [UNANSWERED]: { class: "source" },
7913
+ [RELEASE_TOO_OLD]: { class: "caller" },
7914
+ [LOGIN_REQUIRED]: { class: "operator" },
7915
+ [APPROVAL_PENDING]: { class: "wait" },
7916
+ [APPROVAL_DENIED]: { class: "operator" },
7917
+ [APPROVAL_EXPIRED]: { class: "operator" },
7918
+ [LOGIN_REJECTED]: { class: "operator" }
7669
7919
  };
7670
7920
  /**
7671
7921
  * The Runtime codes only some Commands reach: each Command that throws one, Built-in or the CLI's
@@ -7700,7 +7950,8 @@ function mustDeclare(code, table) {
7700
7950
  //#endregion
7701
7951
  //#region ../agent-cli/dist/define-command.js
7702
7952
  /** Throws when the Command's declaration breaks a rule its type cannot express; `label` names it. */
7703
- function checkCommand(command, label, table) {
7953
+ function checkCommand(command, label, table, logins) {
7954
+ checkLogins(command.logins ?? [], label, logins);
7704
7955
  checkNoStandardFlags(command, label);
7705
7956
  checkForce(command, label);
7706
7957
  checkArrayArgLast(label, command.args);
@@ -7708,6 +7959,10 @@ function checkCommand(command, label, table) {
7708
7959
  checkNoBooleanArrayOption(label, command.options);
7709
7960
  checkErrors(command.errors ?? [], label, table);
7710
7961
  }
7962
+ function checkLogins(names, label, logins) {
7963
+ const unknown = names.filter((name) => !Object.hasOwn(logins, name));
7964
+ if (unknown.length > 0) throw new Error(`${label} declares the Login ${unknown.join(", ")}, which the CLI does not declare in logins`);
7965
+ }
7711
7966
  /** Throws on a code in `errors` that is neither in `table` nor a Runtime code some Commands declare. */
7712
7967
  function checkErrors(errors, label, table) {
7713
7968
  const unknown = errors.filter((code) => !mustDeclare(code, table));
@@ -7744,13 +7999,214 @@ function cliErrorOf(code, init, options) {
7744
7999
  }, options);
7745
8000
  }
7746
8001
  //#endregion
8002
+ //#region ../agent-cli/dist/login/store.js
8003
+ const storedLoginSchema = object({
8004
+ accessToken: string(),
8005
+ refreshToken: string().optional(),
8006
+ expiresAt: datetime().optional()
8007
+ });
8008
+ const approvalSchema = object({
8009
+ deviceCode: string(),
8010
+ userCode: string(),
8011
+ verificationUri: string(),
8012
+ verificationUriComplete: string().optional(),
8013
+ expiresAt: datetime(),
8014
+ /** Seconds between polls of the token endpoint. */
8015
+ interval: number$1()
8016
+ });
8017
+ const KEY_LENGTH = 16;
8018
+ function keyOf({ tokenEndpoint, clientId }) {
8019
+ return createHash("sha256").update(`${tokenEndpoint}\n${clientId}`).digest("hex").slice(0, KEY_LENGTH);
8020
+ }
8021
+ function loginFilesOf(userFile, login) {
8022
+ const key = keyOf(login);
8023
+ return {
8024
+ stored: userFile(`login-${key}`, storedLoginSchema),
8025
+ approval: userFile(`approval-${key}`, approvalSchema)
8026
+ };
8027
+ }
8028
+ /** The file's value, or `undefined` once its `expiresAt` has passed, removing the file then. */
8029
+ async function readUnexpired(file, clock) {
8030
+ const value = await file.read();
8031
+ if (value?.expiresAt === void 0 || Date.parse(value.expiresAt) > clock.now()) return value;
8032
+ await file.remove();
8033
+ }
8034
+ /**
8035
+ * The stored Login, unless its access token expired with no refresh token to renew it, removing
8036
+ * the file then.
8037
+ */
8038
+ async function readStored(file, clock) {
8039
+ const stored = await file.read();
8040
+ return stored?.refreshToken === void 0 ? await readUnexpired(file, clock) : stored;
8041
+ }
8042
+ //#endregion
8043
+ //#region ../agent-cli/dist/login/token-endpoint.js
8044
+ const tokenSchema = object({
8045
+ access_token: string(),
8046
+ refresh_token: string().optional(),
8047
+ expires_in: number$1().optional()
8048
+ });
8049
+ const errorSchema = object({ error: string() });
8050
+ function isoAfter(clock, seconds) {
8051
+ return new Date(clock.now() + seconds * MS_PER_S).toISOString();
8052
+ }
8053
+ /** POSTs `form` to an OAuth endpoint and parses its JSON answer, whatever its status. */
8054
+ async function postForm(fetch, url, form, { ignoreStop } = {}) {
8055
+ const response = await fetch(url, {
8056
+ method: "POST",
8057
+ once: false,
8058
+ ...ignoreStop === void 0 ? {} : { ignoreStop },
8059
+ headers: { accept: "application/json" },
8060
+ body: new URLSearchParams(form)
8061
+ });
8062
+ const text = await response.text();
8063
+ try {
8064
+ return JSON.parse(text);
8065
+ } catch (error) {
8066
+ throw new Error(`${url} answered ${response.status} with a body that is not JSON`, { cause: error });
8067
+ }
8068
+ }
8069
+ function parsedAnswer(schema, body, url) {
8070
+ const parsed = schema.safeParse(body);
8071
+ if (!parsed.success) throw new Error(`${url} answered ${JSON.stringify(body)}, not an OAuth answer`);
8072
+ return parsed.data;
8073
+ }
8074
+ function storedLoginOf({ access_token, refresh_token, expires_in }, clock) {
8075
+ return {
8076
+ accessToken: access_token,
8077
+ ...refresh_token === void 0 ? {} : { refreshToken: refresh_token },
8078
+ ...expires_in === void 0 ? {} : { expiresAt: isoAfter(clock, expires_in) }
8079
+ };
8080
+ }
8081
+ /** Whether the stored Login has a refresh token and its access token expires within the margin. */
8082
+ function nearExpiry({ refreshToken, expiresAt }, clock) {
8083
+ return refreshToken !== void 0 && expiresAt !== void 0 && Date.parse(expiresAt) - clock.now() < 3e5;
8084
+ }
8085
+ /**
8086
+ * Refreshes the stored Login per RFC 6749 §6 under `ctx.runToEnd`, so a single-use refresh token is
8087
+ * never spent without its successor stored. `invalid_grant` removes the stored Login and gives `undefined`.
8088
+ */
8089
+ async function refreshed(name, login, file, refreshToken, ctx) {
8090
+ ctx.signal.throwIfAborted();
8091
+ const form = {
8092
+ grant_type: "refresh_token",
8093
+ refresh_token: refreshToken,
8094
+ client_id: login.clientId
8095
+ };
8096
+ return await ctx.runToEnd(`refreshing the Login ${name}`, async () => {
8097
+ const body = await postForm(ctx.fetch, login.tokenEndpoint, form, { ignoreStop: true });
8098
+ const granted = tokenSchema.safeParse(body);
8099
+ if (granted.success) {
8100
+ const stored = {
8101
+ refreshToken,
8102
+ ...storedLoginOf(granted.data, ctx.clock)
8103
+ };
8104
+ await file.write(stored);
8105
+ return stored;
8106
+ }
8107
+ const { error } = parsedAnswer(errorSchema, body, login.tokenEndpoint);
8108
+ if (error !== "invalid_grant") throw new Error(`${login.tokenEndpoint} refused the refresh of ${name} with ${error}`);
8109
+ await file.remove();
8110
+ });
8111
+ }
8112
+ //#endregion
8113
+ //#region ../agent-cli/dist/login/token.js
8114
+ function setSecretOf(login, secret) {
8115
+ const name = login.secret?.name;
8116
+ const found = name === void 0 ? void 0 : secret(name);
8117
+ return name === void 0 || found === void 0 ? void 0 : {
8118
+ name,
8119
+ secret: found
8120
+ };
8121
+ }
8122
+ function secretTokenOf(login, scope) {
8123
+ const set = setSecretOf(login, scope.secret);
8124
+ return set && {
8125
+ value: set.secret.value,
8126
+ source: {
8127
+ kind: "secret",
8128
+ name: set.name
8129
+ }
8130
+ };
8131
+ }
8132
+ function storedToken({ accessToken }) {
8133
+ return {
8134
+ value: accessToken,
8135
+ source: { kind: "stored" }
8136
+ };
8137
+ }
8138
+ function unexpired({ expiresAt }, clock) {
8139
+ return expiresAt === void 0 || Date.parse(expiresAt) > clock.now();
8140
+ }
8141
+ /**
8142
+ * The Login's token without sending anything: its Secret's value when set, else the stored Login's
8143
+ * while its access token has not expired.
8144
+ */
8145
+ async function currentTokenOf(login, scope) {
8146
+ const fromSecret = secretTokenOf(login, scope);
8147
+ if (fromSecret !== void 0) return fromSecret;
8148
+ const stored = await readStored(loginFilesOf(scope.userFile, login).stored, scope.clock);
8149
+ return stored && unexpired(stored, scope.clock) ? storedToken(stored) : void 0;
8150
+ }
8151
+ /** The Login's token: its Secret's value when set, else the stored Login's, refreshed near expiry. */
8152
+ async function freshTokenOf(name, login, ctx) {
8153
+ const fromSecret = secretTokenOf(login, tokenScopeOf(ctx));
8154
+ if (fromSecret !== void 0) return fromSecret;
8155
+ const file = loginFilesOf(ctx.userFile, login).stored;
8156
+ const stored = await readStored(file, ctx.clock);
8157
+ if (stored?.refreshToken === void 0 || !nearExpiry(stored, ctx.clock)) return stored && storedToken(stored);
8158
+ const renewed = await refreshed(name, login, file, stored.refreshToken, ctx);
8159
+ return renewed && storedToken(renewed);
8160
+ }
8161
+ function tokenScopeOf(ctx) {
8162
+ const { env, envFile, fileError } = ctx;
8163
+ return {
8164
+ secret: (name) => secretOf({
8165
+ env,
8166
+ envFile,
8167
+ fileError
8168
+ }, name),
8169
+ userFile: ctx.userFile,
8170
+ clock: ctx.clock
8171
+ };
8172
+ }
8173
+ //#endregion
8174
+ //#region ../agent-cli/dist/login/doctor-rows.js
8175
+ function loginRow(name, login, runAs) {
8176
+ return {
8177
+ name: `login ${name}`,
8178
+ advisory: true,
8179
+ run: async (ctx) => {
8180
+ const set = setSecretOf(login, tokenScopeOf(ctx).secret);
8181
+ if (set !== void 0) return {
8182
+ state: "ok",
8183
+ message: `the token in ${set.name}, from ${originOf(set.secret)}`
8184
+ };
8185
+ if (await readStored(loginFilesOf(ctx.userFile, login).stored, ctx.clock) !== void 0) return {
8186
+ state: "ok",
8187
+ message: "signed in: a stored Login"
8188
+ };
8189
+ const secretName = login.secret?.name;
8190
+ return {
8191
+ state: "problem",
8192
+ message: `not signed in${secretName === void 0 ? "" : `, and ${secretName} is not set`}; a Command that needs ${name} fails until the person approves a code`,
8193
+ fix: lineOf(loginStep(name), runAs)
8194
+ };
8195
+ }
8196
+ };
8197
+ }
8198
+ /** One `doctor` row per Login: where its token comes from, and `login` as the fix with none. */
8199
+ function loginRows(logins, runAs) {
8200
+ return Object.entries(logins).map(([name, login]) => loginRow(name, login, runAs));
8201
+ }
8202
+ //#endregion
7747
8203
  //#region ../agent-cli/dist/version.js
7748
8204
  /** The bundler's stamp, absent when the CLI runs unbundled. Read per call, so a test can define it. */
7749
8205
  function buildStamp() {
7750
8206
  return {
7751
- "sha": "7f79c40",
8207
+ "sha": "7dd915f",
7752
8208
  "dirty": false,
7753
- "builtAt": "2026-11-09T07:03:37.000Z"
8209
+ "builtAt": "2026-11-10T03:40:31.000Z"
7754
8210
  };
7755
8211
  }
7756
8212
  /** The first line of `--version`: the version, and the commit and time of a stamped build. */
@@ -8105,95 +8561,330 @@ async function projectRootOf(files, cwd) {
8105
8561
  return (await lockfileRootOf(files, cwd))?.dir ?? cwd;
8106
8562
  }
8107
8563
  //#endregion
8108
- //#region ../agent-cli/dist/built-ins/install/run-as.js
8109
- /** The Run-as: the bare name, or `npx -q --no-install <bin>` for a Dependency install (ADR 0011). */
8110
- function runAsOf({ name, install }) {
8111
- return install?.mode === "dependency" ? `npx -q --no-install ${name}` : name;
8112
- }
8113
- //#endregion
8114
- //#region ../agent-cli/dist/built-ins/install/dependency.js
8115
- const LINES = {
8116
- pnpm: {
8117
- upgrade: (packages) => `pnpm up --latest ${packages.join(" ")}`,
8118
- add: (packages) => `pnpm add -D ${packages.join(" ")}`,
8119
- install: "pnpm install"
8120
- },
8121
- npm: {
8122
- upgrade: (packages) => `npm install ${packages.map((name) => `${name}@latest`).join(" ")}`,
8123
- add: (packages) => `npm install -D ${packages.join(" ")}`,
8124
- install: "npm install"
8125
- }
8126
- };
8127
- const packageSchema = object({ version: string() });
8128
- async function manifestListing(files, name, cwd, root) {
8129
- const dirs = ancestorsOf(cwd);
8130
- const top = root === void 0 ? dirs.length : dirs.indexOf(root.dir) + 1;
8131
- for (const dir of dirs.slice(0, top)) {
8132
- const manifest = await manifestIn(files, dir);
8133
- if (manifest?.dependencies?.[name] !== void 0 || manifest?.devDependencies?.[name] !== void 0) return join(dir, "package.json");
8134
- }
8564
+ //#region ../agent-cli/dist/built-ins/install/global-npm.js
8565
+ /** Where npm puts global packages under its global prefix. */
8566
+ function globalModulesDir(prefix, platform) {
8567
+ return platform === "win32" ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules");
8135
8568
  }
8136
- function versionIn(text) {
8137
- try {
8138
- return packageSchema.parse(JSON.parse(text)).version;
8139
- } catch (error) {
8140
- if (error instanceof SyntaxError || error instanceof ZodError) return { reason: messageOf(error) };
8141
- throw error;
8142
- }
8569
+ /** Whether `path` itself is a symlink, which a link in a folder above it does not make it. */
8570
+ async function isLink(files, path) {
8571
+ const real = await files.realPath(path);
8572
+ if (real === void 0) return false;
8573
+ const folder = await files.realPath(dirname(path));
8574
+ return folder === void 0 || real !== join(folder, basename(path));
8143
8575
  }
8144
- async function standingOf(files, install, bin, cwd, root) {
8145
- if (bin === void 0) return { kind: "source" };
8146
- for (const projectDir of ancestorsOf(cwd)) {
8147
- const folder = join(projectDir, "node_modules", install.package);
8148
- const manifest = join(folder, "package.json");
8149
- const text = await readIfAny(files, manifest);
8150
- if (text === void 0) continue;
8151
- const version = versionIn(text);
8152
- if (typeof version !== "string") return {
8153
- kind: "unreadable",
8154
- manifest,
8155
- ...version
8156
- };
8157
- const copy = {
8158
- projectDir,
8159
- realDir: await files.realPath(folder) ?? folder,
8160
- version
8161
- };
8162
- if (!copy.realDir.split(sep).includes("node_modules")) return {
8163
- kind: "linked",
8164
- copy
8165
- };
8166
- const runningFrom = await files.realPath(bin) ?? bin;
8167
- return isInside(copy.realDir, runningFrom) ? {
8168
- kind: "installed",
8169
- copy
8170
- } : {
8171
- kind: "other",
8172
- copy,
8173
- runningFrom
8174
- };
8175
- }
8176
- const manifest = await manifestListing(files, install.package, cwd, root);
8177
- return manifest === void 0 ? { kind: "missing" } : {
8178
- kind: "listed",
8179
- manifest
8180
- };
8576
+ function notGlobal(ctx, message) {
8577
+ return runtimeError({
8578
+ code: NOT_GLOBAL_INSTALL,
8579
+ message,
8580
+ hint: "install it by running the Next step, so its update Command can replace it",
8581
+ next: [wholeLine(setupCommandLine(ctx.registry))]
8582
+ });
8181
8583
  }
8182
- async function surveyDependency(install, bin, { files, cwd }) {
8183
- const root = await lockfileRootOf(files, cwd);
8584
+ /**
8585
+ * The global npm install this copy runs from, found by asking npm for its global prefix.
8586
+ * `bin` is the script that started the CLI; throws `NOT_GLOBAL_INSTALL` when it is not inside that install.
8587
+ */
8588
+ async function globalInstallOf(bin, ctx) {
8589
+ if (bin === void 0) throw notGlobal(ctx, `${ctx.cliName} runs from source, not from an npm install`);
8590
+ const prefix = await globalPrefix(ctx);
8591
+ const packageDir = join(globalModulesDir(prefix, ctx.platform), ctx.registry.package);
8592
+ const installed = await ctx.files.realPath(packageDir);
8593
+ const here = await ctx.files.realPath(bin) ?? bin;
8594
+ if (installed === void 0 || !isInside(installed, here)) throw notGlobal(ctx, `${ctx.cliName} runs from ${here}, not from npm's global install at ${packageDir}`);
8595
+ if (await isLink(ctx.files, packageDir)) throw notGlobal(ctx, `${ctx.cliName} runs from a link to ${installed} (npm link), not from an npm install`);
8184
8596
  return {
8185
- cwd,
8186
- root,
8187
- standing: await standingOf(files, install, bin, cwd, root)
8597
+ prefix,
8598
+ packageDir
8188
8599
  };
8189
8600
  }
8190
- function packagesOf(install) {
8191
- return [install.package, ...install.lockstep ?? []];
8601
+ const NPMJS = "https://registry.npmjs.org/";
8602
+ /** The flag that points npm at the CLI's registry; none for npmjs, npm's default. */
8603
+ function registryFlags({ package: name, registry }) {
8604
+ if (registry === NPMJS) return [];
8605
+ const scope = scopeOf(name);
8606
+ return [scope === void 0 ? `--registry=${registry}` : `--${scope}:registry=${registry}`];
8192
8607
  }
8193
- function isUnchecked(standing) {
8194
- return standing.kind === "source" || standing.kind === "linked";
8608
+ /** The line that sets a Global install up, run before the CLI is on the machine. */
8609
+ function setupLineOf(install) {
8610
+ return setupCommandLine(globalRegistry(install));
8195
8611
  }
8196
- function skippedFor$1(cli, install, standing) {
8612
+ function globalRegistry(install) {
8613
+ const { package: name, registry } = install;
8614
+ return {
8615
+ package: name,
8616
+ label: registry,
8617
+ flags: registryFlags(install),
8618
+ unreachableHint: "check the network or VPN",
8619
+ loginHint: `log in to ${registry} (\`npm login --registry=${registry}\`) or set its token in ~/.npmrc`,
8620
+ missingHint: `check that ${name} is published on ${registry}`
8621
+ };
8622
+ }
8623
+ /** npm for a Global install, run in the working directory. */
8624
+ function globalNpm(cli, install, ctx, launch) {
8625
+ return npmContext(cli, globalRegistry(install), ctx, launch, ctx.cwd);
8626
+ }
8627
+ //#endregion
8628
+ //#region ../agent-cli/dist/built-ins/install/release-check.js
8629
+ const CHECK_INTERVAL_MS = 864e5;
8630
+ const checkSchema = object({
8631
+ checkedAt: number$1(),
8632
+ latest: string().optional(),
8633
+ /** The highest release the CLI's server named, which started a check sooner. */
8634
+ named: string().optional(),
8635
+ error: string().optional()
8636
+ });
8637
+ const CHECK_SCRIPT = `
8638
+ const { spawnSync } = require("node:child_process");
8639
+ const { mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } = require("node:fs");
8640
+ const { tmpdir } = require("node:os");
8641
+ const { join } = require("node:path");
8642
+ const [file, checkedAt, previous, npm, ...args] = process.argv.slice(1);
8643
+ const windows = process.platform === "win32";
8644
+ const cache = mkdtempSync(join(tmpdir(), "release-check-"));
8645
+ const namedNow = () => {
8646
+ try {
8647
+ return JSON.parse(readFileSync(file, "utf8")).named;
8648
+ } catch {
8649
+ return undefined;
8650
+ }
8651
+ };
8652
+ const write = (check) => {
8653
+ const temp = file + "." + process.pid + ".tmp";
8654
+ const named = namedNow();
8655
+ writeFileSync(temp, JSON.stringify({ checkedAt: Number(checkedAt), named, ...check }));
8656
+ renameSync(temp, file);
8657
+ };
8658
+ const latestOf = (stdout) => {
8659
+ try {
8660
+ const parsed = JSON.parse(stdout);
8661
+ const latest = Array.isArray(parsed) ? parsed.at(-1) : parsed;
8662
+ return typeof latest === "string" && /^\\d+\\.\\d+\\.\\d+/.test(latest) ? latest : undefined;
8663
+ } catch {
8664
+ return undefined;
8665
+ }
8666
+ };
8667
+ // cmd.exe resolves %~dp0 against the working directory for a quoted batch name found on PATH, so
8668
+ // only a full path, which may hold a space, is quoted.
8669
+ const command = windows && /[\\\\/]/.test(npm) ? '"' + npm + '"' : npm;
8670
+ try {
8671
+ const answer = spawnSync(command, args, {
8672
+ encoding: "utf8",
8673
+ shell: windows,
8674
+ windowsHide: true,
8675
+ env: { ...process.env, npm_config_cache: join(cache, "cache"), npm_config_logs_max: "0" },
8676
+ });
8677
+ const latest = answer.status === 0 ? latestOf(answer.stdout) : undefined;
8678
+ if (latest !== undefined) {
8679
+ write({ latest });
8680
+ } else {
8681
+ const said = (answer.stderr || "").trim().split(/\\r?\\n/).slice(0, 5).join("; ");
8682
+ const error = answer.error ? answer.error.message : said || "npm answered " + answer.stdout.trim();
8683
+ write({ latest: previous || undefined, error });
8684
+ }
8685
+ } finally {
8686
+ rmSync(cache, { recursive: true, force: true });
8687
+ }
8688
+ `;
8689
+ function isOff(cliName, env) {
8690
+ return Boolean(env[cliVariable(cliName, "NO_RELEASE_CHECK")] || env.CI);
8691
+ }
8692
+ function cacheFileOf(cliName, env) {
8693
+ const cache = env.XDG_CACHE_HOME || join(env.HOME || env.USERPROFILE || homedir(), ".cache");
8694
+ return join(cache, cliName, "release-check.json");
8695
+ }
8696
+ function parsedCheck(text) {
8697
+ try {
8698
+ return checkSchema.safeParse(JSON.parse(text)).data;
8699
+ } catch {
8700
+ return;
8701
+ }
8702
+ }
8703
+ async function lastCheck(files, file) {
8704
+ const text = await readIfAny(files, file);
8705
+ return text === void 0 ? void 0 : parsedCheck(text);
8706
+ }
8707
+ async function startCheck(cli, install, file, last, named, launch, ctx) {
8708
+ const checkedAt = ctx.clock.now();
8709
+ const previous = last?.latest ?? "";
8710
+ await ctx.files.write(file, JSON.stringify({
8711
+ checkedAt,
8712
+ latest: last?.latest,
8713
+ named
8714
+ }));
8715
+ const npm = globalNpm(cli, install, ctx, launch);
8716
+ const { path, env } = await npmOf(npm);
8717
+ await ctx.spawnDetached(process.execPath, [
8718
+ "-e",
8719
+ CHECK_SCRIPT,
8720
+ file,
8721
+ String(checkedAt),
8722
+ previous,
8723
+ path,
8724
+ ...latestViewArgs(npm.registry)
8725
+ ], { env });
8726
+ }
8727
+ function debugLine(cli, ctx, text) {
8728
+ if (isDebug({
8729
+ env: ctx.env,
8730
+ cliName: cli.name
8731
+ })) ctx.progress(`release check failed: ${text}`);
8732
+ }
8733
+ const NO_RELEASE_CHECK = {
8734
+ notice: async () => {},
8735
+ latestRelease: async () => {}
8736
+ };
8737
+ function isHigher(version, than) {
8738
+ return than === void 0 || !isVersion(than) || compareVersions(version, than) > 0;
8739
+ }
8740
+ /**
8741
+ * Tells the caller of a newer release that an earlier Release check found, and starts the next
8742
+ * check once the last is a day old, or sooner when the CLI's server names a release higher than
8743
+ * any it named before (ADR 0019).
8744
+ */
8745
+ function releaseCheck(cli, install, runAs, launch) {
8746
+ const guarded = async (ctx, work) => {
8747
+ if (launch.builtIn || launch.bin === void 0 || cli.commands === void 0) return;
8748
+ if (isOff(cli.name, ctx.env)) return;
8749
+ try {
8750
+ await work();
8751
+ } catch (error) {
8752
+ if (errnoOf(error) === void 0 && !(error instanceof CliError)) throw error;
8753
+ debugLine(cli, ctx, messageOf(error));
8754
+ }
8755
+ };
8756
+ let startedInRun = false;
8757
+ let naming = Promise.resolve();
8758
+ const named = async (version, ctx) => {
8759
+ if (!isVersion(version) || !isHigher(version, cli.version)) return;
8760
+ const file = cacheFileOf(cli.name, ctx.env);
8761
+ const last = await lastCheck(ctx.files, file);
8762
+ if (!isHigher(version, last?.named)) return;
8763
+ if (startedInRun) {
8764
+ await ctx.files.write(file, JSON.stringify({
8765
+ ...last,
8766
+ named: version
8767
+ }));
8768
+ return;
8769
+ }
8770
+ await startCheck(cli, install, file, last, version, launch, ctx);
8771
+ startedInRun = true;
8772
+ };
8773
+ return {
8774
+ notice: (ctx) => guarded(ctx, async () => {
8775
+ startedInRun = await checkAndTell(cli, install, runAs, launch, ctx);
8776
+ }),
8777
+ latestRelease: (version, ctx) => {
8778
+ naming = naming.then(() => guarded(ctx, () => named(version, ctx)));
8779
+ return naming;
8780
+ }
8781
+ };
8782
+ }
8783
+ /** Whether it started a check. */
8784
+ async function checkAndTell(cli, install, runAs, launch, ctx) {
8785
+ const file = cacheFileOf(cli.name, ctx.env);
8786
+ const last = await lastCheck(ctx.files, file);
8787
+ if (last?.error !== void 0) debugLine(cli, ctx, last.error);
8788
+ const due = last === void 0 || ctx.clock.now() - last.checkedAt >= CHECK_INTERVAL_MS;
8789
+ if (due) await startCheck(cli, install, file, last, last?.named, launch, ctx);
8790
+ tell(cli, runAs, last, ctx);
8791
+ return due;
8792
+ }
8793
+ function tell(cli, runAs, last, ctx) {
8794
+ const latest = last?.latest;
8795
+ if (latest === void 0 || !isVersion(latest) || compareVersions(latest, cli.version) <= 0) return;
8796
+ ctx.notice(`${cli.name} ${latest} is out, this is ${cli.version}; run \`${runAs} update\``);
8797
+ }
8798
+ //#endregion
8799
+ //#region ../agent-cli/dist/built-ins/install/run-as.js
8800
+ /** The Run-as: the bare name, or `npx -q --no-install <bin>` for a Dependency install (ADR 0011). */
8801
+ function runAsOf({ name, install }) {
8802
+ return install?.mode === "dependency" ? `npx -q --no-install ${name}` : name;
8803
+ }
8804
+ //#endregion
8805
+ //#region ../agent-cli/dist/built-ins/install/dependency.js
8806
+ const LINES = {
8807
+ pnpm: {
8808
+ upgrade: (packages) => `pnpm up --latest ${packages.join(" ")}`,
8809
+ add: (packages) => `pnpm add -D ${packages.join(" ")}`,
8810
+ install: "pnpm install"
8811
+ },
8812
+ npm: {
8813
+ upgrade: (packages) => `npm install ${packages.map((name) => `${name}@latest`).join(" ")}`,
8814
+ add: (packages) => `npm install -D ${packages.join(" ")}`,
8815
+ install: "npm install"
8816
+ }
8817
+ };
8818
+ const packageSchema = object({ version: string() });
8819
+ async function manifestListing(files, name, cwd, root) {
8820
+ const dirs = ancestorsOf(cwd);
8821
+ const top = root === void 0 ? dirs.length : dirs.indexOf(root.dir) + 1;
8822
+ for (const dir of dirs.slice(0, top)) {
8823
+ const manifest = await manifestIn(files, dir);
8824
+ if (manifest?.dependencies?.[name] !== void 0 || manifest?.devDependencies?.[name] !== void 0) return join(dir, "package.json");
8825
+ }
8826
+ }
8827
+ function versionIn(text) {
8828
+ try {
8829
+ return packageSchema.parse(JSON.parse(text)).version;
8830
+ } catch (error) {
8831
+ if (error instanceof SyntaxError || error instanceof ZodError) return { reason: messageOf(error) };
8832
+ throw error;
8833
+ }
8834
+ }
8835
+ async function standingOf(files, install, bin, cwd, root) {
8836
+ if (bin === void 0) return { kind: "source" };
8837
+ for (const projectDir of ancestorsOf(cwd)) {
8838
+ const folder = join(projectDir, "node_modules", install.package);
8839
+ const manifest = join(folder, "package.json");
8840
+ const text = await readIfAny(files, manifest);
8841
+ if (text === void 0) continue;
8842
+ const version = versionIn(text);
8843
+ if (typeof version !== "string") return {
8844
+ kind: "unreadable",
8845
+ manifest,
8846
+ ...version
8847
+ };
8848
+ const copy = {
8849
+ projectDir,
8850
+ realDir: await files.realPath(folder) ?? folder,
8851
+ version
8852
+ };
8853
+ if (!copy.realDir.split(sep).includes("node_modules")) return {
8854
+ kind: "linked",
8855
+ copy
8856
+ };
8857
+ const runningFrom = await files.realPath(bin) ?? bin;
8858
+ return isInside(copy.realDir, runningFrom) ? {
8859
+ kind: "installed",
8860
+ copy
8861
+ } : {
8862
+ kind: "other",
8863
+ copy,
8864
+ runningFrom
8865
+ };
8866
+ }
8867
+ const manifest = await manifestListing(files, install.package, cwd, root);
8868
+ return manifest === void 0 ? { kind: "missing" } : {
8869
+ kind: "listed",
8870
+ manifest
8871
+ };
8872
+ }
8873
+ async function surveyDependency(install, bin, { files, cwd }) {
8874
+ const root = await lockfileRootOf(files, cwd);
8875
+ return {
8876
+ cwd,
8877
+ root,
8878
+ standing: await standingOf(files, install, bin, cwd, root)
8879
+ };
8880
+ }
8881
+ function packagesOf(install) {
8882
+ return [install.package, ...install.lockstep ?? []];
8883
+ }
8884
+ function isUnchecked(standing) {
8885
+ return standing.kind === "source" || standing.kind === "linked";
8886
+ }
8887
+ function skippedFor$1(cli, install, standing) {
8197
8888
  return {
8198
8889
  state: "skipped",
8199
8890
  message: standing.kind === "source" ? `not checked: ${cli.name} runs from source, not from an install` : `not checked: ${install.package} links to ${standing.copy.realDir}, so the workspace decides its version`
@@ -8269,83 +8960,24 @@ function checkOf$1(cli, install, runAs, launch) {
8269
8960
  npm: npmContext(cli, registryOf(install, root?.dir), ctx, launch, root?.dir ?? cwd),
8270
8961
  advise: (latest) => adviceFor(install, root, latest)
8271
8962
  };
8272
- }
8273
- };
8274
- }
8275
- /** The Install of a CLI each project pins as a dependency, run through npx (ADR 0011). */
8276
- function dependencyInstall(cli, install) {
8277
- const runAs = runAsOf(cli);
8278
- return {
8279
- runAs,
8280
- builtIns: () => ({}),
8281
- check: (launch) => checkOf$1(cli, install, runAs, launch),
8282
- notice: async () => {}
8283
- };
8284
- }
8285
- //#endregion
8286
- //#region ../agent-cli/dist/built-ins/install/global-npm.js
8287
- /** Where npm puts global packages under its global prefix. */
8288
- function globalModulesDir(prefix, platform) {
8289
- return platform === "win32" ? join(prefix, "node_modules") : join(prefix, "lib", "node_modules");
8290
- }
8291
- /** Whether `path` itself is a symlink, which a link in a folder above it does not make it. */
8292
- async function isLink(files, path) {
8293
- const real = await files.realPath(path);
8294
- if (real === void 0) return false;
8295
- const folder = await files.realPath(dirname(path));
8296
- return folder === void 0 || real !== join(folder, basename(path));
8297
- }
8298
- function notGlobal(ctx, message) {
8299
- return runtimeError({
8300
- code: NOT_GLOBAL_INSTALL,
8301
- message,
8302
- hint: "install it by running the Next step, so its update Command can replace it",
8303
- next: [wholeLine(setupCommandLine(ctx.registry))]
8304
- });
8305
- }
8306
- /**
8307
- * The global npm install this copy runs from, found by asking npm for its global prefix.
8308
- * `bin` is the script that started the CLI; throws `NOT_GLOBAL_INSTALL` when it is not inside that install.
8309
- */
8310
- async function globalInstallOf(bin, ctx) {
8311
- if (bin === void 0) throw notGlobal(ctx, `${ctx.cliName} runs from source, not from an npm install`);
8312
- const prefix = await globalPrefix(ctx);
8313
- const packageDir = join(globalModulesDir(prefix, ctx.platform), ctx.registry.package);
8314
- const installed = await ctx.files.realPath(packageDir);
8315
- const here = await ctx.files.realPath(bin) ?? bin;
8316
- if (installed === void 0 || !isInside(installed, here)) throw notGlobal(ctx, `${ctx.cliName} runs from ${here}, not from npm's global install at ${packageDir}`);
8317
- if (await isLink(ctx.files, packageDir)) throw notGlobal(ctx, `${ctx.cliName} runs from a link to ${installed} (npm link), not from an npm install`);
8318
- return {
8319
- prefix,
8320
- packageDir
8963
+ }
8321
8964
  };
8322
8965
  }
8323
- const NPMJS = "https://registry.npmjs.org/";
8324
- /** The flag that points npm at the CLI's registry; none for npmjs, npm's default. */
8325
- function registryFlags({ package: name, registry }) {
8326
- if (registry === NPMJS) return [];
8327
- const scope = scopeOf(name);
8328
- return [scope === void 0 ? `--registry=${registry}` : `--${scope}:registry=${registry}`];
8329
- }
8330
- /** The line that sets a Global install up, run before the CLI is on the machine. */
8331
- function setupLineOf(install) {
8332
- return setupCommandLine(globalRegistry(install));
8333
- }
8334
- function globalRegistry(install) {
8335
- const { package: name, registry } = install;
8966
+ /** The Install of a CLI each project pins as a dependency, run through npx (ADR 0011). */
8967
+ function dependencyInstall(cli, install) {
8968
+ const runAs = runAsOf(cli);
8336
8969
  return {
8337
- package: name,
8338
- label: registry,
8339
- flags: registryFlags(install),
8340
- unreachableHint: "check the network or VPN",
8341
- loginHint: `log in to ${registry} (\`npm login --registry=${registry}\`) or set its token in ~/.npmrc`,
8342
- missingHint: `check that ${name} is published on ${registry}`
8970
+ runAs,
8971
+ builtIns: () => ({}),
8972
+ check: (launch) => checkOf$1(cli, install, runAs, launch),
8973
+ releaseCheck: () => NO_RELEASE_CHECK,
8974
+ updateLine: async ({ files, cwd }) => {
8975
+ const root = await lockfileRootOf(files, cwd);
8976
+ const lines = root === void 0 ? void 0 : LINES[root.manager];
8977
+ return lines === void 0 ? void 0 : wholeLine(lines.upgrade(packagesOf(install)));
8978
+ }
8343
8979
  };
8344
8980
  }
8345
- /** npm for a Global install, run in the working directory. */
8346
- function globalNpm(cli, install, ctx, launch) {
8347
- return npmContext(cli, globalRegistry(install), ctx, launch, ctx.cwd);
8348
- }
8349
8981
  //#endregion
8350
8982
  //#region ../agent-cli/dist/built-ins/skill/sync.js
8351
8983
  async function walk$1(files, dir, inner) {
@@ -8826,121 +9458,6 @@ function updateCommand(cli, install, launch) {
8826
9458
  });
8827
9459
  }
8828
9460
  //#endregion
8829
- //#region ../agent-cli/dist/built-ins/install/release-check.js
8830
- const CHECK_INTERVAL_MS = 864e5;
8831
- const checkSchema = object({
8832
- checkedAt: number(),
8833
- latest: string().optional(),
8834
- error: string().optional()
8835
- });
8836
- const CHECK_SCRIPT = `
8837
- const { spawnSync } = require("node:child_process");
8838
- const { mkdtempSync, renameSync, rmSync, writeFileSync } = require("node:fs");
8839
- const { tmpdir } = require("node:os");
8840
- const { join } = require("node:path");
8841
- const [file, checkedAt, previous, npm, ...args] = process.argv.slice(1);
8842
- const windows = process.platform === "win32";
8843
- const cache = mkdtempSync(join(tmpdir(), "release-check-"));
8844
- const write = (check) => {
8845
- const temp = file + "." + process.pid + ".tmp";
8846
- writeFileSync(temp, JSON.stringify({ checkedAt: Number(checkedAt), ...check }));
8847
- renameSync(temp, file);
8848
- };
8849
- const latestOf = (stdout) => {
8850
- try {
8851
- const parsed = JSON.parse(stdout);
8852
- const latest = Array.isArray(parsed) ? parsed.at(-1) : parsed;
8853
- return typeof latest === "string" && /^\\d+\\.\\d+\\.\\d+/.test(latest) ? latest : undefined;
8854
- } catch {
8855
- return undefined;
8856
- }
8857
- };
8858
- try {
8859
- const answer = spawnSync(windows ? '"' + npm + '"' : npm, args, {
8860
- encoding: "utf8",
8861
- shell: windows,
8862
- windowsHide: true,
8863
- env: { ...process.env, npm_config_cache: join(cache, "cache"), npm_config_logs_max: "0" },
8864
- });
8865
- const latest = answer.status === 0 ? latestOf(answer.stdout) : undefined;
8866
- if (latest !== undefined) {
8867
- write({ latest });
8868
- } else {
8869
- const said = (answer.stderr || "").trim().split(/\\r?\\n/).slice(0, 5).join("; ");
8870
- const error = answer.error ? answer.error.message : said || "npm answered " + answer.stdout.trim();
8871
- write({ latest: previous || undefined, error });
8872
- }
8873
- } finally {
8874
- rmSync(cache, { recursive: true, force: true });
8875
- }
8876
- `;
8877
- function isOff(cliName, env) {
8878
- return Boolean(env[cliVariable(cliName, "NO_RELEASE_CHECK")] || env.CI);
8879
- }
8880
- function cacheFileOf(cliName, env) {
8881
- const cache = env.XDG_CACHE_HOME || join(env.HOME || env.USERPROFILE || homedir(), ".cache");
8882
- return join(cache, cliName, "release-check.json");
8883
- }
8884
- function parsedCheck(text) {
8885
- try {
8886
- return checkSchema.safeParse(JSON.parse(text)).data;
8887
- } catch {
8888
- return;
8889
- }
8890
- }
8891
- async function lastCheck(files, file) {
8892
- const text = await readIfAny(files, file);
8893
- return text === void 0 ? void 0 : parsedCheck(text);
8894
- }
8895
- async function startCheck(cli, install, file, last, launch, ctx) {
8896
- const checkedAt = ctx.clock.now();
8897
- const previous = last?.latest ?? "";
8898
- await ctx.files.write(file, JSON.stringify({
8899
- checkedAt,
8900
- latest: last?.latest
8901
- }));
8902
- const npm = globalNpm(cli, install, ctx, launch);
8903
- const { path, env } = await npmOf(npm);
8904
- await ctx.spawnDetached(process.execPath, [
8905
- "-e",
8906
- CHECK_SCRIPT,
8907
- file,
8908
- String(checkedAt),
8909
- previous,
8910
- path,
8911
- ...latestViewArgs(npm.registry)
8912
- ], { env });
8913
- }
8914
- function debugLine(cli, ctx, text) {
8915
- if (isDebug({
8916
- env: ctx.env,
8917
- cliName: cli.name
8918
- })) ctx.progress(`release check failed: ${text}`);
8919
- }
8920
- /**
8921
- * Tells the caller of a newer release that an earlier Release check found, and starts the next
8922
- * check once the last is a day old.
8923
- */
8924
- async function releaseCheck(cli, install, runAs, launch, ctx) {
8925
- if (launch.builtIn || launch.bin === void 0 || cli.commands === void 0) return;
8926
- if (isOff(cli.name, ctx.env)) return;
8927
- try {
8928
- await checkAndTell(cli, install, runAs, launch, ctx);
8929
- } catch (error) {
8930
- if (errnoOf(error) === void 0 && !(error instanceof CliError)) throw error;
8931
- debugLine(cli, ctx, messageOf(error));
8932
- }
8933
- }
8934
- async function checkAndTell(cli, install, runAs, launch, ctx) {
8935
- const file = cacheFileOf(cli.name, ctx.env);
8936
- const last = await lastCheck(ctx.files, file);
8937
- if (last?.error !== void 0) debugLine(cli, ctx, last.error);
8938
- if (last === void 0 || ctx.clock.now() - last.checkedAt >= CHECK_INTERVAL_MS) await startCheck(cli, install, file, last, launch, ctx);
8939
- const latest = last?.latest;
8940
- if (latest === void 0 || !isVersion(latest) || compareVersions(latest, cli.version) <= 0) return;
8941
- ctx.notice(`${cli.name} ${latest} is out, this is ${cli.version}; run \`${runAs} update\``);
8942
- }
8943
- //#endregion
8944
9461
  //#region ../agent-cli/dist/built-ins/install/global.js
8945
9462
  function checkOf(cli, install, launch) {
8946
9463
  return {
@@ -8978,13 +9495,13 @@ function globalInstall(cli, install) {
8978
9495
  update: updateCommand(cli, install, launch)
8979
9496
  }),
8980
9497
  check: (launch) => checkOf(cli, install, launch),
8981
- notice: (launch, ctx) => releaseCheck(cli, install, adapter.runAs, launch, ctx)
9498
+ releaseCheck: (launch) => releaseCheck(cli, install, adapter.runAs, launch),
9499
+ updateLine: async () => ["update"]
8982
9500
  };
8983
9501
  return adapter;
8984
9502
  }
8985
9503
  //#endregion
8986
9504
  //#region ../agent-cli/dist/built-ins/install/install.js
8987
- const noNotice = async () => {};
8988
9505
  function noInstall(cli) {
8989
9506
  const skipped = async () => ({
8990
9507
  state: "skipped",
@@ -8997,7 +9514,8 @@ function noInstall(cli) {
8997
9514
  install: skipped,
8998
9515
  release: async () => ({ skipped: await skipped() })
8999
9516
  }),
9000
- notice: noNotice
9517
+ releaseCheck: () => NO_RELEASE_CHECK,
9518
+ updateLine: async () => void 0
9001
9519
  };
9002
9520
  }
9003
9521
  function installOf(cli) {
@@ -9114,7 +9632,7 @@ const SECTION_VERBS = {
9114
9632
  add: "add the Agents section to",
9115
9633
  rewrite: "rewrite the Agents section in"
9116
9634
  };
9117
- function renderPlan(cli, plan) {
9635
+ function renderPlan$1(cli, plan) {
9118
9636
  const files = [
9119
9637
  ...plan.write.map((file) => ` write ${file}`),
9120
9638
  ...plan.replace.map((file) => ` replace ${file}`),
@@ -9168,7 +9686,7 @@ function skillInstallCommand(cli, folder, agents) {
9168
9686
  };
9169
9687
  },
9170
9688
  render: (data) => renderInstalled(cli, data),
9171
- renderPlan: (plan) => renderPlan(cli, plan)
9689
+ renderPlan: (plan) => renderPlan$1(cli, plan)
9172
9690
  });
9173
9691
  }
9174
9692
  //#endregion
@@ -9368,6 +9886,7 @@ function doctorChecks(cli, launch, scope) {
9368
9886
  ...cli.doctor ?? [],
9369
9887
  ...tools,
9370
9888
  ...secretRows(cli.secrets ?? [], cli.commands),
9889
+ ...loginRows(cli.logins ?? {}, scope.runAs),
9371
9890
  installRow(check),
9372
9891
  registryRow(cli, check),
9373
9892
  ...skillOf(cli, install).rows
@@ -9378,7 +9897,6 @@ function doctorChecks(cli, launch, scope) {
9378
9897
  //#endregion
9379
9898
  //#region ../agent-cli/dist/built-ins/doctor.js
9380
9899
  const DEFAULT_DEADLINE_MS = 1e4;
9381
- const MS_PER_SECOND = 1e3;
9382
9900
  const MIN_LABEL_WIDTH = 8;
9383
9901
  const reportSchema = object({
9384
9902
  rows: array(object({
@@ -9397,7 +9915,7 @@ const reportSchema = object({
9397
9915
  function problemOf(check, error, { signal, deadline, ms, runAs }) {
9398
9916
  if (!signal.aborted && deadline.aborted && error === deadline.reason) return {
9399
9917
  state: "problem",
9400
- message: `${check.name} did not answer within ${ms / MS_PER_SECOND} s`
9918
+ message: `${check.name} did not answer within ${ms / MS_PER_S} s`
9401
9919
  };
9402
9920
  return problemOfError(check.name, error, runAs);
9403
9921
  }
@@ -9532,17 +10050,338 @@ function doctorCommand(cli, launch) {
9532
10050
  };
9533
10051
  }
9534
10052
  //#endregion
10053
+ //#region ../agent-cli/dist/login/declared.js
10054
+ function declaredLogin(logins, name) {
10055
+ const login = logins[name];
10056
+ if (login === void 0) throw new Error(`${name} is not a Login the CLI declares`);
10057
+ return login;
10058
+ }
10059
+ //#endregion
10060
+ //#region ../agent-cli/dist/login/device-flow.js
10061
+ const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
10062
+ /** RFC 8628 §3.2: the interval when the server gives none. */
10063
+ const DEFAULT_INTERVAL_S = 5;
10064
+ /** RFC 8628 §3.5: what each `slow_down` adds to the interval. */
10065
+ const SLOW_DOWN_S = 5;
10066
+ const deviceSchema = object({
10067
+ device_code: string(),
10068
+ user_code: string(),
10069
+ verification_uri: string(),
10070
+ verification_uri_complete: string().optional(),
10071
+ expires_in: number$1(),
10072
+ interval: number$1().optional()
10073
+ });
10074
+ async function startApproval(login, { fetch, clock }) {
10075
+ const form = {
10076
+ client_id: login.clientId,
10077
+ ...login.scope === void 0 ? {} : { scope: login.scope }
10078
+ };
10079
+ const device = parsedAnswer(deviceSchema, await postForm(fetch, login.deviceEndpoint, form), login.deviceEndpoint);
10080
+ return {
10081
+ deviceCode: device.device_code,
10082
+ userCode: device.user_code,
10083
+ verificationUri: device.verification_uri,
10084
+ ...device.verification_uri_complete === void 0 ? {} : { verificationUriComplete: device.verification_uri_complete },
10085
+ expiresAt: isoAfter(clock, device.expires_in),
10086
+ interval: device.interval ?? DEFAULT_INTERVAL_S
10087
+ };
10088
+ }
10089
+ async function pollApproval(name, login, { approval, takenUp }, scope, signal) {
10090
+ const form = {
10091
+ grant_type: DEVICE_CODE_GRANT,
10092
+ device_code: approval.deviceCode,
10093
+ client_id: login.clientId
10094
+ };
10095
+ let intervalS = approval.interval;
10096
+ for (let first = true;; first = false) {
10097
+ if (!(first && takenUp)) await scope.clock.sleep(intervalS * MS_PER_S, signal);
10098
+ const body = await postForm(scope.fetch, login.tokenEndpoint, form);
10099
+ const granted = tokenSchema.safeParse(body);
10100
+ if (granted.success) return storedLoginOf(granted.data, scope.clock);
10101
+ const { error } = parsedAnswer(errorSchema, body, login.tokenEndpoint);
10102
+ if (error === "slow_down") intervalS += SLOW_DOWN_S;
10103
+ else if (error !== "authorization_pending") throw refusal(name, login, error);
10104
+ }
10105
+ }
10106
+ /** The error a token endpoint's answer other than pending or slow down ends the polling with. */
10107
+ function refusal(name, login, error) {
10108
+ if (error === "access_denied") return approvalDenied(name);
10109
+ if (error === "expired_token" || error === "invalid_grant") return approvalExpired(name);
10110
+ return /* @__PURE__ */ new Error(`${login.tokenEndpoint} refused the device code with ${error}`);
10111
+ }
10112
+ function endsApproval(error) {
10113
+ return error instanceof CliError && (error.code === "APPROVAL_DENIED" || error.code === "APPROVAL_EXPIRED");
10114
+ }
10115
+ /** Takes up the pending Approval, or asks for one and keeps it as a User file, and prints its code. */
10116
+ async function askedApproval(login, files, scope) {
10117
+ const pending = await readUnexpired(files.approval, scope.clock);
10118
+ const approval = pending ?? await startApproval(login, scope);
10119
+ if (pending === void 0) await files.approval.write(approval);
10120
+ scope.progress(`open ${approval.verificationUriComplete ?? approval.verificationUri} and approve code ${approval.userCode}`);
10121
+ return {
10122
+ approval,
10123
+ takenUp: pending !== void 0
10124
+ };
10125
+ }
10126
+ /** The `APPROVAL_PENDING` of the pending Approval, or of a new one, without polling it. */
10127
+ async function pendingApproval(name, login, files, scope, rerun) {
10128
+ const { approval } = await askedApproval(login, files, scope);
10129
+ return approvalPending(name, approval, rerun);
10130
+ }
10131
+ /**
10132
+ * Polls the pending Approval, or a new one, until the person approves, and stores the Login. A run
10133
+ * that stops first leaves the Approval for the next.
10134
+ */
10135
+ async function signIn(name, login, files, scope, { waitS, rerun }) {
10136
+ const asked = await askedApproval(login, files, scope);
10137
+ const wait = scope.deadline(waitS * MS_PER_S);
10138
+ let stored;
10139
+ try {
10140
+ stored = await pollApproval(name, login, asked, scope, wait);
10141
+ } catch (error) {
10142
+ if (wait.aborted && !scope.signal.aborted) throw approvalPending(name, asked.approval, rerun);
10143
+ if (endsApproval(error)) await files.approval.remove();
10144
+ throw error;
10145
+ }
10146
+ await files.stored.write(stored);
10147
+ await files.approval.remove();
10148
+ return stored;
10149
+ }
10150
+ //#endregion
10151
+ //#region ../agent-cli/dist/built-ins/login-name.js
10152
+ /** The Login a `login` or `logout` run names, or the only one; with several, the name is needed. */
10153
+ function chosenName(run, given, names) {
10154
+ const [only, ...others] = names;
10155
+ if (given !== void 0) return given;
10156
+ if (others.length === 0) return only;
10157
+ throw new CliError({
10158
+ code: INVALID_INPUT,
10159
+ message: `\`${run.cliName} ${run.command}\` needs the name of a Login: ${names.join(", ")}`,
10160
+ hint: "run the Next step for the Login the task needs",
10161
+ next: names.map((name) => [run.command, name])
10162
+ });
10163
+ }
10164
+ /** The optional `name` arg of `login` and `logout`; `purpose` reads as "the Login to <purpose>". */
10165
+ function nameArgs(names, purpose) {
10166
+ return object({ name: _enum(names).optional().describe(`the Login to ${purpose}, of ${names.join(", ")}; needed only with several`) });
10167
+ }
10168
+ /** The name an example passes: none with one Login, the first with several. */
10169
+ function exampleName(names) {
10170
+ return names.length === 1 ? [] : [names[0]];
10171
+ }
10172
+ //#endregion
10173
+ //#region ../agent-cli/dist/built-ins/logout.js
10174
+ const logoutSchema = object({
10175
+ login: string(),
10176
+ stored: _enum([
10177
+ "revoked",
10178
+ "removed",
10179
+ "none"
10180
+ ]),
10181
+ /** The Secret still set for this Login, which logout never touches. */
10182
+ secret: string().optional()
10183
+ });
10184
+ function renderLogout({ login, stored, secret }) {
10185
+ const head = stored === "none" ? `not signed in to ${login}: nothing to do` : `signed out of ${login}${stored === "revoked" ? ", and the server revoked its token" : ""}`;
10186
+ return secret === void 0 ? head : `${head}; ${login} still uses the token in ${secret}`;
10187
+ }
10188
+ function renderPlan({ login, stored, revokeEndpoint, secret }) {
10189
+ if (!stored) return renderLogout({
10190
+ login,
10191
+ stored: "none",
10192
+ ...secret === void 0 ? {} : { secret }
10193
+ });
10194
+ return `would sign out of ${login}${revokeEndpoint === void 0 ? "" : `, revoking its token at ${revokeEndpoint}`}`;
10195
+ }
10196
+ /**
10197
+ * RFC 7009 §2.1: revoking the refresh token ends the grant, so the server should drop its access
10198
+ * tokens too; a Login without one revokes its access token.
10199
+ */
10200
+ async function revoke(endpoint, { clientId }, { accessToken, refreshToken }, ctx) {
10201
+ const [token, hint] = refreshToken === void 0 ? [accessToken, "access_token"] : [refreshToken, "refresh_token"];
10202
+ const response = await ctx.fetch(endpoint, {
10203
+ method: "POST",
10204
+ once: false,
10205
+ body: new URLSearchParams({
10206
+ token,
10207
+ token_type_hint: hint,
10208
+ client_id: clientId
10209
+ })
10210
+ });
10211
+ if (!response.ok) throw new Error(`${endpoint} answered ${response.status} to the revocation of a token`);
10212
+ }
10213
+ /** The Built-in `logout`: revokes and removes the stored Login, never touching its Secret. */
10214
+ function logoutCommand(cli, logins, names) {
10215
+ const named = exampleName(names);
10216
+ return defineCommand$1.write({
10217
+ description: "sign out: revoke the stored Login and remove it",
10218
+ help: "Revokes the stored Login at the server when it has a revoke endpoint, then removes it for this user. A Secret set for the Login stays set, so the Commands keep using it. It does nothing when no Login is stored.",
10219
+ examples: [{
10220
+ command: [
10221
+ cli.name,
10222
+ "logout",
10223
+ ...named
10224
+ ].join(" "),
10225
+ note: "sign out"
10226
+ }],
10227
+ args: nameArgs(names, "sign out of"),
10228
+ output: logoutSchema,
10229
+ plan: async ({ name: given }, ctx) => {
10230
+ const name = chosenName({
10231
+ cliName: cli.name,
10232
+ command: "logout"
10233
+ }, given, names);
10234
+ const login = declaredLogin(logins, name);
10235
+ return {
10236
+ login: name,
10237
+ stored: await loginFilesOf(ctx.userFile, login).stored.read() !== void 0,
10238
+ revokeEndpoint: login.revokeEndpoint,
10239
+ secret: setSecretOf(login, tokenScopeOf(ctx).secret)?.name
10240
+ };
10241
+ },
10242
+ apply: async ({ login: name, secret }, ctx) => {
10243
+ const login = declaredLogin(logins, name);
10244
+ const file = loginFilesOf(ctx.userFile, login).stored;
10245
+ const stored = await file.read();
10246
+ const kept = secret === void 0 ? {} : { secret };
10247
+ if (stored === void 0) return {
10248
+ login: name,
10249
+ stored: "none",
10250
+ ...kept
10251
+ };
10252
+ if (login.revokeEndpoint !== void 0) await revoke(login.revokeEndpoint, login, stored, ctx);
10253
+ await file.remove();
10254
+ return {
10255
+ login: name,
10256
+ stored: login.revokeEndpoint === void 0 ? "removed" : "revoked",
10257
+ ...kept
10258
+ };
10259
+ },
10260
+ render: renderLogout,
10261
+ renderPlan
10262
+ });
10263
+ }
10264
+ //#endregion
10265
+ //#region ../agent-cli/dist/built-ins/login.js
10266
+ const loginSchema = object({
10267
+ login: string(),
10268
+ source: _enum([
10269
+ "approved",
10270
+ "stored",
10271
+ "secret"
10272
+ ]),
10273
+ secret: string().optional()
10274
+ });
10275
+ function renderLogin({ login, source, secret }) {
10276
+ if (source === "approved") return `signed in to ${login}`;
10277
+ if (source === "stored") return `already signed in to ${login}: nothing to do`;
10278
+ return `${login} uses the token in ${secret}: nothing to do`;
10279
+ }
10280
+ function foundData(login, { source }) {
10281
+ return source.kind === "secret" ? {
10282
+ login,
10283
+ source: "secret",
10284
+ secret: source.name
10285
+ } : {
10286
+ login,
10287
+ source: "stored"
10288
+ };
10289
+ }
10290
+ function loginCommand(cli, logins, names) {
10291
+ const named = exampleName(names);
10292
+ return defineCommand$1.write({
10293
+ description: "sign in through a browser, so the Commands that need a Login can run",
10294
+ help: "Prints a link and a code for the person who runs this CLI to approve, then waits for the approval and keeps the Login for this user. A rerun takes up the same code. It does nothing when its Secret is set or the stored Login's access token has not expired, and refreshes one that has.",
10295
+ examples: [{
10296
+ command: [
10297
+ cli.name,
10298
+ "login",
10299
+ ...named
10300
+ ].join(" "),
10301
+ note: `sign in, waiting at most 100 s for the code to be approved`
10302
+ }, {
10303
+ command: [
10304
+ cli.name,
10305
+ "login",
10306
+ ...named,
10307
+ WAIT_FLAG.flag,
10308
+ "30"
10309
+ ].join(" "),
10310
+ note: "wait at most 30 s for the approval"
10311
+ }],
10312
+ args: nameArgs(names, "sign in to"),
10313
+ options: object({ wait: number$1().int().nonnegative().optional().describe(`${WAIT_FLAG.description}; 100 when absent`) }),
10314
+ output: loginSchema,
10315
+ plan: async ({ name: given, wait }, ctx) => {
10316
+ const name = chosenName({
10317
+ cliName: cli.name,
10318
+ command: "login"
10319
+ }, given, names);
10320
+ const login = declaredLogin(logins, name);
10321
+ const token = await currentTokenOf(login, tokenScopeOf(ctx));
10322
+ const stored = await readStored(loginFilesOf(ctx.userFile, login).stored, ctx.clock);
10323
+ return {
10324
+ login: name,
10325
+ wait,
10326
+ found: token && foundData(name, token),
10327
+ renew: stored?.refreshToken !== void 0
10328
+ };
10329
+ },
10330
+ apply: async ({ login: name, wait, found }, ctx) => {
10331
+ if (found !== void 0) return found;
10332
+ const login = declaredLogin(logins, name);
10333
+ const files = loginFilesOf(ctx.userFile, login);
10334
+ const stored = await readStored(files.stored, ctx.clock);
10335
+ if (stored?.refreshToken !== void 0 && await refreshed(name, login, files.stored, stored.refreshToken, ctx) !== void 0) return {
10336
+ login: name,
10337
+ source: "stored"
10338
+ };
10339
+ await signIn(name, login, files, ctx, {
10340
+ waitS: wait ?? 100,
10341
+ rerun: [
10342
+ "login",
10343
+ name,
10344
+ WAIT_FLAG.flag,
10345
+ String(100)
10346
+ ]
10347
+ });
10348
+ return {
10349
+ login: name,
10350
+ source: "approved"
10351
+ };
10352
+ },
10353
+ render: renderLogin,
10354
+ renderPlan: ({ login, found, renew }) => {
10355
+ if (found !== void 0) return renderLogin(found);
10356
+ return renew ? `would refresh the Login ${login}, or sign in through a browser if the server refuses` : `would sign in to ${login} through a browser`;
10357
+ }
10358
+ });
10359
+ }
10360
+ /** The Built-in `login` and `logout`, for a CLI that declares a Login. */
10361
+ function loginBuiltIns(cli) {
10362
+ const logins = cli.logins ?? {};
10363
+ const [first, ...rest] = Object.keys(logins);
10364
+ if (first === void 0) return {};
10365
+ const names = [first, ...rest];
10366
+ return {
10367
+ login: loginCommand(cli, logins, names),
10368
+ logout: logoutCommand(cli, logins, names)
10369
+ };
10370
+ }
10371
+ //#endregion
9535
10372
  //#region ../agent-cli/dist/built-ins/commands.js
9536
10373
  /**
9537
10374
  * The Commands the Runtime adds to a multi-Command CLI: `setup` and `update` only for a Global
9538
- * install, and `skill install` only for a skill whose copy goes under the project.
10375
+ * install, `skill install` only for a skill whose copy goes under the project, and `login` only
10376
+ * for a CLI that declares a Login.
9539
10377
  */
9540
10378
  function builtInCommands(cli, launch) {
9541
10379
  const install = installOf(cli);
9542
10380
  return {
9543
10381
  doctor: doctorCommand(cli, launch),
9544
10382
  ...install.builtIns(launch),
9545
- ...skillOf(cli, install).builtIns
10383
+ ...skillOf(cli, install).builtIns,
10384
+ ...loginBuiltIns(cli)
9546
10385
  };
9547
10386
  }
9548
10387
  //#endregion
@@ -9556,15 +10395,18 @@ function commandLabel(path, cliName) {
9556
10395
  return path.length === 0 ? [cliName] : path;
9557
10396
  }
9558
10397
  function declaredOf(command) {
10398
+ const wait = takesWait(command);
9559
10399
  if (!hasPlan(command)) return {
9560
10400
  outputs: false,
9561
10401
  force: void 0,
9562
- cost: false
10402
+ cost: false,
10403
+ wait
9563
10404
  };
9564
10405
  return {
9565
10406
  outputs: command.outputs !== void 0,
9566
10407
  force: command.force,
9567
- cost: command.cost !== void 0
10408
+ cost: command.cost !== void 0,
10409
+ wait
9568
10410
  };
9569
10411
  }
9570
10412
  function withRunAs(example, { name, runAs }) {
@@ -9679,11 +10521,11 @@ function checkOwnCodes(errors) {
9679
10521
  const redeclared = runtimeCodesIn(errors);
9680
10522
  if (redeclared.length > 0) throw new Error(`The Error table declares ${redeclared.join(", ")}, an error code the Runtime already declares`);
9681
10523
  }
9682
- function checkTree(commands, path, table) {
10524
+ function checkTree(commands, path, table, logins) {
9683
10525
  for (const [key, node] of Object.entries(commands)) {
9684
10526
  const at = [...path, key];
9685
- if (isCommand(node)) checkCommand(node, at.join(" "), table);
9686
- else checkTree(node, at, table);
10527
+ if (isCommand(node)) checkCommand(node, at.join(" "), table, logins);
10528
+ else checkTree(node, at, table, logins);
9687
10529
  }
9688
10530
  }
9689
10531
  function checkSkill({ name, skill, install }) {
@@ -9702,13 +10544,13 @@ function checkDeclared(cli) {
9702
10544
  const table = errorTableOf(cli);
9703
10545
  checkDocs(cli);
9704
10546
  if (cli.commands === void 0) {
9705
- checkCommand(cli.command, commandLabel([], cli.name).join(" "), table);
10547
+ checkCommand(cli.command, commandLabel([], cli.name).join(" "), table, {});
9706
10548
  if (cli.skill !== void 0) throw new Error(`${cli.name} declares a skill, which only a CLI with several Commands can install`);
9707
10549
  return cli;
9708
10550
  }
9709
10551
  checkSkill(cli);
9710
10552
  const { commands } = cli;
9711
- checkTree(commands, [], table);
10553
+ checkTree(commands, [], table, cli.logins ?? {});
9712
10554
  for (const row of cli.doctor ?? []) checkErrors(row.errors ?? [], `the ${row.name} row of doctor`, table);
9713
10555
  const taken = Object.keys(builtInCommands(cli, {
9714
10556
  bin: void 0,
@@ -10018,6 +10860,12 @@ async function parseInput(spec, words, invocation, readStdin) {
10018
10860
  if (only !== void 0 && unknown.length === 1 && otherLines.length === 0) throw unknownOptionError(spec.commandLine, invocation, only.flag, only.suggestion === void 0 ? [] : [only.suggestion]);
10019
10861
  throw invalidInput(spec.commandLine, invocation, unknown, otherLines);
10020
10862
  }
10863
+ function waitOf(given, commandLine) {
10864
+ if (given === void 0) return void 0;
10865
+ const parsed = WAIT_SECONDS.safeParse(given === true ? void 0 : given);
10866
+ if (!parsed.success) throw invalidInputError(commandLine, `option '${WAIT_FLAG.usage}' takes a whole number of seconds, not ${given === true ? "nothing" : JSON.stringify(given)}`);
10867
+ return parsed.data;
10868
+ }
10021
10869
  /**
10022
10870
  * The validated input and Standard flag values of the routed Command, or one usage error; the arg
10023
10871
  * given `-` takes its text from `readStdin`.
@@ -10033,6 +10881,7 @@ async function parseCommand({ spec, words, json }, invocation, readStdin) {
10033
10881
  confirm: typeof confirm === "string" ? confirm : void 0,
10034
10882
  yes: values.get(YES_FLAG.flag) === true,
10035
10883
  force: values.get(FORCE_FLAG.flag) === true,
10884
+ wait: waitOf(values.get(WAIT_FLAG.flag), spec.commandLine),
10036
10885
  page,
10037
10886
  fields: spec.list === void 0 ? void 0 : selectedFields(values, spec.list.rowFields, spec.commandLine)
10038
10887
  }
@@ -10710,6 +11559,28 @@ function rootSpec(cli, launch) {
10710
11559
  } : groupSpec(names, cli.commands, builtInCommands(cli, launch));
10711
11560
  }
10712
11561
  //#endregion
11562
+ //#region ../agent-cli/dist/built-ins/install/release-too-old.js
11563
+ function isTooOld(error) {
11564
+ return error instanceof CliError && error.code === "RELEASE_TOO_OLD";
11565
+ }
11566
+ function mapLeaves(error, map) {
11567
+ if (error instanceof AggregateError && error.errors.length > 0) return new AggregateError(error.errors.map((inner) => mapLeaves(inner, map)), error.message, { cause: error.cause });
11568
+ return map(error);
11569
+ }
11570
+ /** `error` with the Install's update line leading the Next steps of each `RELEASE_TOO_OLD` in it. */
11571
+ async function withUpdateLine(error, install, ctx) {
11572
+ if (!errorsOf(error).some(isTooOld)) return error;
11573
+ const line = await install.updateLine(ctx);
11574
+ if (line === void 0) return error;
11575
+ return mapLeaves(error, (leaf) => isTooOld(leaf) ? runtimeError({
11576
+ code: leaf.code,
11577
+ message: leaf.message,
11578
+ hint: leaf.hint,
11579
+ details: leaf.details,
11580
+ next: [line, ...leaf.next]
11581
+ }, { cause: leaf.cause }) : leaf);
11582
+ }
11583
+ //#endregion
10713
11584
  //#region ../agent-cli/dist/context/spill.js
10714
11585
  const STDOUT_BUDGET_CHARS = 3e4;
10715
11586
  const SPILL_RETENTION_MS = 6048e5;
@@ -11290,6 +12161,91 @@ function resolveOptions(options) {
11290
12161
  };
11291
12162
  }
11292
12163
  //#endregion
12164
+ //#region ../agent-cli/dist/context/derived.js
12165
+ /**
12166
+ * `base` with `extra`'s properties over it, built on `base` as its prototype, so a lazy getter of
12167
+ * `base` such as `ctx.ports` is not read, as a spread would.
12168
+ */
12169
+ function derived(base, extra) {
12170
+ const child = Object.create(base);
12171
+ return Object.assign(child, extra);
12172
+ }
12173
+ //#endregion
12174
+ //#region ../agent-cli/dist/login/with-logins.js
12175
+ /** The rerun of an `APPROVAL_PENDING`, which waits for the approval. */
12176
+ function approvalRerun(ctx) {
12177
+ return ctx.rerun({
12178
+ remove: [WAIT_FLAG.flag],
12179
+ add: [WAIT_FLAG.flag, String(100)]
12180
+ });
12181
+ }
12182
+ async function tokensOf(names, logins, ctx, waitS) {
12183
+ const found = await Promise.all(names.map(async (name) => {
12184
+ const login = declaredLogin(logins, name);
12185
+ return {
12186
+ name,
12187
+ token: ctx.dryRun ? await currentTokenOf(login, tokenScopeOf(ctx)) : await freshTokenOf(name, login, ctx)
12188
+ };
12189
+ }));
12190
+ const missing = found.flatMap(({ name, token }) => token === void 0 ? [name] : []);
12191
+ if (missing.length > 0 && ctx.dryRun) throw loginRequired(missing, ctx.rerun());
12192
+ const tokens = /* @__PURE__ */ new Map();
12193
+ for (const { name, token } of found) {
12194
+ if (token !== void 0) {
12195
+ tokens.set(name, token);
12196
+ continue;
12197
+ }
12198
+ const login = declaredLogin(logins, name);
12199
+ const stored = await signIn(name, login, loginFilesOf(ctx.userFile, login), ctx, {
12200
+ waitS,
12201
+ rerun: approvalRerun(ctx)
12202
+ });
12203
+ tokens.set(name, storedToken(stored));
12204
+ }
12205
+ ctx.signal.throwIfAborted();
12206
+ return tokens;
12207
+ }
12208
+ /** The Login a `LOGIN_REJECTED` names in `details.login`, or the Command's only one. */
12209
+ function rejectedName(rejected, tokens) {
12210
+ const { details } = rejected;
12211
+ if (typeof details === "object" && details !== null && "login" in details) return typeof details.login === "string" ? details.login : void 0;
12212
+ const [only, ...rest] = tokens.keys();
12213
+ return rest.length === 0 ? only : void 0;
12214
+ }
12215
+ /**
12216
+ * What a run whose Command threw `error` fails with: a `LOGIN_REJECTED` of a stored Login drops
12217
+ * it for a new Approval, one of a Secret's token fails as the operator's to fix.
12218
+ */
12219
+ async function afterRejection(error, tokens, logins, ctx) {
12220
+ if (!(error instanceof CliError && error.code === "LOGIN_REJECTED")) return error;
12221
+ const name = rejectedName(error, tokens);
12222
+ const token = name === void 0 ? void 0 : tokens.get(name);
12223
+ if (name === void 0 || token === void 0) return new Error(`the Command threw ${LOGIN_REJECTED} naming no Login it declares in details.login`, { cause: error });
12224
+ const login = declaredLogin(logins, name);
12225
+ if (token.source.kind === "secret" && login.secret !== void 0) return secretRejected(name, login.secret, error);
12226
+ const files = loginFilesOf(ctx.userFile, login);
12227
+ await files.stored.remove();
12228
+ if (ctx.dryRun) return loginRequired([name], ctx.rerun());
12229
+ return await pendingApproval(name, login, files, ctx, approvalRerun(ctx));
12230
+ }
12231
+ /**
12232
+ * Runs `work` with a `ctx` whose `login` gives each named Login's token, signing in first, for at
12233
+ * most `waitS` seconds, where one is missing. A `LOGIN_REJECTED` from `work` drops the stored Login.
12234
+ */
12235
+ async function withLogins(ctx, names, logins, waitS, work) {
12236
+ const tokens = names.length === 0 ? /* @__PURE__ */ new Map() : await tokensOf(names, logins, ctx, waitS ?? 0);
12237
+ const loggedIn = derived(ctx, { login: (name) => tokens.get(name)?.value ?? undeclaredLogin(name) });
12238
+ try {
12239
+ return await work(loggedIn);
12240
+ } catch (error) {
12241
+ throw await afterRejection(error, tokens, logins, ctx);
12242
+ }
12243
+ }
12244
+ /** `ctx.login` of a name the Command does not declare, which only a cast reaches. */
12245
+ function undeclaredLogin(name) {
12246
+ throw new Error(`ctx.login("${name}") names a Login the Command does not declare`);
12247
+ }
12248
+ //#endregion
11293
12249
  //#region ../agent-cli/dist/execute.js
11294
12250
  const PLAN_INDENT = " ";
11295
12251
  function outcomeOf(value, render) {
@@ -11334,17 +12290,19 @@ function dryRunOutcome(command, plan, commandLine) {
11334
12290
  };
11335
12291
  }
11336
12292
  function serveContextOf(ctx, end) {
11337
- const serveCtx = Object.create(ctx);
11338
- return Object.assign(serveCtx, { end });
12293
+ return derived(ctx, { end });
11339
12294
  }
11340
- async function execute(command, input, ctx, { flags, commandLine, started, outputs: runOutputs }) {
11341
- await checkTools(command.tools ?? [], ctx, ctx.rerun());
11342
- const { env, envFile, fileError } = ctx;
12295
+ async function execute(command, input, unlogged, run) {
12296
+ await checkTools(command.tools ?? [], unlogged, unlogged.rerun());
12297
+ const { env, envFile, fileError } = unlogged;
11343
12298
  checkSecrets(command.secrets ?? [], {
11344
12299
  env,
11345
12300
  envFile,
11346
12301
  fileError
11347
- }, ctx.rerun());
12302
+ }, unlogged.rerun());
12303
+ return await withLogins(unlogged, command.logins ?? [], run.logins, run.flags.wait, (ctx) => executeLoggedIn(command, input, ctx, run));
12304
+ }
12305
+ async function executeLoggedIn(command, input, ctx, { flags, commandLine, started, outputs: runOutputs }) {
11348
12306
  if (command.rows !== void 0) {
11349
12307
  const { render } = command;
11350
12308
  return outcomeOf(await command.run({
@@ -11401,6 +12359,66 @@ function manifestAt(packageRoot) {
11401
12359
  return parsed.success ? parsed.data : NO_MANIFEST;
11402
12360
  }
11403
12361
  //#endregion
12362
+ //#region ../agent-cli/dist/context/user-file.js
12363
+ const FOLDER_MODE = 448;
12364
+ const FILE_MODE = 384;
12365
+ /** `$XDG_STATE_HOME/<cli>`, with `~/.local/state` when the variable is unset or empty. */
12366
+ function stateFolderOf(cliName, env) {
12367
+ const state = env.XDG_STATE_HOME || join(env.HOME || homedir(), ".local", "state");
12368
+ return join(state, cliName);
12369
+ }
12370
+ function parsed(bytes, schema) {
12371
+ let json;
12372
+ try {
12373
+ json = JSON.parse(new TextDecoder().decode(bytes));
12374
+ } catch {
12375
+ return;
12376
+ }
12377
+ const result = schema.safeParse(json);
12378
+ return result.success ? result.data : void 0;
12379
+ }
12380
+ function userFileOf({ folder, files, fileError }) {
12381
+ return (name, schema) => {
12382
+ const path = join(folder, `${name}.json`);
12383
+ return {
12384
+ read: async () => {
12385
+ let bytes;
12386
+ try {
12387
+ bytes = await files.read(path);
12388
+ } catch (error) {
12389
+ if (isMissingFile(error)) return void 0;
12390
+ throw fileError(error, {
12391
+ path,
12392
+ access: "read"
12393
+ });
12394
+ }
12395
+ return parsed(bytes, schema);
12396
+ },
12397
+ write: async (value) => {
12398
+ try {
12399
+ await files.mkdir(dirname(path), { mode: FOLDER_MODE });
12400
+ await files.write(path, `${JSON.stringify(value)}\n`, { mode: FILE_MODE });
12401
+ } catch (error) {
12402
+ throw fileError(error, {
12403
+ path,
12404
+ access: "write"
12405
+ });
12406
+ }
12407
+ },
12408
+ remove: async () => {
12409
+ try {
12410
+ await files.remove(path);
12411
+ } catch (error) {
12412
+ throw fileError(error, {
12413
+ path,
12414
+ access: "write"
12415
+ });
12416
+ }
12417
+ }
12418
+ };
12419
+ };
12420
+ }
12421
+ //#endregion
11404
12422
  //#region ../agent-cli/dist/run-scope.js
11405
12423
  function selfOf(name, bin) {
11406
12424
  return bin === void 0 ? [name] : [
@@ -11439,12 +12457,19 @@ function runScopeOf(cli, routed, settings, write, baseInvocation) {
11439
12457
  env,
11440
12458
  platform
11441
12459
  });
11442
- const outputs = outputsOf(settings.files ?? realFiles(), {
12460
+ const files = settings.files ?? realFiles();
12461
+ const outputs = outputsOf(files, {
11443
12462
  cwd,
11444
12463
  fileError
11445
12464
  });
11446
12465
  const packageRoot = packageRootOf(settings.bin, cwd);
11447
12466
  const progress = (message) => write.stderr(progressLine(message, routed.json));
12467
+ const noticed = /* @__PURE__ */ new Set();
12468
+ const notice = (text) => {
12469
+ if (noticed.has(text)) return;
12470
+ noticed.add(text);
12471
+ write.stderr(noticeLine(text, routed.json));
12472
+ };
11448
12473
  const envFile = envFileOf(cli.name, env);
11449
12474
  const spawning = {
11450
12475
  fileError,
@@ -11458,8 +12483,15 @@ function runScopeOf(cli, routed, settings, write, baseInvocation) {
11458
12483
  platform,
11459
12484
  outputs,
11460
12485
  progress,
11461
- notice: (text) => write.stderr(noticeLine(text, routed.json)),
12486
+ notice,
11462
12487
  packageRoot,
12488
+ fetch: settings.fetch ?? ((input, init) => globalThis.fetch(input, init)),
12489
+ userAgent: `${cli.name}/${cli.version}`,
12490
+ userFile: userFileOf({
12491
+ folder: stateFolderOf(cli.name, env),
12492
+ files,
12493
+ fileError
12494
+ }),
11463
12495
  ports: portsOf(cli, settings.ports),
11464
12496
  portsBase: (signal) => ({
11465
12497
  cwd,
@@ -11493,7 +12525,7 @@ function runScopeOf(cli, routed, settings, write, baseInvocation) {
11493
12525
  })
11494
12526
  };
11495
12527
  }
11496
- function contextOf(scope, control, { command, flags, project, deliver }) {
12528
+ function contextOf(scope, control, { command, flags, project, deliver, latestRelease }) {
11497
12529
  const portsBase = scope.portsBase(control.signal);
11498
12530
  const ports = once(() => scope.ports(portsBase));
11499
12531
  const declared = new Map((command.secrets ?? []).map((declaration) => [declaration.name, declaration]));
@@ -11507,8 +12539,17 @@ function contextOf(scope, control, { command, flags, project, deliver }) {
11507
12539
  return {
11508
12540
  ...portsBase,
11509
12541
  secret,
12542
+ login: undeclaredLogin,
12543
+ userFile: scope.userFile,
11510
12544
  fail: cliErrorOf,
11511
12545
  deadline: (ms, options) => control.deadline(ms, options),
12546
+ fetch: contextFetch({
12547
+ fetch: scope.fetch,
12548
+ userAgent: scope.userAgent,
12549
+ deadline: (ms, options) => control.deadline(ms, options),
12550
+ clock: scope.clock,
12551
+ rerun: scope.rerun()
12552
+ }),
11512
12553
  runToEnd: (name, work) => control.runToEnd(name, work),
11513
12554
  get ports() {
11514
12555
  return ports();
@@ -11519,7 +12560,8 @@ function contextOf(scope, control, { command, flags, project, deliver }) {
11519
12560
  rerun: scope.rerun,
11520
12561
  poll: (check, { intervalMs, signal: stop }) => poll(portsBase.clock, check, intervalMs, stop === void 0 ? control.signal : AbortSignal.any([control.signal, stop])),
11521
12562
  deliver,
11522
- notice: scope.notice
12563
+ notice: scope.notice,
12564
+ latestRelease
11523
12565
  };
11524
12566
  }
11525
12567
  /** `build` runs on the first call; later calls give its value or throw its error again. */
@@ -11644,10 +12686,17 @@ async function runCommand(cli, routed, options, write, baseFormat) {
11644
12686
  return ran(await failed(error), sideTask);
11645
12687
  }
11646
12688
  let delivered;
12689
+ const release = installOf(cli).releaseCheck({
12690
+ builtIn,
12691
+ bin: options.bin,
12692
+ node: options.node,
12693
+ platform
12694
+ });
11647
12695
  const ctx = contextOf(scope, control, {
11648
12696
  command,
11649
12697
  flags,
11650
12698
  project,
12699
+ latestRelease: (version) => release.latestRelease(version, ctx),
11651
12700
  deliver: (data) => {
11652
12701
  delivered = () => dataOutcome(command, data, commandLine);
11653
12702
  }
@@ -11663,19 +12712,15 @@ async function runCommand(cli, routed, options, write, baseFormat) {
11663
12712
  let served = false;
11664
12713
  let settled;
11665
12714
  try {
11666
- const outcome = await control.settle(noticesOf(cli, {
11667
- builtIn,
11668
- bin: options.bin,
11669
- node: options.node,
11670
- platform
11671
- }, ctx).then(() => execute(command, input, ctx, {
12715
+ const outcome = await control.settle(release.notice(ctx).then(() => execute(command, input, ctx, {
11672
12716
  flags,
11673
12717
  commandLine,
11674
12718
  started: async (outcome) => {
11675
12719
  write.stdout(await startedOutput(outcome, format, spill));
11676
12720
  served = true;
11677
12721
  },
11678
- outputs
12722
+ outputs,
12723
+ logins: cli.logins ?? {}
11679
12724
  })));
11680
12725
  if (served) return ran(STOPPED, sideTask);
11681
12726
  settled = {
@@ -11686,7 +12731,7 @@ async function runCommand(cli, routed, options, write, baseFormat) {
11686
12731
  if (served && control.signal.aborted) return ran(STOPPED, sideTask);
11687
12732
  settled = {
11688
12733
  ok: false,
11689
- error,
12734
+ error: await withUpdateLine(error, installOf(cli), ctx),
11690
12735
  delivered
11691
12736
  };
11692
12737
  }
@@ -11695,9 +12740,6 @@ async function runCommand(cli, routed, options, write, baseFormat) {
11695
12740
  fields: flags.fields
11696
12741
  }, spill), sideTask);
11697
12742
  }
11698
- async function noticesOf(cli, launch, ctx) {
11699
- await installOf(cli).notice(launch, ctx);
11700
- }
11701
12743
  //#endregion
11702
12744
  //#region ../agent-cli/dist/style.js
11703
12745
  function colourEnabled(env, stdoutIsTTY) {
@@ -11856,7 +12898,7 @@ async function runProcess(cli) {
11856
12898
  //#region package.json
11857
12899
  var package_default = {
11858
12900
  name: "@duyquangnvx/create-agent-cli",
11859
- version: "0.30.1",
12901
+ version: "0.31.0",
11860
12902
  description: "Creates a new Agent CLI repository wired to @duyquangnvx/agent-cli.",
11861
12903
  type: "module",
11862
12904
  engines: { "node": ">=22.12.0" },