pi-dent-agent 0.2.9 → 0.2.11

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.
Files changed (39) hide show
  1. package/lib/plugin-state.ts +587 -0
  2. package/lib/plugin-ui.ts +2 -0
  3. package/lib/script-runner.ts +8 -0
  4. package/lib/script-tool.ts +3 -0
  5. package/lib/script-worker.ts +78 -7
  6. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/CacheStore.md +11 -0
  7. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Client.md +1 -1
  8. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Connector.md +9 -2
  9. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Dispatcher.md +20 -0
  10. package/node_modules/pi-web-access/node_modules/undici/docs/docs/api/Interceptors.md +13 -3
  11. package/node_modules/pi-web-access/node_modules/undici/docs/docs/best-practices/mocking-request.md +1 -1
  12. package/node_modules/pi-web-access/node_modules/undici/lib/api/abort-signal.js +55 -5
  13. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-connect.js +6 -2
  14. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-pipeline.js +7 -2
  15. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-request.js +12 -4
  16. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-stream.js +6 -2
  17. package/node_modules/pi-web-access/node_modules/undici/lib/api/api-upgrade.js +6 -2
  18. package/node_modules/pi-web-access/node_modules/undici/lib/core/request.js +17 -0
  19. package/node_modules/pi-web-access/node_modules/undici/lib/core/symbols.js +3 -1
  20. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h1.js +24 -0
  21. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client-h2.js +11 -5
  22. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/client.js +109 -2
  23. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher-base.js +6 -1
  24. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/dispatcher.js +22 -1
  25. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool-base.js +72 -16
  26. package/node_modules/pi-web-access/node_modules/undici/lib/dispatcher/pool.js +22 -9
  27. package/node_modules/pi-web-access/node_modules/undici/lib/handler/cache-handler.js +1 -1
  28. package/node_modules/pi-web-access/node_modules/undici/lib/handler/retry-handler.js +27 -1
  29. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/cache.js +9 -2
  30. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/decompress.js +0 -11
  31. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/deduplicate.js +4 -1
  32. package/node_modules/pi-web-access/node_modules/undici/lib/interceptor/redirect.js +4 -1
  33. package/node_modules/pi-web-access/node_modules/undici/lib/util/cache.js +1 -1
  34. package/node_modules/pi-web-access/node_modules/undici/lib/util/timers.js +1 -1
  35. package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/index.js +20 -1
  36. package/node_modules/pi-web-access/node_modules/undici/lib/web/fetch/util.js +2 -2
  37. package/node_modules/pi-web-access/node_modules/undici/package.json +3 -3
  38. package/node_modules/pi-web-access/node_modules/undici/types/retry-handler.d.ts +1 -1
  39. package/package.json +1 -1
@@ -6,6 +6,18 @@ import { ChildProcess } from "node:child_process";
6
6
  import * as vm from "node:vm";
7
7
  import { Writable } from "node:stream";
8
8
  import { isJsonCompatible, renderReturn } from "./script-render.ts";
9
+ import {
10
+ deletePluginState,
11
+ ensurePluginStateDataDir,
12
+ getPluginState,
13
+ listPluginStateKeys,
14
+ setPluginState,
15
+ watchPluginState,
16
+ type PluginStateChangeListener,
17
+ type PluginStateScope,
18
+ type PluginStateTarget,
19
+ type PluginStateWatcher,
20
+ } from "./plugin-state.ts";
9
21
  import { TEMP_VARIABLES } from "./session-tmp.ts";
10
22
  import { parentPort, workerData } from "node:worker_threads";
11
23
  import { createJiti } from "jiti";
@@ -34,6 +46,10 @@ interface ScriptWorkerData {
34
46
  toolTypes: string;
35
47
  /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
36
48
  uiCall?: boolean;
49
+ /** Plugin namespace when running a plugin script (specs/plugin-state.md Section 6). */
50
+ pluginNamespace?: string;
51
+ /** Workspace root for `dent.state` (defaults to `cwd`). */
52
+ stateWorkspaceRoot?: string;
37
53
  }
