@agenttrail/cli 0.2.24 → 0.2.29

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.
@@ -3099,45 +3099,161 @@ function agentDenialOf(body) {
3099
3099
  const reason = typeof o.reason === "string" ? o.reason.trim() : "";
3100
3100
  return reason.startsWith("Denied by ") ? reason : null;
3101
3101
  }
3102
- async function holdForApproval(args, fetchFn) {
3103
- const res = await boundedFetch(
3104
- fetchFn,
3105
- args.url,
3106
- {
3107
- method: "POST",
3108
- headers: { "content-type": "application/json", authorization: `Bearer ${args.token}` },
3109
- body: JSON.stringify({
3110
- ...args.request,
3111
- correlation_id: args.correlationId,
3112
- // Omitted entirely when the caller sends none, so the Claude Code path's request
3113
- // body is byte-identical to what it was before Cursor needed the field.
3114
- ...args.maxWindowSeconds === void 0 ? {} : { max_window_seconds: args.maxWindowSeconds }
3115
- })
3116
- },
3117
- args.timeoutMs
3118
- );
3119
- if (res.status === 403) {
3120
- if (await isApiTierRefusal(res)) return "tier-disabled";
3121
- throw foreign403("hold");
3122
- }
3123
- if (res.status !== 200) {
3124
- throw new PdpUnreachableError(`hold status ${res.status}`, statusKind(res.status));
3102
+ var PdpHoldInterruptedError = class extends PdpUnreachableError {
3103
+ };
3104
+ var PdpHoldUnconfirmedError = class extends PdpUnreachableError {
3105
+ constructor(reason) {
3106
+ super(reason, "parse_error");
3125
3107
  }
3108
+ };
3109
+ async function readBodyBounded(res, signal) {
3110
+ let onAbort;
3111
+ const aborted = new Promise((_, reject) => {
3112
+ onAbort = () => reject(new Error("hold response body exceeded its deadline"));
3113
+ if (signal.aborted) onAbort();
3114
+ else signal.addEventListener("abort", onAbort, { once: true });
3115
+ });
3116
+ aborted.catch(() => {
3117
+ });
3126
3118
  try {
3127
- args.onHeld?.();
3128
- } catch {
3119
+ return await Promise.race([res.text(), aborted]);
3120
+ } finally {
3121
+ if (onAbort) signal.removeEventListener("abort", onAbort);
3129
3122
  }
3130
- let parsed;
3123
+ }
3124
+ async function holdAttempt(args, fetchFn, timeoutMs, windowSeconds, onHeld, afterAcceptMs) {
3125
+ const controller = new AbortController();
3126
+ let timer = setTimeout(() => controller.abort(), timeoutMs);
3131
3127
  try {
3132
- parsed = JSON.parse(await res.text());
3133
- } catch {
3134
- throw new PdpUnreachableError("hold 200 with unparseable body", "parse_error");
3128
+ let res;
3129
+ try {
3130
+ res = await fetchFn(args.url, {
3131
+ method: "POST",
3132
+ headers: { "content-type": "application/json", authorization: `Bearer ${args.token}` },
3133
+ body: JSON.stringify({
3134
+ ...args.request,
3135
+ correlation_id: args.correlationId,
3136
+ // Omitted entirely when the caller sends none, so the Claude Code path's first
3137
+ // request body is byte-identical to what it was before Cursor needed the field.
3138
+ ...windowSeconds === void 0 ? {} : { max_window_seconds: windowSeconds }
3139
+ }),
3140
+ signal: controller.signal
3141
+ });
3142
+ } catch (err) {
3143
+ const msg = err instanceof Error ? err.message : String(err);
3144
+ if (controller.signal.aborted) throw new PdpUnreachableError(msg, "timeout");
3145
+ throw new PdpHoldInterruptedError(msg, "unreachable");
3146
+ }
3147
+ if (res.status === 403) {
3148
+ if (await isApiTierRefusal(res)) return "tier-disabled";
3149
+ throw foreign403("hold");
3150
+ }
3151
+ if (res.status !== 200) {
3152
+ const kind = statusKind(res.status);
3153
+ const message = `hold status ${res.status}`;
3154
+ throw res.status >= 500 ? new PdpHoldInterruptedError(message, kind) : new PdpUnreachableError(message, kind);
3155
+ }
3156
+ if (afterAcceptMs) {
3157
+ clearTimeout(timer);
3158
+ timer = setTimeout(() => controller.abort(), Math.max(0, afterAcceptMs()));
3159
+ }
3160
+ try {
3161
+ onHeld?.();
3162
+ } catch {
3163
+ }
3164
+ let text;
3165
+ try {
3166
+ text = await readBodyBounded(res, controller.signal);
3167
+ } catch (err) {
3168
+ const msg = err instanceof Error ? err.message : String(err);
3169
+ if (controller.signal.aborted) throw new PdpUnreachableError(msg, "timeout");
3170
+ throw new PdpHoldInterruptedError(`hold response broke: ${msg}`, "unreachable");
3171
+ }
3172
+ if (text.trim() === "") {
3173
+ throw new PdpHoldInterruptedError("hold response ended before a verdict", "unreachable");
3174
+ }
3175
+ let parsed;
3176
+ try {
3177
+ parsed = JSON.parse(text);
3178
+ } catch {
3179
+ throw new PdpUnreachableError("hold 200 with unparseable body", "parse_error");
3180
+ }
3181
+ const outcome = parsed?.outcome;
3182
+ if (outcome === "approved" || outcome === "denied" || outcome === "unanswered") {
3183
+ const id = parsed.approval_id;
3184
+ return {
3185
+ result: { outcome, denial: agentDenialOf(parsed) },
3186
+ approvalId: typeof id === "string" && id !== "" ? id : null
3187
+ };
3188
+ }
3189
+ throw new PdpUnreachableError("hold 200 with malformed outcome", "parse_error");
3190
+ } finally {
3191
+ clearTimeout(timer);
3135
3192
  }
3136
- const outcome = parsed?.outcome;
3137
- if (outcome === "approved" || outcome === "denied" || outcome === "unanswered") {
3138
- return { outcome, denial: agentDenialOf(parsed) };
3193
+ }
3194
+ var REATTACH_BACKOFF_MS = [250, 500, 1e3, 2e3];
3195
+ var REATTACH_MAX_ATTEMPTS = 12;
3196
+ var REATTACH_MIN_REMAINING_MS = 2e3;
3197
+ var HOLD_PRE_ACCEPT_RETRY_CAP_MS = 3e4;
3198
+ function canReattach(err) {
3199
+ return err instanceof PdpHoldInterruptedError;
3200
+ }
3201
+ async function holdWithReattach(args, fetchFn, clock = {}) {
3202
+ const now = clock.now ?? (() => performance.now());
3203
+ const sleep = clock.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
3204
+ const start = now();
3205
+ const hardEnd = start + args.timeoutMs;
3206
+ const windowSeconds = args.maxWindowSeconds ?? POLICY_HOLD_MAX_WINDOW_SECONDS;
3207
+ const windowEnd = start + windowSeconds * 1e3;
3208
+ const preAcceptEnd = start + HOLD_PRE_ACCEPT_RETRY_CAP_MS;
3209
+ let accepted = false;
3210
+ let uploaded = false;
3211
+ let lastError;
3212
+ for (let attempt = 0; attempt < REATTACH_MAX_ATTEMPTS; attempt++) {
3213
+ if (attempt > 0) {
3214
+ const wait = REATTACH_BACKOFF_MS[Math.min(attempt - 1, REATTACH_BACKOFF_MS.length - 1)] ?? 0;
3215
+ if (hardEnd - now() - wait < REATTACH_MIN_REMAINING_MS) break;
3216
+ if (!accepted && now() + wait >= preAcceptEnd) break;
3217
+ await sleep(wait);
3218
+ }
3219
+ const remaining = hardEnd - now();
3220
+ if (attempt > 0 && remaining < REATTACH_MIN_REMAINING_MS) break;
3221
+ const sendWindow = attempt === 0 ? args.maxWindowSeconds : Math.min(windowSeconds, Math.max(1, Math.floor((windowEnd - now()) / 1e3)));
3222
+ try {
3223
+ const out = await holdAttempt(
3224
+ args,
3225
+ fetchFn,
3226
+ accepted ? remaining : Math.min(remaining, Math.max(1, preAcceptEnd - now())),
3227
+ sendWindow,
3228
+ () => {
3229
+ accepted = true;
3230
+ if (args.onHeld && !uploaded) {
3231
+ uploaded = true;
3232
+ args.onHeld();
3233
+ }
3234
+ },
3235
+ () => hardEnd - now()
3236
+ );
3237
+ if (out === "tier-disabled") {
3238
+ if (accepted || attempt > 0) {
3239
+ throw new PdpHoldUnconfirmedError(
3240
+ "re-attached hold answered with a tier refusal, not a reviewer's answer; failing closed"
3241
+ );
3242
+ }
3243
+ return out;
3244
+ }
3245
+ if (attempt > 0 && out.result.outcome === "approved" && out.approvalId === null) {
3246
+ throw new PdpHoldUnconfirmedError(
3247
+ "re-attached hold answered approved with no approval id (the policy changed during the hold); failing closed"
3248
+ );
3249
+ }
3250
+ return out.result;
3251
+ } catch (err) {
3252
+ if (!canReattach(err)) throw err;
3253
+ lastError = err;
3254
+ }
3139
3255
  }
3140
- throw new PdpUnreachableError("hold 200 with malformed outcome", "parse_error");
3256
+ throw lastError instanceof Error ? lastError : new PdpUnreachableError("hold could not be reached", "unreachable");
3141
3257
  }
3142
3258
  function readCachedSnapshot(path, io2 = {}) {
3143
3259
  const read = io2.readFile ?? ((p) => readFileSync4(p, "utf8"));
@@ -3189,6 +3305,9 @@ function holdWindowSeconds(elapsedMs) {
3189
3305
  function holdWatchdogDelayMs(elapsedMs) {
3190
3306
  return Math.max(1, PEP_HOLD_WATCHDOG_MS - Math.max(0, elapsedMs));
3191
3307
  }
3308
+ function holdDeadlineMs(elapsedMs) {
3309
+ return Math.max(1e3, PEP_HOLD_FETCH_TIMEOUT_MS - Math.max(0, elapsedMs));
3310
+ }
3192
3311
  async function holdCursorApproval(input) {
3193
3312
  const { cfg, correlationId } = input;
3194
3313
  if (!cfg.holdUrl || !cfg.token || correlationId === null || correlationId === "") {
@@ -3203,13 +3322,15 @@ async function holdCursorApproval(input) {
3203
3322
  return res;
3204
3323
  });
3205
3324
  try {
3206
- const held = await holdForApproval(
3325
+ const held = await holdWithReattach(
3207
3326
  {
3208
3327
  url: cfg.holdUrl,
3209
3328
  token: cfg.token,
3210
3329
  request: input.request,
3211
3330
  correlationId,
3212
- timeoutMs: PEP_HOLD_FETCH_TIMEOUT_MS,
3331
+ // The re-attach loop owns one deadline. The 595 s ceiling counts from the hook's
3332
+ // start, as the watchdog does, so a retry never outlives the budget.
3333
+ timeoutMs: holdDeadlineMs(input.elapsedMs),
3213
3334
  maxWindowSeconds: windowSeconds
3214
3335
  },
3215
3336
  observedFetch
@@ -5993,6 +6114,7 @@ var HOOK_OUTCOMES = Object.keys({
5993
6114
  none: 0
5994
6115
  });
5995
6116
  var REVIEWER_DENIED = "Denied by an AgentTrail reviewer.";
6117
+ var HOLD_UNCONFIRMED = "AgentTrail could not confirm this approval after the connection dropped (the policy changed while the call was held); failing closed. Run the action again to ask for approval.";
5996
6118
  var NO_DECISION = { decision: "none", reason: "" };
5997
6119
  var MAX_DETAIL_LEN = 8192;
5998
6120
  var PEP_VENDOR = "claude-code";
@@ -6026,7 +6148,7 @@ var handleApproval = async (payload, verdict, ctx) => {
6026
6148
  }
6027
6149
  ctx.extendDeadline?.(PEP_HOLD_WATCHDOG_MS);
6028
6150
  try {
6029
- const held = await holdForApproval(
6151
+ const held = await holdWithReattach(
6030
6152
  {
6031
6153
  url: ctx.cfg.holdUrl,
6032
6154
  token: ctx.cfg.token,
@@ -6059,7 +6181,8 @@ var handleApproval = async (payload, verdict, ctx) => {
6059
6181
  );
6060
6182
  return {
6061
6183
  decision: "deny",
6062
- reason: "AgentTrail approval hold was unreachable; failing closed."
6184
+ // Say so when the cause is a re-attach that no reviewer can have answered.
6185
+ reason: err instanceof PdpHoldUnconfirmedError ? HOLD_UNCONFIRMED : "AgentTrail approval hold was unreachable; failing closed."
6063
6186
  };
6064
6187
  }
6065
6188
  };