@mnemonik/shared 7.152.1 → 7.154.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.
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Gate telemetry rides the next injections request instead of its own.
3
+ *
4
+ * Why: every PreToolUse a hook gated used to end with an awaited POST
5
+ * /api/v1/hooks/gate-fired, a whole extra round trip (about 220 ms from New
6
+ * Zealand to us-east-1) after the decision was already made, because the host
7
+ * waits for the hook process to exit. Measured on 26 October 2026 it was about
8
+ * 30% of a PreToolUse hook's process time on an idle machine, and one in three
9
+ * hook requests the server received. The event is telemetry: who gated what,
10
+ * how, and the action observation for credit capture. Nothing on the agent's
11
+ * path waits for it.
12
+ *
13
+ * So the hook writes the event to a small per-session folder (synchronous, no
14
+ * network) and the next injections request of the same session claims the
15
+ * events and carries them as `gateEvents`; the server records them exactly as
16
+ * the gate-fired route does. A request that gets no answer puts its events
17
+ * back for the next one; each event carries an id the server records once, so
18
+ * a request that was recorded but whose answer was lost does not count twice.
19
+ * Events still queued when a session goes idle for GATE_OUTBOX_MAX_AGE_MS are
20
+ * dropped, and the folder holds at most GATE_OUTBOX_CAP events (the oldest
21
+ * go first), so a server that stays unreachable cannot grow it without
22
+ * bound. Temporary and claimed files a killed hook process left behind are
23
+ * swept after GATE_OUTBOX_STRAY_MS. Never throws.
24
+ *
25
+ * One file per event, written to a temporary name and renamed into the folder,
26
+ * and claimed by renaming it again: a reader never sees half an event, two
27
+ * hook processes never claim the same one, and a writer racing a reader never
28
+ * loses its event.
29
+ */
30
+
31
+ import { randomUUID } from 'node:crypto';
32
+ import {
33
+ mkdirSync,
34
+ readFileSync,
35
+ readdirSync,
36
+ renameSync,
37
+ statSync,
38
+ unlinkSync,
39
+ writeFileSync,
40
+ } from 'node:fs';
41
+ import { join } from 'node:path';
42
+
43
+ /** The per-session folder name (pass it to the host's session state path helper). */
44
+ export const GATE_OUTBOX_FILE = 'gate-outbox';
45
+
46
+ /** The most events one request carries; the server accepts the same. */
47
+ export const GATE_OUTBOX_MAX_EVENTS = 32;
48
+
49
+ /** Events older than this are dropped rather than reported: the session went idle. */
50
+ export const GATE_OUTBOX_MAX_AGE_MS = 24 * 60 * 60 * 1000;
51
+
52
+ /** The most events the folder holds; past it the oldest are dropped. */
53
+ export const GATE_OUTBOX_CAP = 500;
54
+
55
+ /**
56
+ * A temporary or claimed file older than this belongs to a hook process that
57
+ * was killed between two renames (a live one holds it for milliseconds).
58
+ */
59
+ export const GATE_OUTBOX_STRAY_MS = 10 * 60 * 1000;
60
+
61
+ export interface QueuedGateEvent {
62
+ /** Unique per event; the server records each id once. */
63
+ id: string;
64
+ tool: string;
65
+ mode: string;
66
+ outcome: string;
67
+ /** Epoch ms when the gate fired; the server stores it as the event's time. */
68
+ at: number;
69
+ host?: string;
70
+ cwd?: string;
71
+ projectId?: string;
72
+ projectRoot?: string;
73
+ actionObservation?: unknown;
74
+ }
75
+
76
+ function write(folder: string, event: QueuedGateEvent): void {
77
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
78
+ const name = `${String(event.at).padStart(15, '0')}-${event.id}.json`;
79
+ const temporary = join(folder, `.${name}.tmp`);
80
+ writeFileSync(temporary, JSON.stringify(event), { mode: 0o600 });
81
+ renameSync(temporary, join(folder, name));
82
+ }
83
+
84
+ const unlinkQuietly = (path: string): void => {
85
+ try {
86
+ unlinkSync(path);
87
+ } catch {
88
+ // Already gone.
89
+ }
90
+ };
91
+
92
+ /** Event file names, oldest first (names start with the zero-padded time). */
93
+ function queuedNames(folder: string): string[] {
94
+ return readdirSync(folder)
95
+ .filter((name) => name.endsWith('.json') && !name.startsWith('.'))
96
+ .sort();
97
+ }
98
+
99
+ /** Drop the oldest events past GATE_OUTBOX_CAP. */
100
+ function enforceCap(folder: string): void {
101
+ try {
102
+ const names = queuedNames(folder);
103
+ for (const name of names.slice(0, Math.max(0, names.length - GATE_OUTBOX_CAP)))
104
+ unlinkQuietly(join(folder, name));
105
+ } catch {
106
+ // Telemetry.
107
+ }
108
+ }
109
+
110
+ export function queueGateEvent(folder: string, event: Omit<QueuedGateEvent, 'id'>): boolean {
111
+ try {
112
+ write(folder, { ...event, id: randomUUID() });
113
+ enforceCap(folder);
114
+ return true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Claim every queued event of this session, oldest first, at most
122
+ * GATE_OUTBOX_MAX_EVENTS (the rest wait for the next request).
123
+ */
124
+ export function takeGateEvents(folder: string, now: number = Date.now()): QueuedGateEvent[] {
125
+ let entries: string[];
126
+ try {
127
+ entries = readdirSync(folder);
128
+ } catch {
129
+ return [];
130
+ }
131
+ // Sweep what killed hook processes left between renames.
132
+ for (const name of entries) {
133
+ if (!name.startsWith('.') || !(name.endsWith('.tmp') || name.endsWith('.claimed'))) continue;
134
+ const path = join(folder, name);
135
+ try {
136
+ if (now - statSync(path).mtimeMs > GATE_OUTBOX_STRAY_MS) unlinkQuietly(path);
137
+ } catch {
138
+ // Gone meanwhile.
139
+ }
140
+ }
141
+ const names = entries.filter((name) => name.endsWith('.json') && !name.startsWith('.')).sort();
142
+ const events: QueuedGateEvent[] = [];
143
+ for (const name of names) {
144
+ if (events.length >= GATE_OUTBOX_MAX_EVENTS) break;
145
+ const claimed = join(folder, `.${name}.${process.pid}.claimed`);
146
+ try {
147
+ renameSync(join(folder, name), claimed);
148
+ } catch {
149
+ continue; // Another hook process of this session took it.
150
+ }
151
+ try {
152
+ const event = JSON.parse(readFileSync(claimed, 'utf8')) as QueuedGateEvent;
153
+ if (
154
+ typeof event?.id === 'string' &&
155
+ typeof event.tool === 'string' &&
156
+ typeof event.mode === 'string' &&
157
+ typeof event.outcome === 'string' &&
158
+ typeof event.at === 'number' &&
159
+ now - event.at <= GATE_OUTBOX_MAX_AGE_MS
160
+ )
161
+ events.push(event);
162
+ } catch {
163
+ // Unreadable; dropped.
164
+ } finally {
165
+ unlinkQuietly(claimed);
166
+ }
167
+ }
168
+ return events;
169
+ }
170
+
171
+ /** Put back events a request could not deliver, so the next request carries them. */
172
+ export function returnGateEvents(folder: string, events: readonly QueuedGateEvent[]): void {
173
+ for (const event of events) {
174
+ try {
175
+ write(folder, event);
176
+ } catch {
177
+ // Lost; telemetry.
178
+ }
179
+ }
180
+ enforceCap(folder);
181
+ }
@@ -3,6 +3,7 @@ import { constants } from 'node:fs';
3
3
  import { lstat, mkdir, open, rename, rm, utimes } from 'node:fs/promises';
4
4
  import { dirname } from 'node:path';
5
5
  import { withFileLock } from './settingsIo.js';
6
+ import { HOOK_REQUEST_ID_HEADER } from './hookTimeouts.js';
6
7
  import { ensureWindowsPrivateDirectorySync } from './runtimeSigners.js';
7
8
 
8
9
  type HookFetchInit = NonNullable<Parameters<typeof fetch>[1]>;
@@ -27,6 +28,15 @@ function boundedHandle(value: unknown): value is string {
27
28
 
28
29
  export class HookConversation {
29
30
  private conversationId?: string;
31
+ /**
32
+ * The hook call (x-mnemonik-hook-request-id) whose acquiring request holds
33
+ * the conversation lock in this process. Its hedged second request
34
+ * (hedgedHookRequest) is the same call: waiting for the lock would hold it
35
+ * until the first request finished, which is exactly what the hedge exists
36
+ * to route around. The server hands both requests the same answer, so the
37
+ * second may save the handle without the lock.
38
+ */
39
+ private lockHeldFor?: string;
30
40
  private readonly scope: string;
31
41
  constructor(private readonly input: HookConversationInput) {
32
42
  this.scope = createHash('sha256')
@@ -185,7 +195,20 @@ export class HookConversation {
185
195
  } else if (this.conversationId) await this.save(this.conversationId);
186
196
  return response;
187
197
  };
188
- const response = acquisition ? await this.locked(send) : await send();
198
+ const callId = hookCallId(init.headers);
199
+ let response: Response;
200
+ if (!acquisition || (callId !== undefined && this.lockHeldFor === callId)) {
201
+ response = await send();
202
+ } else {
203
+ response = await this.locked(async () => {
204
+ this.lockHeldFor = callId;
205
+ try {
206
+ return await send();
207
+ } finally {
208
+ if (this.lockHeldFor === callId) this.lockHeldFor = undefined;
209
+ }
210
+ });
211
+ }
189
212
  // The server refused the cached handle (a signing-secret rotation, say).
190
213
  // Forget it so the next acquiring event mints a fresh one; this request
191
214
  // is never resent, and a handle another event acquired meanwhile stays.
@@ -263,6 +286,14 @@ export function conversationMarker(): string | undefined {
263
286
  export async function adoptHookConversation(result: unknown): Promise<void> {
264
287
  await active?.adopt(result);
265
288
  }
289
+ function hookCallId(headers: HookFetchInit['headers']): string | undefined {
290
+ try {
291
+ return new Headers(headers).get(HOOK_REQUEST_ID_HEADER) ?? undefined;
292
+ } catch {
293
+ return undefined;
294
+ }
295
+ }
296
+
266
297
  export function withHookConversation(
267
298
  url: string,
268
299
  init: HookFetchInit,
@@ -295,3 +295,4 @@ export * from './projectSetupHandoff.js';
295
295
 
296
296
  export * from './hookConversation.js';
297
297
  export * from './hookTrace.js';
298
+ export * from './gateOutbox.js';
@@ -1,3 +1,5 @@
1
+ import diagnosticsChannel from 'node:diagnostics_channel';
2
+
1
3
  /**
2
4
  * Hook dispatcher HTTP timeout budgets + AbortSignal helper.
3
5
  *
@@ -108,51 +110,63 @@ export function withHookTimeout(ms: number): { signal: AbortSignal; cleanup: ()
108
110
  }
109
111
 
110
112
  /**
111
- * One second attempt on the main hook call (POST /api/v1/hooks/injections).
113
+ * The main hook call (POST /api/v1/hooks/injections) is hedged: when the first
114
+ * request has not answered by HOOK_HEDGE_SHARE of the budget, a second request
115
+ * starts beside it on a fresh connection, and whichever answers first is used.
116
+ *
117
+ * Why a second request at all: on 24 October 2026 about a third of one
118
+ * machine's hook calls were lost for 50 minutes to a stall between Cloudflare
119
+ * and one load-balancer node. The server had accepted those requests and was
120
+ * waiting for a body that never finished arriving. A second request opens a new
121
+ * connection and normally lands on a healthy path.
112
122
  *
113
- * Why it exists: on 24 October 2026 about a third of one machine's hook calls
114
- * were lost for 50 minutes to a stall between Cloudflare and one load-balancer
115
- * node. The server had accepted those requests and was waiting for a body that
116
- * never finished arriving. A second request opens a new connection and
117
- * normally lands on a healthy path. The call is idempotent by design (the
118
- * injection bus dedups on the server), so repeating it is safe.
123
+ * Why it is a hedge and not a retry: v7.149.0 abandoned the first request at
124
+ * 65% of the budget and then retried. Every hook process opens its own
125
+ * connection (DNS, TCP and TLS from the user's machine to Cloudflare), and the
126
+ * credential is read before the request leaves, so on 25 October that first
127
+ * request had often been on the wire for only a few hundred milliseconds when
128
+ * it was abandoned. Answers that were merely slow were thrown away, half the
129
+ * calls on the owner's machine needed two requests, about 8% lost both, and the
130
+ * load balancer counted each abandoned request as a client close (ELB 460). A
131
+ * hedge never abandons an answer that is on its way: the first request keeps
132
+ * running to the end of the budget.
119
133
  *
120
- * Shape: the whole call, both attempts included, still ends inside `budgetMs`,
121
- * so the budget every hook event is checked against (tests/HookEventBudgets
122
- * .test.ts) and the host's kill limit do not move. The first attempt gets
123
- * HOOK_FIRST_ATTEMPT_SHARE of the budget; the second gets whatever is left.
124
- * A first attempt that fails fast leaves the second nearly the whole budget.
134
+ * Both requests share one deadline, `budgetMs` from the call, so the budget
135
+ * every hook event is checked against (tests/HookEventBudgets.test.ts) and the
136
+ * host's kill limit do not move. A first request that fails fast (a connection
137
+ * error or a gateway status) starts the second at once instead of at the hedge
138
+ * point.
125
139
  *
126
- * What is retried: a timeout, a connection error, and the gateway statuses
127
- * that mean the request never reached the application (408, 502, 503, 504 and
128
- * Cloudflare's 52x). Nothing else is: a 4xx or a 500 repeats exactly, and a
129
- * response that arrives is final.
140
+ * What counts as an answer: any response other than a gateway status (408, 502,
141
+ * 503, 504, Cloudflare's 52x) and other than the server's "the first request is
142
+ * still working" reply (HOOK_REPLAY_HEADER: pending). A 4xx or a 500 is an
143
+ * answer (null to the caller): repeating it would repeat the failure.
130
144
  *
131
- * Nothing is queued or stored on the client. A call that fails twice is dropped,
132
- * as before. The server keeps an answer for 15 s so the second attempt can have
133
- * it when the first attempt gave up on an answer that was already decided.
145
+ * The server de-duplicates the two requests by HOOK_REQUEST_ID_HEADER
146
+ * (src/server/hookReplay.ts): the second request is handed the first one's
147
+ * answer, or waits for it, and nothing is counted twice. Nothing is queued or
148
+ * stored on the client; a call with no answer by the deadline is dropped.
134
149
  */
135
- export const HOOK_FIRST_ATTEMPT_SHARE = 0.65;
150
+ export const HOOK_HEDGE_SHARE = 0.65;
136
151
 
137
- /** Below this much budget left, a second attempt cannot complete a round trip. */
152
+ /** Below this much budget left, a second request cannot complete a round trip. */
138
153
  export const HOOK_SECOND_ATTEMPT_MIN_MS = 300;
139
154
 
140
- /** Sent on every attempt so the server can count how many calls needed a second one. */
155
+ /** Sent on every request: 1 for the first, 2 for the hedge. */
141
156
  export const HOOK_ATTEMPT_HEADER = 'x-mnemonik-hook-attempt';
142
157
 
143
158
  /**
144
- * Sent on both attempts with the same value. The server keeps the first
145
- * attempt's answer for a few seconds under this id and hands it to the second
146
- * attempt, so an answer decided after the first attempt gave up is delivered
147
- * rather than lost, and nothing is counted twice (src/server/hookReplay.ts).
159
+ * Sent on both requests with the same value. The server keeps the first
160
+ * request's answer for a few seconds under this id and hands it to the second,
161
+ * so an answer decided by one request is delivered through either, and nothing
162
+ * is counted twice (src/server/hookReplay.ts).
148
163
  */
149
164
  export const HOOK_REQUEST_ID_HEADER = 'x-mnemonik-hook-request-id';
150
165
 
151
166
  /**
152
- * Sent on every attempt: how many milliseconds this attempt may still take.
153
- * The server never waits for a first attempt's answer longer than this less a
154
- * margin for the return trip, so it does not hold a request for a client that
155
- * has already given up.
167
+ * Sent on every request: how many milliseconds the caller will still wait. The
168
+ * server fits its own work inside this less the return trip, so it never
169
+ * decides an answer the client will not be there to receive.
156
170
  */
157
171
  export const HOOK_BUDGET_HEADER = 'x-mnemonik-hook-budget-ms';
158
172
 
@@ -171,11 +185,75 @@ export function withHookVersion<T extends { headers?: unknown }>(
171
185
  runtime: string,
172
186
  version: string
173
187
  ): T {
174
- const headers = new Headers(init.headers as ConstructorParameters<typeof Headers>[0]);
188
+ const raw = init.headers;
189
+ if (raw && typeof raw === 'object' && !(raw instanceof Headers) && !Array.isArray(raw)) {
190
+ // A plain record is copied with its property descriptors, not its values:
191
+ // the hedged hook client's budget header is a getter read when the
192
+ // request is sent, after the credential is read (hedgedHookRequest).
193
+ const headers = Object.defineProperties({}, Object.getOwnPropertyDescriptors(raw)) as Record<
194
+ string,
195
+ string
196
+ >;
197
+ for (const name of Object.keys(headers)) {
198
+ if (name.toLowerCase() === HOOK_VERSION_HEADER) delete headers[name];
199
+ }
200
+ headers[HOOK_VERSION_HEADER] = `${runtime}/${version}`;
201
+ return { ...init, headers };
202
+ }
203
+ const headers = new Headers(raw as ConstructorParameters<typeof Headers>[0]);
175
204
  headers.set(HOOK_VERSION_HEADER, `${runtime}/${version}`);
176
205
  return { ...init, headers: Object.fromEntries(headers.entries()) };
177
206
  }
178
207
 
208
+ /**
209
+ * Sent on every request by a hedging client (hedgedHookRequest). Its budget
210
+ * header is what the whole call still has; clients v7.149 to v7.151 sent the
211
+ * first attempt's own 1.3 s cut-off instead, so a server that sees no marker
212
+ * assumes the whole-call 2 s budget rather than trusting that header.
213
+ */
214
+ export const HOOK_HEDGED_HEADER = 'x-mnemonik-hook-hedged';
215
+
216
+ /**
217
+ * Sent on the second request only: what had become of the first when the second
218
+ * left. `pending; sent=812` (still waiting, its body finished sending 812 ms
219
+ * earlier), `pending; sent=none` (it had not finished sending, so the client
220
+ * itself was slow), `gateway; sent=<ms>` (the edge answered 502/503/504/52x) or
221
+ * `transport; sent=<ms>` (the connection failed). The server uses it to count
222
+ * requests the network lost on the way in, which is what the edge alarm reads
223
+ * (src/server/hookReplay.ts, hookEdgeMetrics.ts).
224
+ */
225
+ export const HOOK_FIRST_ATTEMPT_HEADER = 'x-mnemonik-hook-first-attempt';
226
+
227
+ /**
228
+ * Set by the server on a reply that is not an answer: the request found the
229
+ * other request of the same call still working on it and could not wait any
230
+ * longer. The client keeps waiting for the other request.
231
+ */
232
+ export const HOOK_REPLAY_HEADER = 'x-mnemonik-hook-replay';
233
+ export const HOOK_REPLAY_PENDING = 'pending';
234
+
235
+ export type HookFirstAttemptState = 'pending' | 'gateway' | 'transport';
236
+
237
+ export interface HookFirstAttempt {
238
+ state: HookFirstAttemptState;
239
+ /** Milliseconds since the first request finished sending its body; null when it had not. */
240
+ sentAgoMs: number | null;
241
+ }
242
+
243
+ export function formatHookFirstAttempt(first: HookFirstAttempt): string {
244
+ return `${first.state}; sent=${first.sentAgoMs === null ? 'none' : Math.max(0, Math.round(first.sentAgoMs))}`;
245
+ }
246
+
247
+ export function parseHookFirstAttempt(value: unknown): HookFirstAttempt | null {
248
+ if (typeof value !== 'string') return null;
249
+ const match = /^(pending|gateway|transport); sent=(none|\d{1,6})$/.exec(value.trim());
250
+ if (!match) return null;
251
+ return {
252
+ state: match[1] as HookFirstAttemptState,
253
+ sentAgoMs: match[2] === 'none' ? null : Number(match[2]),
254
+ };
255
+ }
256
+
179
257
  /** Statuses that mean the request did not reach, or was not served by, the application. */
180
258
  export function isRetryableHookStatus(status: number): boolean {
181
259
  return (
@@ -200,44 +278,157 @@ export function isTransientHookFetchError(error: unknown): boolean {
200
278
  );
201
279
  }
202
280
 
203
- export type HookAttemptResult<T> = { done: true; value: T } | { done: false };
281
+ /**
282
+ * When the first request finished sending its body, read from Node's fetch
283
+ * (undici) diagnostics channels. Matched by the request id header, so other
284
+ * requests the process makes at the same time are ignored. Reports null when
285
+ * the channels are unavailable or the body never finished sending; nothing
286
+ * depends on it except the HOOK_FIRST_ATTEMPT_HEADER the server counts.
287
+ */
288
+ function watchFirstRequestSent(
289
+ requestId: string,
290
+ clock: () => number
291
+ ): { sentAt(): number | null; stop(): void } {
292
+ let sentAt: number | null = null;
293
+ let request: object | null = null;
294
+ const onCreate = (message: unknown): void => {
295
+ const candidate = (message as { request?: { headers?: unknown } } | null)?.request;
296
+ if (request || !candidate) return;
297
+ if (String(candidate.headers ?? '').includes(requestId)) request = candidate;
298
+ };
299
+ const onBodySent = (message: unknown): void => {
300
+ if (sentAt === null && request && (message as { request?: object })?.request === request) {
301
+ sentAt = clock();
302
+ }
303
+ };
304
+ try {
305
+ diagnosticsChannel.subscribe('undici:request:create', onCreate);
306
+ diagnosticsChannel.subscribe('undici:request:bodySent', onBodySent);
307
+ } catch {
308
+ return { sentAt: () => null, stop: () => undefined };
309
+ }
310
+ return {
311
+ sentAt: () => sentAt,
312
+ stop: () => {
313
+ try {
314
+ diagnosticsChannel.unsubscribe('undici:request:create', onCreate);
315
+ diagnosticsChannel.unsubscribe('undici:request:bodySent', onBodySent);
316
+ } catch {
317
+ // Nothing to undo.
318
+ }
319
+ },
320
+ };
321
+ }
322
+
323
+ type HookAttemptOutcome<T> =
324
+ { final: true; value: T | null } | { final: false; kind: 'gateway' | 'transport' | 'pending' };
204
325
 
205
326
  /**
206
- * Run `attempt` and, when it ends in a transient failure, run it once more
207
- * inside the rest of `budgetMs`. Returns the value of the attempt that
208
- * finished, or null when neither did. `attempt` returns `{ done: false }` for
209
- * a retryable response and throws for a transport failure; anything else it
210
- * returns is final.
327
+ * Send one hook call as up to two hedged requests inside `budgetMs` (see
328
+ * HOOK_HEDGE_SHARE). `send` performs one request with the headers and signal it
329
+ * is given; `parse` reads an answer. Returns the first answer, null when no
330
+ * request answered in time or the answer was an error status, and rejects only
331
+ * when `send` or `parse` fails in a way that is not a transport failure.
211
332
  */
212
- export async function withSecondAttempt<T>(
333
+ export function hedgedHookRequest<T>(
213
334
  budgetMs: number,
214
- attempt: (
215
- signal: AbortSignal,
216
- attemptNumber: 1 | 2,
217
- requestId: string,
218
- budgetMs: number
219
- ) => Promise<HookAttemptResult<T>>,
335
+ send: (headers: Record<string, string>, signal: AbortSignal) => Promise<Response>,
336
+ parse: (response: Response) => Promise<T>,
220
337
  clock: () => number = Date.now
221
338
  ): Promise<T | null> {
222
339
  const startedAt = clock();
340
+ const deadline = startedAt + budgetMs;
223
341
  const requestId = globalThis.crypto.randomUUID();
224
- const run = async (attemptNumber: 1 | 2, timeoutMs: number): Promise<HookAttemptResult<T>> => {
225
- const { signal, cleanup } = withHookTimeout(timeoutMs);
226
- try {
227
- return await attempt(signal, attemptNumber, requestId, timeoutMs);
228
- } catch (error) {
229
- if (!isTransientHookFetchError(error)) throw error;
230
- return { done: false };
231
- } finally {
232
- cleanup();
233
- }
234
- };
342
+ const sent = watchFirstRequestSent(requestId, clock);
343
+ const controllers: AbortController[] = [];
344
+
345
+ return new Promise<T | null>((resolve, reject) => {
346
+ let settled = false;
347
+ let running = 0;
348
+ let secondStarted = false;
349
+ let firstFailure: 'gateway' | 'transport' | null = null;
350
+ let hedgeTimer: ReturnType<typeof setTimeout> | undefined;
351
+
352
+ const finish = (value: T | null, error?: unknown, winner?: AbortController): void => {
353
+ if (settled) return;
354
+ settled = true;
355
+ clearTimeout(deadlineTimer);
356
+ clearTimeout(hedgeTimer);
357
+ sent.stop();
358
+ // Cancel whatever is still in flight; the request that answered is done.
359
+ for (const controller of controllers) if (controller !== winner) controller.abort();
360
+ if (error !== undefined) reject(error);
361
+ else resolve(value);
362
+ };
363
+ const deadlineTimer = setTimeout(() => finish(null), budgetMs);
364
+
365
+ const startSecond = (): boolean => {
366
+ if (settled || secondStarted) return secondStarted;
367
+ if (deadline - clock() < HOOK_SECOND_ATTEMPT_MIN_MS) return false;
368
+ secondStarted = true;
369
+ clearTimeout(hedgeTimer);
370
+ launch(2);
371
+ return true;
372
+ };
235
373
 
236
- const first = await run(1, Math.floor(budgetMs * HOOK_FIRST_ATTEMPT_SHARE));
237
- if (first.done) return first.value;
374
+ const launch = (attemptNumber: 1 | 2): void => {
375
+ const controller = new AbortController();
376
+ controllers.push(controller);
377
+ const now = clock();
378
+ const headers: Record<string, string> = {
379
+ [HOOK_ATTEMPT_HEADER]: String(attemptNumber),
380
+ [HOOK_REQUEST_ID_HEADER]: requestId,
381
+ [HOOK_HEDGED_HEADER]: '1',
382
+ };
383
+ // Read when the request is actually built (after the credential read or
384
+ // rotation and the conversation lock), not when the attempt starts, so
385
+ // the server's deadline does not include time already spent here.
386
+ Object.defineProperty(headers, HOOK_BUDGET_HEADER, {
387
+ enumerable: true,
388
+ get: () => String(Math.max(0, Math.floor(deadline - clock()))),
389
+ });
390
+ if (attemptNumber === 2) {
391
+ const sentAt = sent.sentAt();
392
+ headers[HOOK_FIRST_ATTEMPT_HEADER] = formatHookFirstAttempt({
393
+ state: firstFailure ?? 'pending',
394
+ sentAgoMs: sentAt === null ? null : now - sentAt,
395
+ });
396
+ }
397
+ running += 1;
398
+ void (async () => {
399
+ let outcome: HookAttemptOutcome<T>;
400
+ try {
401
+ const response = await send(headers, controller.signal);
402
+ if (isRetryableHookStatus(response.status)) outcome = { final: false, kind: 'gateway' };
403
+ else if (response.headers.get(HOOK_REPLAY_HEADER) === HOOK_REPLAY_PENDING)
404
+ outcome = { final: false, kind: 'pending' };
405
+ else if (!response.ok) outcome = { final: true, value: null };
406
+ else outcome = { final: true, value: await parse(response) };
407
+ } catch (error) {
408
+ if (!settled && !isTransientHookFetchError(error)) {
409
+ running -= 1;
410
+ finish(null, error);
411
+ return;
412
+ }
413
+ outcome = { final: false, kind: 'transport' };
414
+ }
415
+ running -= 1;
416
+ if (settled) return;
417
+ if (outcome.final) {
418
+ finish(outcome.value, undefined, controller);
419
+ return;
420
+ }
421
+ // Not an answer. The first request's failure starts the second at once;
422
+ // with no request left running there is no answer to wait for.
423
+ if (attemptNumber === 1) {
424
+ if (outcome.kind !== 'pending') firstFailure = outcome.kind;
425
+ startSecond();
426
+ }
427
+ if (running === 0) finish(null);
428
+ })();
429
+ };
238
430
 
239
- const remainingMs = budgetMs - (clock() - startedAt);
240
- if (remainingMs < HOOK_SECOND_ATTEMPT_MIN_MS) return null;
241
- const second = await run(2, Math.floor(remainingMs));
242
- return second.done ? second.value : null;
431
+ launch(1);
432
+ hedgeTimer = setTimeout(startSecond, Math.floor(budgetMs * HOOK_HEDGE_SHARE));
433
+ });
243
434
  }