38
54
 
39
55
  const port = parentPort;
@@ -55,9 +71,22 @@ class ScriptExit extends Error {}
55
71
 
56
72
  const isScriptExit = (value: unknown): boolean => value instanceof ScriptExit;
57
73
 
74
+ const activeStateWatchers = new Set<PluginStateWatcher>();
75
+ const closeStateWatchers = (): void => {
76
+ for (const watcher of activeStateWatchers) {
77
+ try {
78
+ watcher.close();
79
+ } catch {
80
+ // Best effort.
81
+ }
82
+ }
83
+ activeStateWatchers.clear();
84
+ };
85
+
58
86
  /** Settle `exit-called` and end the script's flow (Section 3). */
59
87
  const postExit = (code?: number): never => {
60
88
  exitCalled = true;
89
+ closeStateWatchers();
61
90
  try {
62
91
  port.postMessage({ type: "exit-called", code: code ?? 0 });
63
92
  } catch {
@@ -250,13 +279,53 @@ const sendUiMessage = (payload: unknown): void => {
250
279
  // Port closed.
251
280
  }
252
281
  };
253
- const scriptDent =
254
- data.uiCall === true
255
- ? Object.freeze({
256
- toolTypes: (): string => data.toolTypes,
257
- ui: Object.freeze({ send: sendUiMessage }),
258
- })
259
- : Object.freeze({ toolTypes: (): string => data.toolTypes });
282
+ const makeStateScopeBinding = (namespace: string, scope: PluginStateScope) => {
283
+ const target: PluginStateTarget =
284
+ scope === "workspace"
285
+ ? { namespace, scope, workspaceRoot: data.stateWorkspaceRoot ?? data.cwd }
286
+ : { namespace, scope };
287
+ const binding = {
288
+ get: (key: string, defaultValue?: unknown): Promise<unknown> =>
289
+ getPluginState(target, key, defaultValue),
290
+ set: (key: string, value: unknown): Promise<void> => setPluginState(target, key, value),
291
+ delete: (key: string): Promise<void> => deletePluginState(target, key),
292
+ keys: (): Promise<string[]> => listPluginStateKeys(target),
293
+ onChange: (listener: PluginStateChangeListener): (() => void) => {
294
+ if (typeof listener !== "function") {
295
+ throw new TypeError("onChange listener must be a function");
296
+ }
297
+ const watcher = watchPluginState(target, (key, value) => {
298
+ if (exitCalled) return;
299
+ listener(key, value);
300
+ });
301
+ activeStateWatchers.add(watcher);
302
+ return () => {
303
+ watcher.close();
304
+ activeStateWatchers.delete(watcher);
305
+ };
306
+ },
307
+ get dir(): string {
308
+ return ensurePluginStateDataDir(target);
309
+ },
310
+ };
311
+ return binding;
312
+ };
313
+
314
+ const scriptState =
315
+ typeof data.pluginNamespace === "string" && data.pluginNamespace !== ""
316
+ ? (() => {
317
+ const ws = makeStateScopeBinding(data.pluginNamespace, "workspace");
318
+ const user = Object.freeze(makeStateScopeBinding(data.pluginNamespace, "user"));
319
+ Object.defineProperty(ws, "user", { value: user, enumerable: true });
320
+ return Object.freeze(ws);
321
+ })()
322
+ : undefined;
323
+
324
+ const scriptDent = Object.freeze({
325
+ toolTypes: (): string => data.toolTypes,
326
+ ...(data.uiCall === true ? { ui: Object.freeze({ send: sendUiMessage }) } : {}),
327
+ ...(scriptState === undefined ? {} : { state: scriptState }),
328
+ });
260
329
  Object.defineProperty(globalThis, "tools", {
261
330
  value: scriptTools,
262
331
  writable: true,
@@ -1094,6 +1163,7 @@ void (async () => {
1094
1163
  mod = { default: completion };
1095
1164
  }
1096
1165
  } catch (err) {
1166
+ closeStateWatchers();
1097
1167
  // The exit already settled the run (Section 3); the worker stays up for the
1098
1168
  // runner's termination and the reaping of the tree it kills (Section 6).
1099
1169
  if (exitCalled || isScriptExit(err)) return;
@@ -1101,6 +1171,7 @@ void (async () => {
1101
1171
  reportError(e);
1102
1172
  return;
1103
1173
  }
1174
+ closeStateWatchers();
1104
1175
  // A script that caught the exit's error reaches its own end; its run already
1105
1176
  // settled as exit-called, so there is no result to report.
1106
1177
  if (exitCalled) return;
@@ -203,6 +203,16 @@ added: v7.0.0
203
203
  integers; a `TypeError` is thrown otherwise, or if `maxEntrySize` is greater
204
204
  than 2 GB.
205
205
 
206
+ The database is not encrypted, and nothing in it is hashed. The request URL
207
+ (including the query string), the response headers and body, and the values of
208
+ any request headers named in the response's `Vary` header (for example
209
+ `Authorization` or `Cookie`) are written as plain text to `location`. Protect
210
+ that file like any other sensitive data, or use `':memory:'`. A response to a
211
+ request that carries `Authorization` is only stored when the response allows it
212
+ with `public`, `s-maxage`, or `must-revalidate` (see [RFC 9111, Section 3.5][]);
213
+ servers can send `Cache-Control: no-store` to keep a response out of the cache
214
+ entirely.
215
+
206
216
  ### `sqliteCacheStore.close()`
207
217
 
208
218
  <!-- YAML
@@ -372,4 +382,5 @@ The value returned by `get`. It contains every field of
372
382
  body. (optional)
373
383
 
374
384
  [RFC&nbsp;9111]: https://www.rfc-editor.org/rfc/rfc9111.html
385
+ [RFC 9111, Section 3.5]: https://www.rfc-editor.org/rfc/rfc9111.html#section-3.5
375
386
  [`node:sqlite`]: https://nodejs.org/api/sqlite.html
@@ -217,7 +217,7 @@ import { Client, buildConnector } from 'undici'
217
217
  const connector = buildConnector({ rejectUnauthorized: false })
218
218
  const client = new Client('https://localhost:3000', {
219
219
  connect (opts, cb) {
220
- connector(opts, (err, socket) => {
220
+ return connector(opts, (err, socket) => {
221
221
  if (err) {
222
222
  cb(err)
223
223
  } else {
@@ -78,7 +78,7 @@ const connector = buildConnector({ rejectUnauthorized: false })
78
78
 
79
79
  const client = new Client('https://localhost:3000', {
80
80
  connect (opts, cb) {
81
- connector(opts, (err, socket) => {
81
+ return connector(opts, (err, socket) => {
82
82
  if (err) {
83
83
  cb(err)
84
84
  } else if (/* assertion */ false) {
@@ -124,6 +124,13 @@ targets or a [`tls.TLSSocket`][] for `https:` targets, applies TCP keep-alive an
124
124
  the connect timeout, and invokes `callback` once the socket connects or errors.
125
125
  The socket is also returned synchronously.
126
126
 
127
+ undici uses the returned socket to cancel a connection attempt that no request
128
+ needs any more: once every request waiting for it is aborted, the socket is
129
+ destroyed and the next request opens a new connection instead of waiting for
130
+ it. A connector that wraps another one should return the socket it gets back,
131
+ as the examples on this page do. If it returns nothing, the attempt runs until
132
+ it connects or fails.
133
+
127
134
  When connecting over TLS, established sessions are cached (subject to
128
135
  `maxCachedSessions`) and reused for subsequent connections to the same
129
136
  `servername` or `hostname`.
@@ -141,7 +148,7 @@ const connector = buildConnector({ rejectUnauthorized: false })
141
148
 
142
149
  const client = new Client('https://localhost:3000', {
143
150
  connect (opts, cb) {
144
- connector(opts, (err, socket) => {
151
+ return connector(opts, (err, socket) => {
145
152
  if (err) {
146
153
  cb(err)
147
154
  } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) {
@@ -705,6 +705,26 @@ The order of the interceptors matters: the last interceptor in the chain is the
705
705
  first to be called. Forking the chain of interceptors can lead to unexpected
706
706
  results.
707
707
 
708
+ Because interceptors wrap each other, ordering is the end-user's responsibility.
709
+ Certain built-in interceptors are order-sensitive and will throw an
710
+ `InvalidArgumentError` if composed in an unsafe order. In particular, the
711
+ `cache` interceptor must be composed **after** the `redirect` interceptor. When
712
+ `cache` is composed before `redirect`, the cache handler is wrapped *above* the
713
+ redirect handler, so it never observes the redirect history and its
714
+ cross-origin / credential-bearing redirect guards are silently disabled.
715
+ This allows an attacker-controlled or cross-principal redirect response to be
716
+ stored under the trusted origin's cache key and replayed to unrelated callers
717
+ (see GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26 and
718
+ GHSA-7XG3-FPHP-28HG).
719
+
720
+ ```js
721
+ // Correct: cache is composed after redirect.
722
+ new Agent().compose(interceptors.redirect({ maxRedirections: 5 }), interceptors.cache({}))
723
+
724
+ // Throws an InvalidArgumentError: cache composed before redirect.
725
+ new Agent().compose(interceptors.cache({}), interceptors.redirect({ maxRedirections: 5 }))
726
+ ```
727
+
708
728
  ```text
709
729
  compose([interceptor1, interceptor2, interceptor3])
710
730
 
@@ -204,9 +204,6 @@ and `x-compress`, is left untouched, matching `fetch()`. As required by
204
204
  [RFC 9659](https://www.rfc-editor.org/rfc/rfc9659.html), a `zstd` frame that
205
205
  requires a window size larger than 8 MB fails to decode.
206
206
 
207
- > **Experimental:** This interceptor is experimental and subject to change.
208
- > A one-time `ExperimentalWarning` is emitted on first use.
209
-
210
207
  **Parameters**
211
208
 
212
209
  * `opts` {Object} (optional)
@@ -359,12 +356,25 @@ backing store.
359
356
 
360
357
  **Returns:** {Dispatcher.DispatcherComposeInterceptor}
361
358
 
359
+ > **Ordering:** the `cache` interceptor must be composed **after** the
360
+ > `redirect` interceptor. When `cache` is composed before `redirect`, the cache
361
+ > handler is wrapped above the redirect handler, so it never observes the
362
+ > redirect history and its cross-origin / credential-bearing redirect guards are
363
+ > silently disabled, which lets an attacker-controlled or cross-principal
364
+ > redirect response be stored under the trusted origin's cache key and replayed
365
+ > to unrelated callers (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32,
366
+ > GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG). `compose()` throws an
367
+ > `InvalidArgumentError` for this unsafe order. The `deduplicate` interceptor
368
+ > participates in the same redirect-history contract and may be placed before or
369
+ > after `redirect`, as long as `cache` follows `redirect`.
370
+
362
371
  **Example**
363
372
 
364
373
  ```js
365
374
  import { Agent, interceptors, cacheStores } from 'undici'
366
375
 
367
376
  const agent = new Agent().compose(
377
+ interceptors.redirect({ maxRedirections: 5 }),
368
378
  interceptors.cache({ store: new cacheStores.MemoryCacheStore() })
369
379
  )
370
380
  ```
@@ -61,7 +61,7 @@ const success = await bankTransfer('1234567890', '100')
61
61
 
62
62
  assert.deepEqual(success, { message: 'transaction processed' })
63
63
 
64
- // if you dont want to check whether the body or the headers contain the same value
64
+ // if you don't want to check whether the body or the headers contain the same value
65
65
  // just remove it from interceptor
66
66
  mockPool.intercept({
67
67
  path: '/bank-transfer',
@@ -2,15 +2,17 @@
2
2
 
3
3
  const { addAbortListener } = require('../core/util')
4
4
  const { RequestAbortedError } = require('../core/errors')
5
+ const { kQueuedAbort } = require('../core/symbols')
5
6
 
6
7
  const kListener = Symbol('kListener')
7
8
  const kSignal = Symbol('kSignal')
8
9
 
9
10
  function abort (self) {
11
+ // Keep the reason even when abort is set: a queued request that cannot be
12
+ // taken out of its queue is aborted once it starts.
13
+ self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
10
14
  if (self.abort) {
11
- self.abort(self[kSignal]?.reason)
12
- } else {
13
- self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
15
+ self.abort(self.reason)
14
16
  }
15
17
  removeSignal(self)
16
18
  }
@@ -26,7 +28,7 @@ function addSignal (self, signal) {
26
28
  }
27
29
 
28
30
  if (signal.aborted) {
29
- abort(self)
31
+ self.reason = signal.reason ?? new RequestAbortedError()
30
32
  return
31
33
  }
32
34
 
@@ -53,7 +55,55 @@ function removeSignal (self) {
53
55
  self[kListener] = null
54
56
  }
55
57
 
58
+ // Dispatchers call the kQueuedAbort hook while a request waits for a
59
+ // connection, with a function that takes it out of their queue. Until the
60
+ // request starts, the handler's abort calls that function.
61
+ //
62
+ // A retry or a redirect dispatches the same handler again after an earlier
63
+ // attempt started. The handler's abort then also calls the controller of that
64
+ // attempt: it does nothing once the attempt is over, and still reaches a
65
+ // response that a retry resumes.
66
+ function queuedAbortHook (handler) {
67
+ // The abort set by onRequestStart, and the one this hook installed last.
68
+ let started = null
69
+ let installed = null
70
+ return (cancel) => {
71
+ if (handler.reason) {
72
+ cancel(handler.reason)
73
+ return
74
+ }
75
+
76
+ if (handler.abort !== installed) {
77
+ started = handler.abort
78
+ }
79
+
80
+ if (started === null) {
81
+ installed = cancel
82
+ } else {
83
+ const abortStarted = started
84
+ installed = (reason) => {
85
+ abortStarted(reason)
86
+ cancel(reason)
87
+ }
88
+ }
89
+ handler.abort = installed
90
+ }
91
+ }
92
+
93
+ // Dispatches a request whose options carry a signal. Requests without a signal
94
+ // are dispatched directly and never reach this function.
95
+ function dispatchWithSignal (dispatcher, opts, handler) {
96
+ if (handler.reason) {
97
+ // Already aborted: fail without dispatching, so no connection is opened.
98
+ handler.onResponseError(null, handler.reason)
99
+ return
100
+ }
101
+
102
+ dispatcher.dispatch({ ...opts, [kQueuedAbort]: queuedAbortHook(handler) }, handler)
103
+ }
104
+
56
105
  module.exports = {
57
106
  addSignal,
58
- removeSignal
107
+ removeSignal,
108
+ dispatchWithSignal
59
109
  }
@@ -4,7 +4,7 @@ const assert = require('node:assert')
4
4
  const { AsyncResource } = require('node:async_hooks')
5
5
  const { InvalidArgumentError, SocketError } = require('../core/errors')
6
6
  const util = require('../core/util')
7
- const { addSignal, removeSignal } = require('./abort-signal')
7
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
8
8
 
9
9
  class ConnectHandler extends AsyncResource {
10
10
  constructor (opts, callback) {
@@ -99,7 +99,11 @@ function connect (opts, callback) {
99
99
  try {
100
100
  const connectHandler = new ConnectHandler(opts, callback)
101
101
  const connectOptions = { ...opts, method: 'CONNECT' }
102
- this.dispatch(connectOptions, connectHandler)
102
+ if (opts.signal == null) {
103
+ this.dispatch(connectOptions, connectHandler)
104
+ } else {
105
+ dispatchWithSignal(this, connectOptions, connectHandler)
106
+ }
103
107
  } catch (err) {
104
108
  if (typeof callback !== 'function') {
105
109
  throw err
@@ -14,7 +14,7 @@ const {
14
14
  } = require('../core/errors')
15
15
  const util = require('../core/util')
16
16
  const { kBodyUsed } = require('../core/symbols')
17
- const { addSignal, removeSignal } = require('./abort-signal')
17
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
18
18
 
19
19
  function noop () {}
20
20
 
@@ -255,7 +255,12 @@ class PipelineHandler extends AsyncResource {
255
255
  function pipeline (opts, handler) {
256
256
  try {
257
257
  const pipelineHandler = new PipelineHandler(opts, handler)
258
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
258
+ const pipelineOpts = { ...opts, body: pipelineHandler.req }
259
+ if (opts.signal == null) {
260
+ this.dispatch(pipelineOpts, pipelineHandler)
261
+ } else {
262
+ dispatchWithSignal(this, pipelineOpts, pipelineHandler)
263
+ }
259
264
  return pipelineHandler.ret
260
265
  } catch (err) {
261
266
  return new PassThrough().destroy(err)
@@ -5,6 +5,7 @@ const { AsyncResource } = require('node:async_hooks')
5
5
  const { Readable } = require('./readable')
6
6
  const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
7
7
  const util = require('../core/util')
8
+ const { dispatchWithSignal } = require('./abort-signal')
8
9
 
9
10
  function noop () {}
10
11
 
@@ -37,6 +38,11 @@ class RequestHandler extends AsyncResource {
37
38
  throw new InvalidArgumentError('invalid onInfo callback')
38
39
  }
39
40
 
41
+ // Reject before dispatching: onRequestStart only runs once a connection is established.
42
+ if (signal?.aborted) {
43
+ throw signal.reason ?? new RequestAbortedError()
44
+ }
45
+
40
46
  super('UNDICI_REQUEST')
41
47
  } catch (err) {
42
48
  if (util.isStream(body)) {
@@ -60,9 +66,7 @@ class RequestHandler extends AsyncResource {
60
66
  this.reason = null
61
67
  this.removeAbortListener = null
62
68
 
63
- if (signal?.aborted) {
64
- this.reason = signal.reason ?? new RequestAbortedError()
65
- } else if (signal) {
69
+ if (signal) {
66
70
  this.removeAbortListener = util.addAbortListener(signal, () => {
67
71
  this.reason = signal.reason ?? new RequestAbortedError()
68
72
  if (this.res) {
@@ -230,7 +234,11 @@ function request (opts, callback) {
230
234
  try {
231
235
  const handler = new RequestHandler(opts, callback)
232
236
 
233
- this.dispatch(opts, handler)
237
+ if (opts.signal == null) {
238
+ this.dispatch(opts, handler)
239
+ } else {
240
+ dispatchWithSignal(this, opts, handler)
241
+ }
234
242
  } catch (err) {
235
243
  if (typeof callback !== 'function') {
236
244
  throw err
@@ -4,7 +4,7 @@ const assert = require('node:assert')
4
4
  const { AsyncResource } = require('node:async_hooks')
5
5
  const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors')
6
6
  const util = require('../core/util')
7
- const { addSignal, removeSignal } = require('./abort-signal')
7
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
8
8
 
9
9
  function noop () {}
10
10
 
@@ -257,7 +257,11 @@ function stream (opts, factory, callback) {
257
257
  try {
258
258
  const handler = new StreamHandler(opts, factory, callback)
259
259
 
260
- this.dispatch(opts, handler)
260
+ if (opts.signal == null) {
261
+ this.dispatch(opts, handler)
262
+ } else {
263
+ dispatchWithSignal(this, opts, handler)
264
+ }
261
265
  } catch (err) {
262
266
  if (typeof callback !== 'function') {
263
267
  throw err
@@ -5,7 +5,7 @@ const { AsyncResource } = require('node:async_hooks')
5
5
  const assert = require('node:assert')
6
6
  const util = require('../core/util')
7
7
  const { kHTTP2Stream } = require('../core/symbols')
8
- const { addSignal, removeSignal } = require('./abort-signal')
8
+ const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
9
9
 
10
10
  class UpgradeHandler extends AsyncResource {
11
11
  constructor (opts, callback) {
@@ -108,7 +108,11 @@ function upgrade (opts, callback) {
108
108
  method: opts.method || 'GET',
109
109
  upgrade: opts.protocol || 'Websocket'
110
110
  }
111
- this.dispatch(upgradeOpts, upgradeHandler)
111
+ if (opts.signal == null) {
112
+ this.dispatch(upgradeOpts, upgradeHandler)
113
+ } else {
114
+ dispatchWithSignal(this, upgradeOpts, upgradeHandler)
115
+ }
112
116
  } catch (err) {
113
117
  if (typeof callback !== 'function') {
114
118
  throw err
@@ -47,6 +47,8 @@ const kHandler = Symbol('handler')
47
47
  const kController = Symbol('controller')
48
48
  const kResume = Symbol('resume')
49
49
 
50
+ function noop () {}
51
+
50
52
  class RequestController {
51
53
  #paused = false
52
54
  #reason = null
@@ -463,12 +465,26 @@ class Request {
463
465
  }
464
466
  }
465
467
 
468
+ // Fails a request that was aborted before it reached a connection. The
469
+ // handler gets an aborted controller, so wrappers such as RetryHandler can
470
+ // tell a caller abort apart from a retryable connection failure.
471
+ onQueuedAbort (reason) {
472
+ this[kController] = createAbortedController(reason)
473
+ return this.onResponseError(reason)
474
+ }
475
+
466
476
  addHeader (key, value) {
467
477
  processHeader(this, key, value)
468
478
  return this
469
479
  }
470
480
  }
471
481
 
482
+ function createAbortedController (reason) {
483
+ const controller = new RequestController(noop)
484
+ controller.abort(reason)
485
+ return controller
486
+ }
487
+
472
488
  function processHeader (request, key, val) {
473
489
  if (val && (typeof val === 'object' && !Array.isArray(val))) {
474
490
  throw new InvalidArgumentError(`invalid ${key} header`)
@@ -580,3 +596,4 @@ function isUndiciFormData (body) {
580
596
  }
581
597
 
582
598
  module.exports = Request
599
+ module.exports.createAbortedController = createAbortedController
@@ -60,6 +60,7 @@ module.exports = {
60
60
  kMaxResponseSize: Symbol('max response size'),
61
61
  kHTTP2Session: Symbol('http2Session'),
62
62
  kHTTP2Options: Symbol('http2 options'),
63
+ kQueuedAbort: Symbol('queued abort'),
63
64
  kHTTP2SessionState: Symbol('http2Session state'),
64
65
  kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
65
66
  kConstruct: Symbol('constructable'),
@@ -77,5 +78,6 @@ module.exports = {
77
78
  kNoProxyAgent: Symbol('no proxy agent'),
78
79
  kHttpProxyAgent: Symbol('http proxy agent'),
79
80
  kHttpsProxyAgent: Symbol('https proxy agent'),
80
- kSocks5ProxyAgent: Symbol('socks5 proxy agent')
81
+ kSocks5ProxyAgent: Symbol('socks5 proxy agent'),
82
+ kInterceptorKind: Symbol('interceptor kind')
81
83
  }
@@ -67,6 +67,7 @@ const removeAllListeners = util.removeAllListeners
67
67
  const kIdleSocketValidation = Symbol('kIdleSocketValidation')
68
68
  const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
69
69
  const kSocketUsed = Symbol('kSocketUsed')
70
+ const kIdleSince = Symbol('kIdleSince')
70
71
  const kTypeOfService = Symbol('kTypeOfService')
71
72
 
72
73
  let extractBody
@@ -1107,6 +1108,19 @@ function scheduleIdleSocketValidation (client, socket) {
1107
1108
  })
1108
1109
  }
1109
1110
 
1111
+ /**
1112
+ * kIdleSince is recorded when the keep-alive timer is armed, so this never
1113
+ * expires a socket before that timer is due.
1114
+ * @param {import('net').Socket} socket
1115
+ * @returns {boolean}
1116
+ */
1117
+ function isIdleSocketExpired (socket) {
1118
+ const parser = socket[kParser]
1119
+ return parser.timeoutType === TIMEOUT_KEEP_ALIVE &&
1120
+ parser.timeoutValue > 0 &&
1121
+ performance.now() - socket[kIdleSince] >= parser.timeoutValue
1122
+ }
1123
+
1110
1124
  /**
1111
1125
  * @param {import('./client.js')} client
1112
1126
  */
@@ -1124,6 +1138,15 @@ function resumeH1 (client) {
1124
1138
  socket[kNoRef] = false
1125
1139
  }
1126
1140
 
1141
+ // The keep-alive timer cannot fire while the event loop is blocked, and a
1142
+ // request dispatched from the poll phase passes the idle socket validation
1143
+ // below before that timer or a FIN received during the block is processed.
1144
+ // Check the clock so that an expired socket is not reused.
1145
+ if (client[kRunning] === 0 && client[kPending] > 0 && isIdleSocketExpired(socket)) {
1146
+ util.destroy(socket, new InformationalError('socket idle timeout'))
1147
+ return
1148
+ }
1149
+
1127
1150
  if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
1128
1151
  if (socket[kIdleSocketValidation] === 0) {
1129
1152
  scheduleIdleSocketValidation(client, socket)
@@ -1152,6 +1175,7 @@ function resumeH1 (client) {
1152
1175
 
1153
1176
  if (client[kSize] === 0) {
1154
1177
  if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
1178
+ socket[kIdleSince] = performance.now()
1155
1179
  socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
1156
1180
  }
1157
1181
  } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
@@ -91,6 +91,7 @@ const {
91
91
  HTTP2_HEADER_STATUS,
92
92
  HTTP2_HEADER_PROTOCOL,
93
93
  NGHTTP2_NO_ERROR,
94
+ NGHTTP2_PROTOCOL_ERROR,
94
95
  NGHTTP2_REFUSED_STREAM
95
96
  }
96
97
  } = http2
@@ -1684,11 +1685,16 @@ function onError (err) {
1684
1685
  // noop error sink so that re-delivery cannot go unhandled.
1685
1686
  stream.on('error', noop)
1686
1687
 
1687
- // Node's HTTP/2 implementation can turn an incomplete Content-Length body
1688
- // into a protocol stream error instead of emitting 'end'. Prefer the
1689
- // content-length mismatch error when the received byte count proves it.
1690
- if (state.responseContentLength != null && state.bytesRead !== state.responseContentLength) {
1691
- err = new ResponseContentLengthMismatchError()
1688
+ // Node may report Content-Length violations as protocol errors.
1689
+ if (
1690
+ (err.code === 'ERR_HTTP2_ERROR' ||
1691
+ (err.code === 'ERR_HTTP2_STREAM_ERROR' && stream.rstCode === NGHTTP2_PROTOCOL_ERROR)) &&
1692
+ state.responseContentLength != null &&
1693
+ state.bytesRead !== state.responseContentLength
1694
+ ) {
1695
+ const mismatch = new ResponseContentLengthMismatchError()
1696
+ mismatch.cause = err
1697
+ err = mismatch
1692
1698
  }
1693
1699
 
1694
1700
  if (typeof stream.rstCode === 'number' && stream.rstCode !== NGHTTP2_NO_ERROR) {