@orkestrel/scaffold 0.0.112 → 0.0.114

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 (67) hide show
  1. package/dist/agents/skills/orkestrel-harden/scripts/titles.js +3 -3
  2. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +120 -21
  3. package/dist/bin/main.js +71 -23
  4. package/dist/bin/main.js.map +1 -1
  5. package/dist/host/agents/platforms/windows.md +1 -1
  6. package/dist/host/agents/skills/orkestrel-harden/scripts/titles.ts +3 -3
  7. package/dist/host/agents/skills/orkestrel-publish/SKILL.md +7 -7
  8. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +25 -8
  9. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +187 -54
  10. package/dist/host/claude/agents/orkestrel.md +53 -53
  11. package/dist/host/claude/rules/architecture.md +4 -3
  12. package/dist/host/claude/rules/tests.md +24 -7
  13. package/dist/host/claude/rules/typescript.md +11 -2
  14. package/dist/host/claude/rules/workspace.md +32 -28
  15. package/dist/host/configs/policy.ts +49 -0
  16. package/dist/host/dotfiles/gitignore +1 -0
  17. package/dist/host/dotfiles/oxlintrc.json +6 -0
  18. package/dist/host/guides/agent.md +13 -13
  19. package/dist/host/guides/brief.md +4 -0
  20. package/dist/host/guides/browser.md +162 -44
  21. package/dist/host/guides/budget.md +1 -1
  22. package/dist/host/guides/capture.md +4 -0
  23. package/dist/host/guides/console.md +13 -0
  24. package/dist/host/guides/contract.md +38 -3
  25. package/dist/host/guides/csv.md +5 -0
  26. package/dist/host/guides/database.md +58 -8
  27. package/dist/host/guides/form.md +17 -0
  28. package/dist/host/guides/guide.md +36 -33
  29. package/dist/host/guides/html.md +72 -44
  30. package/dist/host/guides/indexeddb.md +4 -0
  31. package/dist/host/guides/lsp.md +49 -8
  32. package/dist/host/guides/markdown.md +146 -1
  33. package/dist/host/guides/mcp.md +117 -22
  34. package/dist/host/guides/middleware.md +194 -26
  35. package/dist/host/guides/msg.md +9 -5
  36. package/dist/host/guides/pool.md +8 -1
  37. package/dist/host/guides/probe.md +13 -1
  38. package/dist/host/guides/process.md +102 -90
  39. package/dist/host/guides/program.md +4 -0
  40. package/dist/host/guides/qualifier.md +4 -0
  41. package/dist/host/guides/rater.md +4 -0
  42. package/dist/host/guides/reason.md +6 -4
  43. package/dist/host/guides/relation.md +4 -0
  44. package/dist/host/guides/scaffold.md +32 -14
  45. package/dist/host/guides/server.md +29 -13
  46. package/dist/host/guides/sqlite.md +6 -0
  47. package/dist/host/guides/sse.md +6 -0
  48. package/dist/host/guides/study.md +473 -473
  49. package/dist/host/guides/table.md +3 -0
  50. package/dist/host/guides/template.md +3 -0
  51. package/dist/host/guides/test.md +38 -20
  52. package/dist/host/guides/tool.md +3 -0
  53. package/dist/host/guides/toolbox.md +21 -0
  54. package/dist/host/guides/websocket.md +3 -1
  55. package/dist/host/guides/workflow.md +103 -11
  56. package/dist/host/guides/workspace.md +4 -0
  57. package/dist/host/manifest.json +56 -56
  58. package/dist/host/tests/config.test.ts +72 -16
  59. package/dist/host/tests/policy.test.ts +21 -7
  60. package/dist/host/tests/setupPolicy.ts +147 -12
  61. package/dist/src/core/index.cjs +22 -28
  62. package/dist/src/core/index.cjs.map +1 -1
  63. package/dist/src/core/index.d.cts +8 -8
  64. package/dist/src/core/index.d.ts +8 -8
  65. package/dist/src/core/index.js +22 -28
  66. package/dist/src/core/index.js.map +1 -1
  67. package/package.json +12 -12
@@ -914,7 +914,7 @@ cares must call `validate` first and return an
914
914
  the missing argument, or seed `missing: 'empty'` and accept the gaps.
915
915
 
916
916
  **The control that proves these are ports rather than shaped holes** is that neither
917
- adapter is privileged. `tests/setupConformance.ts` backs the same ports with plain
917
+ adapter is privileged. `tests/setupServer.ts` backs the same ports with plain
918
918
  in-memory objects — no workspace, no template engine, no `@orkestrel/*` registry at
919
919
  all — and the foreign conformance client cannot tell the difference, because there is
920
920
  nothing on the wire that could. The compiler now agrees with the wire: that fixture is
@@ -2672,7 +2672,7 @@ const routes = createMCPRoutes(createMCPLegacy(mcp)) // answers `initialize` too
2672
2672
 
2673
2673
  #### Carry asserted caller context from HTTP middleware
2674
2674
 
2675
- `HTTPHandlerOptions<TState>` names the POST handler's `streaming`, `origin`,
2675
+ `HTTPHandlerOptions<TState>` names the POST handler's `stream`, `origin`,
2676
2676
  `keepalive`, and `caller` options; `HTTPTransportOptions<TState>` extends that
2677
2677
  shape with `path`. The caller extractor is the synchronous
2678
2678
  `MCPCallerHandler<TState>`:
@@ -2883,10 +2883,10 @@ An extended interface's name comes before `plus`, with the members it adds after
2883
2883
  | `MCPOriginOptions` | interface | `{ enabled?, origins? }` | Configures the protocol-required HTTP `Origin` validation shared by the route and session enforcement sites. |
2884
2884
  | `MCPKeepaliveOptions` | interface | `{ interval? }` | Configures the shared SSE keepalive for held-open HTTP responses. |
2885
2885
  | `MCPCallerHandler` | type | `(request: Request, context: RouteContext<string, TState> \| undefined) => unknown` | Extracts consumer-asserted caller context synchronously from an HTTP request after the transport has validated it for dispatch. |
2886
- | `HTTPHandlerOptions` | interface | `{ streaming?, origin?, keepalive?, caller? }` | Options shared by the MCP Streamable-HTTP POST handler and route factory. |
2886
+ | `HTTPHandlerOptions` | interface | `{ stream?, origin?, keepalive?, caller? }` | Options shared by the MCP Streamable-HTTP POST handler and route factory. |
2887
2887
  | `HTTPTransportOptions` | interface | `HTTPHandlerOptions<TState> plus { path? }` | Options for `createMCPRoutes` — the mount path plus the shared POST-handler options. `createMCPRoutes` is stateless; sessions are a separate middleware (`createMCPSession`), composed with `server.use`. |
2888
2888
  | `MCPSessionOptions` | interface | `{ capacity?, ttl? } plus clock?` | Options for the `MCPSession` entity — its folded replay log's capacity and per-event lifetime. |
2889
- | `MCPSessionMiddlewareOptions` | interface | `{ path?, ttl?, session?, origin?, keepalive? } plus clock?` | Options for `createMCPSession` — the path the session middleware owns, the session idle time-to-live, and the per-session resumable event-log bound. |
2889
+ | `MCPSessionMiddlewareOptions` | interface | `{ path?, ttl?, session?, origin?, keepalive?, store? } plus clock?` | Options for `createMCPSession` — the path the session middleware owns, the session idle time-to-live, and the per-session resumable event-log bound. |
2890
2890
  | `MCPSessionInterface` | interface | `{ id } plus attach, detach, push, replay` | Represents one MCP transport session — the per-session entity a `createMCPSession` middleware owns (the `MCPSession` entity), carrying the resumable server→client push channel with its bounded replay log folded in. |
2891
2891
  | `MCPSessionState` | interface | `{ session?, initialization? }` | Declares the `context.state` slice a `createMCPSession` middleware sets on a validated / minted request — a consumer's `TState` extends this so the downstream route handler can read `context.state.session` to `push` a server-initiated message onto the session's resumable stream. |
2892
2892
  | `MCPSessionEvent` | interface | `{ id, message, timestamp }` | Represents one entry of an `MCPSessionInterface`'s folded replay log — a single pushed `JSONRPCMessage` tagged with the monotone event `id` the session assigned and the `timestamp` it was appended at (for the lazy-TTL replay window). |
@@ -3295,7 +3295,7 @@ annotations, retains the `AbortController` whose abort is WebMCP's own unregistr
3295
3295
  subscribes to the manager's own `emitter` so a later `add`, `remove`, or `clear` reaches the
3296
3296
  document registry without a second call; `adopt` reads `getTools` and wraps each
3297
3297
  `RegisteredTool` as a tool, excluding `annotations.debugging: true` unless you pass
3298
- `adopt({ debugging: true })`. Each tool's `execute` runs `executeTool` with the caller's
3298
+ `adopt({ debug: true })`. Each tool's `execute` runs `executeTool` with the caller's
3299
3299
  `ToolContext.signal`; `destroy` aborts the registrations this handle made, releases that
3300
3300
  subscription, and leaves a name it never registered alone. WebMCP keys a registration by tool
3301
3301
  name per document, so a release takes whatever now stands under that name. See
@@ -3340,7 +3340,6 @@ const tools = await http.tools()
3340
3340
  | `createMessagePortTransport` | function | Creates the browser-face `MessagePort` transport — a `MCPTransportInterface` over a native `MessagePort`, the symmetric carrier that works as either a server or a client transport depending on which binder (`bindServer` or `bindClient`) it is handed to. |
3341
3341
  | `createScopeServer` | function | Creates an `MCPServer` hosted inside a worker scope and wires that scope's message events to it — the browser face's bootstrap, and the twin of the Node face's `createStdioServer`. |
3342
3342
  | `createScopeTransport` | function | Adapts a hostable `ScopeInterface` (`self` in a dedicated Web Worker, or any structurally matching double) into a `ScopeTransportInterface` — the implicit, portless message channel `createScopeServer` binds for the dedicated-worker shape. |
3343
- | `createScopeMessageListener` | function | Builds `createScopeServer`'s `message`-event listener — the unified dispatcher that routes every inbound event on a hostable scope, portless or port-bearing, to the right binding. |
3344
3343
  | `createPageServer` | function | Creates an `MCPServer` hosted inside the calling page and hands back the client bound to it — the page twin of `createScopeServer`, and the in-page MCP pair as one call. |
3345
3344
  | `createModelContext` | function | Creates the bridge between a tool registry and a document's WebMCP registry, or reports that the document exposes none. |
3346
3345
 
@@ -3421,14 +3420,110 @@ An extended interface's name comes before `plus`, with the members it adds after
3421
3420
  | `ModelContextEventMap` | type | `{ change: readonly [], activate: readonly [name: string], abort: readonly [name: string] }` | Reports changes and execution events from a WebMCP registry. |
3422
3421
  | `ModelContextOptions` | interface | `{ document?, on?, error? }` | Options for `createModelContext` — the document to bridge and the emitter's initial wiring. |
3423
3422
  | `ModelContextPublishOptions` | interface | `{ origins? }` | Options for `ModelContextInterface.publish` — the origins each registration is exposed to. |
3424
- | `ModelContextAdoptOptions` | interface | `{ origins?, debugging? }` | Options for `ModelContextInterface.adopt` — the origins and debugging tools to include. |
3423
+ | `ModelContextAdoptOptions` | interface | `{ origins?, debug? }` | Options for `ModelContextInterface.adopt` — the origins and debugging tools to include. |
3425
3424
  | `ModelContextInterface` | interface | `{ emitter } plus publish, adopt, destroy` | Represents the bridge between a `ToolManagerInterface` and a document's WebMCP registry — what `createModelContext` returns. |
3426
3425
 
3427
3426
  _This face declares no `HTTPClientTransportOptions`. It is host-independent and ships from
3428
3427
  `@orkestrel/mcp`; see [Core § Types](#types)._
3429
3428
 
3429
+ ### Binding and traversal entities
3430
+
3431
+ The core face exports the entities that own a duplex binding and a subscription source.
3432
+ `MCPServer` uses `MCPSubscriptionSource` for its producer queue and registry listeners.
3433
+
3434
+ | API | Kind | Summary |
3435
+ | ----------------------- | -------- | -------------------------------------------------------------------------------------- |
3436
+ | `MCPServerBinding` | class | Owns the request lifetimes installed on a server's duplex carrier. |
3437
+ | `MCPSubscriptionSource` | class | Owns one subscription producer, its registry listeners, and its unread registry frame. |
3438
+ | `walkHeaderAnnotations` | function | Yields annotation values while preserving the schema's depth-first traversal order. |
3439
+
3440
+ | Type | Kind | Shape | Summary |
3441
+ | --------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
3442
+ | `MCPBindingInterface` | interface | `{} plus stop` | Owns one installed transport binding until it is detached. |
3443
+ | `MCPJSONFrame` | type | `{ readonly operation: 'value'; readonly value: unknown; readonly depth: number } \| { readonly operation: 'string'; readonly value: string; readonly output?: string[] } \| { readonly operation: 'text'; readonly text: string } \| { readonly operation: 'close'; readonly value: object; readonly text: string } \| { readonly operation: 'record'; readonly value: object; readonly names: readonly string[]; readonly encoded: string[]; readonly index: number; readonly depth: number }` | Describes a pending operation in the bounded canonical JSON traversal. |
3444
+ | `MCPJSONStep` | interface | `{ bytes, keys, text? }` | Records a traversal step's cumulative budget and its optional emitted JSON token. |
3445
+ | `MCPJSONProperty` | interface | `{ text, value }` | Pairs a serialized property name with its once-read own data value. |
3446
+
3447
+ ```ts
3448
+ import { MCPServerBinding, walkHeaderAnnotations } from '@orkestrel/mcp'
3449
+
3450
+ const binding = new MCPServerBinding(server, transport)
3451
+ binding.stop()
3452
+ Array.from(walkHeaderAnnotations({ properties: { region: { 'x-mcp-header': 'Region' } } }))
3453
+ // ['Region']
3454
+ ```
3455
+
3456
+ The browser face exports the scope entities used by `createScopeServer` and
3457
+ `createScopeTransport`.
3458
+
3459
+ | API | Kind | Summary |
3460
+ | ---------------- | ----- | ------------------------------------------------------------------------- |
3461
+ | `ScopeServer` | class | Owns a scope's implicit binding and every accepted client-port binding. |
3462
+ | `ScopeTransport` | class | Adapts a scope's implicit channel to replaceable MCP transport callbacks. |
3463
+
3464
+ The server face exports the session table and serialized carrier adapter.
3465
+ `createMCPSession` creates an isolated `MCPSessionStore` unless `options.store` supplies
3466
+ a table. A supplied table owns its session identities and idle-cutoff removal.
3467
+
3468
+ | API | Kind | Summary |
3469
+ | ------------------------- | -------- | --------------------------------------------------------------------------------- |
3470
+ | `MCPSessionStore` | class | Owns an in-memory table of negotiated legacy MCP sessions. |
3471
+ | `DuplexServerTransport` | class | Bridges a message carrier to the server's serialized transport protocol. |
3472
+ | `readRequestText` | function | Reads a request body, returning absence when the body cannot be read. |
3473
+ | `resolveHeaderParameters` | function | Resolves a named tool's header declarations through the bounded listing protocol. |
3474
+
3475
+ | Type | Kind | Shape | Summary |
3476
+ | -------------------------- | --------- | --------------------------------- | --------------------------------------------------------------------------------- |
3477
+ | `MCPSessionStoreInterface` | interface | `{} plus get, set, delete, sweep` | Stores negotiated legacy sessions and removes entries at an explicit idle cutoff. |
3478
+
3479
+ ```ts
3480
+ import { readRequestText, resolveHeaderParameters } from '@orkestrel/mcp/server'
3481
+
3482
+ const body = await readRequestText(
3483
+ new Request('https://example.test/mcp', {
3484
+ method: 'POST',
3485
+ body: '{}',
3486
+ }),
3487
+ )
3488
+ const parameters = await resolveHeaderParameters(server, invocation, 'search')
3489
+ ```
3490
+
3491
+ `isMCPError` and `isMCPToolError` require the class's own self-valued symbol brand and
3492
+ declared members on an `Error` subclass instance. They accept subclasses and errors from
3493
+ another installed copy, ignore `name`, and refuse unbranded look-alikes and transparent
3494
+ proxies. `MCPError.context` admits any value, including `undefined`.
3495
+
3430
3496
  ## Methods
3431
3497
 
3498
+ #### `MCPBindingInterface`
3499
+
3500
+ | Method | Returns | Summary |
3501
+ | ------ | ------- | --------------------------------------------------- |
3502
+ | `stop` | `void` | Detaches the binding without closing its transport. |
3503
+
3504
+ ```ts
3505
+ binding.stop()
3506
+ ```
3507
+
3508
+ #### `MCPSessionStoreInterface`
3509
+
3510
+ | Method | Returns | Summary |
3511
+ | -------- | ------------------------------ | ----------------------------------------------------------------- |
3512
+ | `get` | `MCPSessionEntry \| undefined` | Reads the session associated with an opaque protocol identifier. |
3513
+ | `set` | `void` | Publishes an entry under the identifier its session owns. |
3514
+ | `delete` | `boolean` | Removes a session and reports whether its identifier was present. |
3515
+ | `sweep` | `void` | Removes every entry last touched at or before the idle cutoff. |
3516
+
3517
+ ```ts
3518
+ import { MCPSessionStore } from '@orkestrel/mcp/server'
3519
+
3520
+ const store = new MCPSessionStore()
3521
+ store.set(entry)
3522
+ store.get(entry.session.id)
3523
+ store.sweep(Date.now() - 60_000)
3524
+ store.delete(entry.session.id)
3525
+ ```
3526
+
3432
3527
  The public methods of the layer's behavioral interfaces — every call-signature
3433
3528
  member listed (their `readonly` data members stay Surface rows). Each
3434
3529
  implementing class exposes exactly its interface's methods: `MCPServer` ↔
@@ -4095,9 +4190,9 @@ is the same shape, and its `deliver` is what the peer calls to hand a frame acro
4095
4190
  #### `ScopeServerInterface`
4096
4191
 
4097
4192
  The worker-scope handle `createScopeServer` returns, and the browser twin of
4098
- `StdioServerInterface`. No class implements it: the factory owns the `MCPServer`, the
4099
- implicit scope binding, and the per-port bindings behind it, and publishes the one door that
4100
- ends them. It arms at construction rather than on a `start`, because an event delivered
4193
+ `StdioServerInterface`. `ScopeServer` owns the `MCPServer`, the implicit scope binding,
4194
+ and the per-port bindings, and exposes `stop` to end them. It arms at construction
4195
+ rather than on a `start`, because an event delivered
4101
4196
  between the call and an explicit arm would reach nothing.
4102
4197
 
4103
4198
  | Method | Returns | Summary |
@@ -4232,7 +4327,7 @@ value that was thrown no longer exists to forward and a foreign caller receives
4232
4327
  `Error` whose `message` is that text.
4233
4328
 
4234
4329
  The `adopt` method excludes a tool carrying `annotations.debugging: true` unless you pass
4235
- `adopt({ debugging: true })`. A false or omitted hint leaves the tool included either way;
4330
+ `adopt({ debug: true })`. A false or omitted hint leaves the tool included either way;
4236
4331
  the `origins` option continues to filter which registrations the registry returns.
4237
4332
 
4238
4333
  **An adopted tool validates nothing.** It advertises the foreign `inputSchema` as its
@@ -4654,7 +4749,7 @@ import {
4654
4749
 
4655
4750
  const request = new Request('http://localhost/mcp', { headers: { accept: 'text/event-stream' } })
4656
4751
  acceptsEventStream(request) // true
4657
- createMCPPostHandler(mcp, { streaming: true }) // the same stateless POST handler createMCPRoutes mounts
4752
+ createMCPPostHandler(mcp, { stream: true }) // the same stateless POST handler createMCPRoutes mounts
4658
4753
  readSessionHeader(request) // undefined — no mcp-session-id header
4659
4754
  readLastEventId(request) // undefined — no Last-Event-ID header
4660
4755
  rejectUnknownSession() // a 404 JSON-RPC error Response
@@ -5013,7 +5108,7 @@ the implemented rows live.
5013
5108
  | `toolchange` event | `ModelContextEventMap.change` | implement — the registry names no changed tool, so ours is a bare signal and a listener re-reads `adopt` | `G5c` § 2 |
5014
5109
  | `toolactivated` event | `ModelContextEventMap.activate` | implement — republishes the tool name when execution begins | 2026-09-29 draft, `index.bs` |
5015
5110
  | `toolcancel` event | `ModelContextEventMap.abort` | implement — republishes the tool name; `abort` is the fixed lifecycle vocabulary for cancellation | 2026-09-29 draft, `index.bs` |
5016
- | `ToolAnnotations.debugging` | `adopt({ debugging })` | implement — excluded by default; the `debugging` option includes the tool | 2026-09-29 draft, `index.bs` |
5111
+ | `ToolAnnotations.debugging` | `adopt({ debug })` | implement — excluded by default; the `debug` option includes the tool | 2026-09-29 draft, `index.bs` |
5017
5112
  | Registry change events on our own tool registry | `ToolManagerEventMap` (`add`, `remove`, `clear`), followed by `publish` | implement — `@orkestrel/tool` publishes registry events, so `publish` subscribes to the manager's `emitter` and the document registry tracks the tool registry with no second call | `G5c` § 2 |
5018
5113
  | `inputSchema` (JSON Schema) | `ToolDefinition.parameters`, derived from `ToolOptions.contract` | implement, exceeds in the publish direction — a published tool carries the contract that validates arguments before execution; an adopted tool carries the foreign `inputSchema` as `parameters` and validates nothing | `G5c` § 1; `G5` § 8 |
5019
5114
  | `ModelContextTool.title` | `ToolDefinition.title` | implement | `G5c` § 1 |
@@ -5064,7 +5159,7 @@ this package publishes no OAuth client.
5064
5159
  The comparison starts no server and drives no client. It reads the stable Tasks
5065
5160
  extension's published schema from the vendored mirror
5066
5161
  `tests/mirrors/ext-tasks-2026-07-28-schema.json`, and the `TASK_SCHEMA_DIGEST` constant in
5067
- `tests/setupConformance.ts` pins that file's raw bytes: a changed byte throws at module
5162
+ `tests/setupServer.ts` pins that file's raw bytes: a changed byte throws at module
5068
5163
  load, before a comparison row runs, so no row reads a mirror this package has not pinned.
5069
5164
  Each comparison row projects one schema coordinate — a task variant, a result composition,
5070
5165
  a notification shape, a subscription fragment — and compares it with the shape this
@@ -5072,7 +5167,7 @@ package ships, so a contract that drifts from the authority reddens the row nami
5072
5167
  coordinate.
5073
5168
 
5074
5169
  They share one project — `tests/conformance.test.ts` over the fixture in
5075
- `tests/setupConformance.ts` — and `npm test` gates it. It spawns a foreign process and
5170
+ `tests/setupServer.ts` — and `npm test` gates it. It spawns a foreign process and
5076
5171
  drives it over a real socket, but the runner is a pinned development dependency resolved
5077
5172
  from `node_modules` and the socket is loopback, so the run is offline and hermetic. The
5078
5173
  runner's baseline is recorded scenario by scenario rather than as one total, so a scenario
@@ -5372,12 +5467,12 @@ chromestatus record, read 2026-09-15 and last updated 2026-08-12, reports that f
5372
5467
  `Proposed` with `"flag": false` and `"origintrial": false` — no browser ships it, behind a flag or in an origin trial. The real
5373
5468
  Chromium the browser suite drives therefore exposes no `document.modelContext`, which
5374
5469
  `tests/src/browser/factories.test.ts` records as its own reading of the page rather than
5375
- assuming, and every bridge scenario runs against `tests/fixtures/modelContext.ts`: an in-memory
5470
+ assuming, and every bridge scenario runs against `tests/setupBrowser.ts`: an in-memory
5376
5471
  implementation of that WebIDL, member for member and nothing beyond it. **What that proves:**
5377
5472
  the translation each way — the projected annotations, the exposure and origin options, the
5378
5473
  signal carried into a published tool and out to an adopted one, the `toolchange` republication,
5379
5474
  `toolactivated` republished as `activate`, `toolcancel` republished as `abort`, the default
5380
- exclusion of `annotations.debugging: true` tools unless `adopt({ debugging: true })` requests
5475
+ exclusion of `annotations.debugging: true` tools unless `adopt({ debug: true })` requests
5381
5476
  them, and the registration ownership and event listeners `destroy` releases. **What it does not prove:** that a user
5382
5477
  agent's own registry accepts these registrations, or that an agent driving one reaches this
5383
5478
  page's tools. **What it costs:** nothing a consumer can reach today, because
@@ -5635,8 +5730,8 @@ the exact statement:
5635
5730
  exports add no behavioral interface with methods (the factories,
5636
5731
  `acceptsEventStream` / `readSessionHeader` /
5637
5732
  `readLastEventId` / `rejectUnknownSession` / `readEventStream` /
5638
- `decodeEvent` / `upgradeRequestPath` / `extractLines` / `dispatchLines` /
5639
- `createScopeMessageListener` are functions; the options interfaces / event
5733
+ `decodeEvent` / `upgradeRequestPath` / `extractLines` / `dispatchLines`
5734
+ are functions; the options interfaces / event
5640
5735
  maps / `MCPSessionEvent` / `LineExtraction` are bags;
5641
5736
  `StdioClientTransportInterface` extends `MCPMessageTransportInterface` with
5642
5737
  the readonly `evidence` data member and declares no call signature of its
@@ -5687,7 +5782,7 @@ the exact statement:
5687
5782
  serialized origin requires an exact consumer-supplied `origin.origins` entry or
5688
5783
  receives **403**. The predicate reads only `Origin`, never the request URL, `Host`,
5689
5784
  or another request header. `origin.enabled: false` explicitly delegates validation
5690
- to an upstream layer. When `streaming` is enabled (default `true`) and the client
5785
+ to an upstream layer. When `stream` is enabled (default `true`) and the client
5691
5786
  `Accept`s `text/event-stream` (`acceptsEventStream`), the 200 reply is one
5692
5787
  SSE `data:` event over `@orkestrel/server`'s `createStream` seam, then the
5693
5788
  stream ends, carrying `X-Accel-Buffering: no`; else a plain JSON body. A
@@ -6144,8 +6239,8 @@ the exact statement:
6144
6239
  when omitted), `bindServer`s it eagerly over a `createScopeTransport(scope)`
6145
6240
  (the implicit, portless channel — bound once, for the whole lifetime of
6146
6241
  the returned handle, so a dedicated worker's very first portless message
6147
- needs no first-use setup), and registers one `scope.addEventListener(
6148
- 'message', …)` listener built by `createScopeMessageListener`. That one
6242
+ needs no first-use setup), and registers one `message` listener the
6243
+ `ScopeServer` instance owns. That one
6149
6244
  listener handles every shape uniformly, per event, with no upfront
6150
6245
  detection flag: `event.ports.length > 0` spawns a fresh
6151
6246
  `createMessagePortTransport` + `bindServer` for that port (tracked for
@@ -90,14 +90,14 @@ A `Shape` cell holds an interface's data members as bare names in braces, `?` ma
90
90
  | `ForwardedOptions` | type | `{ proxies } \| { trusted }` | Configures `createForwarded` — the trusted-proxy client-IP resolver. |
91
91
  | `ETagOptions` | interface | `{ weak? }` | Configures `createETag` — dynamic response ETag + conditional GET. |
92
92
  | `BearerOptions` | interface | `{ secret, header?, scheme? }` | Configures `createBearer` — bearer-token authentication. |
93
- | `LimiterOptions` | interface | `{ max, window, capacity?, key?, message?, clock?, policy?, evict? }` | Configures `createLimiter` — fixed-window rate limiting. |
93
+ | `LimiterOptions` | interface | `{ store?, max, window, capacity?, key?, message?, clock?, policy?, evict? }` | Configures `createLimiter` — fixed-window rate limiting. |
94
94
  | `BearerState` | interface | `{ token? }` | Describes the bearer-authentication state slice `createBearer` stashes on `context.state` once a token verifies. |
95
95
  | `IdentifierState` | interface | `{ identifier? }` | Describes the request-identifier state slice `createSecurity` stashes when its `identifier` option is enabled. |
96
96
  | `Client` | interface | `{ ip? }` | Describes the resolved client connection facts `createForwarded` stashes. |
97
97
  | `ClientState` | interface | `{ client? }` | Describes the client-facts state slice `createForwarded` stashes. |
98
98
  | `ConnectionState` | interface | `{ connection? }` | Describes the connection-facts state slice `createLimiter`'s default key derivation falls back to when neither `BearerState` nor `ClientState` is present — the raw socket peer surfaced on `context.state` by the server's `state` option. |
99
99
  | `SessionInterface` | interface | `{ id, state } plus set, delete, clear` | Represents a server-managed session's public surface — an id, its live state, and the mutators that write it. |
100
- | `SessionControlInterface` | interface | `{} plus regenerate, destroy` | Describes the mid-handler control handle `createSession` stashes alongside the session itself — the OWASP anti-fixation / logout primitives. |
100
+ | `SessionControlInterface` | interface | `{ destroyed, successor } plus regenerate, destroy` | Describes the mid-handler control handle `createSession` stashes alongside the session itself — the OWASP anti-fixation / logout primitives. |
101
101
  | `SessionState` | interface | `{ session?, control? }` | Describes the session state slice `createSession` stashes. |
102
102
  | `BodyState` | interface | `{ body? }` | Describes the body state slice `createBody` stashes. |
103
103
  | `SessionStoreInterface` | interface | `{} plus get, set, delete` | Describes the pluggable session persistence seam `createSession`'s `store` option implements — a point-access store keyed by session id. |
@@ -119,7 +119,7 @@ A `Shape` cell holds an interface's data members as bare names in braces, `?` ma
119
119
  | `MultipartState` | interface | `{ multipart? }` | Describes the multipart state slice `createMultipart` stashes. |
120
120
  | `Asset` | interface | `{ body, encoding? }` | Describes one in-memory asset representation returned by an `AssetSourceInterface`. |
121
121
  | `AssetSourceInterface` | interface | `{} plus read` | Reads in-memory assets by decoded, browser-build-relative path. |
122
- | `AssetOptions` | interface | `{ source }` | Configures `createAssets` — in-memory identity/Brotli asset serving. |
122
+ | `AssetOptions` | interface | `{ source, store? }` | Configures `createAssets` — in-memory identity/Brotli asset serving. |
123
123
  | `StaticOptions` | interface | `{ root, prefix?, index?, dotfiles?, cache?, etag?, fallback? }` | Configures `createStatic` — node `fs`-backed static file serving. |
124
124
  | `MultipartLimitsInput` | interface | `{ file?, field?, total? }` | Describes the caller's partial `MultipartLimits` — `createMultipart`'s `limits` option, with every member optional. |
125
125
  | `MultipartLimits` | interface | `{ file, field, total }` | Describes the per-category size/count caps `createMultipart` enforces mid-stream — the effective limits, every documented default already applied. |
@@ -131,6 +131,39 @@ A `Shape` cell holds an interface's data members as bare names in braces, `?` ma
131
131
  | `PartHeaders` | interface | `{ name, filename, mime }` | Describes one multipart part's parsed header block — `parsePartHeaders`'s return shape. |
132
132
  | `ByteRange` | interface | `{ start, end }` | Describes one inclusive byte range over a file — `streamFile`'s optional `range` argument and the shape `createStatic` builds for a satisfiable `Range` request. |
133
133
 
134
+ ### Store and response types
135
+
136
+ | Type | Kind | Shape | Summary |
137
+ | --------------------------- | --------- | --------------------------------- | ------------------------------------------------------------------------------ |
138
+ | `StaticFile` | interface | `{ path, handle, info }` | Describes an opened static file and the facts read from its handle. |
139
+ | `StaticResolution` | interface | `{ path, contained }` | Describes a canonical static path and whether it lies inside the serving root. |
140
+ | `StaticPlan` | interface | `{ status, headers, range }` | Describes response headers and the optional byte interval of a static file. |
141
+ | `LimiterLimits` | interface | `{ max, window }` | Describes the budget and duration used when a limiter window starts. |
142
+ | `LimiterResult` | interface | `{ admitted, expiry }` | Reports an atomic admission decision and its window expiry instant. |
143
+ | `LimiterEntry` | interface | `{ budget, expiry }` | Holds the budget and expiry instant of an in-memory limiter entry. |
144
+ | `LimiterStoreInterface` | interface | `{} plus consume` | Provides atomic per-key fixed-window admission. |
145
+ | `MemoryLimiterStoreOptions` | interface | `{ capacity?, evict? }` | Configures the in-memory limiter's capacity and eviction observation. |
146
+ | `AssetRecord` | interface | `{ key, identity, brotli, etag }` | Holds copied asset representations and their shared identity validator. |
147
+ | `AssetStoreInterface` | interface | `{} plus get, set, delete` | Provides asynchronous point access to cached asset representations. |
148
+
149
+ ### Request control and stores
150
+
151
+ | API | Kind | Summary |
152
+ | -------------------------- | -------- | ----------------------------------------------------------------------------------- |
153
+ | `SessionControl` | class | Records one request's session regeneration or destruction intent. |
154
+ | `MemoryLimiterStore` | class | Stores fixed-window budgets with atomic admission and bounded LRU retention. |
155
+ | `MemoryAssetStore` | class | Stores asset representations by key for the lifetime of the store. |
156
+ | `createMemoryLimiterStore` | function | Creates a bounded in-memory atomic limiter store. |
157
+ | `createMemoryAssetStore` | function | Creates an in-memory asset representation store. |
158
+ | `extractBearerToken` | function | Extracts a token after a case-insensitive scheme and one space. |
159
+ | `extractFieldToken` | function | Extracts a string field from a parsed body record. |
160
+ | `resolveStaticFile` | function | Resolves a contained static path, including a directory's index. |
161
+ | `openStaticFile` | function | Opens a static file and reads its handle's metadata. |
162
+ | `planStaticResponse` | function | Plans conditional, HEAD, and byte-range responses from opened-file metadata. |
163
+ | `resolveAssetKey` | function | Resolves a decoded relative asset key while refusing hidden or traversing segments. |
164
+ | `readAssetRecord` | function | Copies an asset, derives its identity bytes, and computes their validator. |
165
+ | `buildAssetResponse` | function | Builds a conditional asset response with identity or Brotli negotiation. |
166
+
134
167
  ### Constants
135
168
 
136
169
  A `Shape` cell holds the constant's declared type.
@@ -190,28 +223,28 @@ A `Shape` cell holds the constant's declared type.
190
223
 
191
224
  ### Helpers — core
192
225
 
193
- | API | Kind | Summary |
194
- | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
195
- | `resolveKey` | function | Derives `createLimiter`'s default rate-limit bucket key from a request's resolved identity facts. |
196
- | `resolveOptInHeader` | function | Resolves an opt-in, value-bearing security header — `string \| boolean` (off by default, `true` uses the secure default), the shape `createSecurity`'s `coep`/`hsts` options use, distinct from the plain value-or-`false` shape `resolveSecurityHeader` (the peer substrate) handles. |
197
- | `buildRetryAfter` | function | Builds the `Retry-After` header value — whole seconds until a window reset, floored at a minimum of `1`. |
198
- | `buildRateLimitField` | function | Builds the draft `RateLimit` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
199
- | `buildRateLimitPolicyField` | function | Builds the draft `RateLimit-Policy` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
200
- | `matchesTrustedEntry` | function | Checks whether a candidate address is a bare (non-CIDR) trusted-hop match — an exact string match, or a simple prefix-CIDR match for IPv4 (`/8`–`/32`). An IPv6 entry matches by exact string only — there is no IPv6 CIDR support. |
201
- | `resolveForwardedFor` | function | Walks `X-Forwarded-For` right-to-left and resolves the first untrusted hop address — `createForwarded`'s core algorithm. |
202
- | `detectEncodings` | function | Feature-detects which of `candidates` the runtime's `CompressionStream` actually supports — `createCompression`'s construction-time intersection. |
203
- | `compressBytes` | function | Compresses bytes with the host-independent `CompressionStream` primitive. |
204
- | `isBufferingIneligible` | function | Checks whether a response must skip the compression and ETag buffering pipeline — the shared cheap-skip predicate both batteries apply before ever touching `response.arrayBuffer()`, true for a `HEAD` request, a `204`/`304` or otherwise bodyless response, an `event-stream` response, and a response already carrying the header the caller is about to set. |
205
- | `isCompressionNegotiated` | function | Checks whether a negotiated `Accept-Encoding` outcome is worth acting on — `createCompression`'s negotiation-eligibility half of the skip list. |
206
- | `rebuildResponse` | function | Rebuilds a `Response` around a replacement body while preserving its status/statusText — the buffered-response reconstruction shared by the compression and ETag batteries after they have consumed `response.arrayBuffer()`. |
207
- | `compressResponse` | function | Runs the shared negotiate → skip → threshold → compress → header-set skeleton both faces' `createCompression` batteries compose — response-body compression over a caller-supplied set of feature-detected codings. |
208
- | `transferSessionState` | function | Copies every entry of one session's `state` into another — the regenerate state-carry `createSession`'s `control.regenerate()` applies. |
209
- | `sessionExpired` | function | Checks whether a session has aged past its idle timeout or absolute lifetime as of `now` — the pure expiry predicate `MemorySessionStore` delegates to. |
210
- | `snapshotSession` | function | Snapshots a session's `state` into a plain, serializable record — the projection a durable store's `set` writes to disk. |
211
- | `validateSessionLimits` | function | Validates a store's idle and absolute-lifetime thresholds, throwing when either is present and malformed — the shared construction gate `MemorySessionStore` and `DatabaseSessionStore` both apply, so one malformed `ttl` is refused identically by whichever store receives it. |
212
- | `isPreflight` | function | Determines whether a request is a CORS preflight — an `OPTIONS` request carrying an `Access-Control-Request-Method` header. |
213
- | `buildClient` | function | Builds the `Client` slice `createForwarded` stashes, from the resolved client IP — a leaf shaping helper. |
214
- | `equalsConstantTime` | function | Compares two strings in constant time — `createCSRF`'s double-submit token comparison, avoiding a timing oracle on the submitted-vs-cookie match. |
226
+ | API | Kind | Summary |
227
+ | ----------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
228
+ | `resolveKey` | function | Derives `createLimiter`'s default rate-limit bucket key from a request's resolved identity facts. |
229
+ | `resolveOptInHeader` | function | Resolves an opt-in, value-bearing security header — `string \| boolean` (off by default, `true` uses the secure default), the shape `createSecurity`'s `coep`/`hsts` options use, distinct from the plain value-or-`false` shape `resolveSecurityHeader` (the peer substrate) handles. |
230
+ | `buildRetryAfter` | function | Builds the `Retry-After` header value — whole seconds until a window reset, floored at a minimum of `1`. |
231
+ | `buildRateLimitField` | function | Builds the draft `RateLimit` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
232
+ | `buildRateLimitPolicyField` | function | Builds the draft `RateLimit-Policy` structured header field — emitted only when `createLimiter`'s `policy` option is `true`. |
233
+ | `matchesTrustedEntry` | function | Checks whether a candidate address is a bare (non-CIDR) trusted-hop match — an exact string match, or a simple prefix-CIDR match for IPv4 (`/8`–`/32`). An IPv6 entry matches by exact string only — there is no IPv6 CIDR support. |
234
+ | `resolveForwardedFor` | function | Walks `X-Forwarded-For` right-to-left and resolves the first untrusted hop address — `createForwarded`'s core algorithm. |
235
+ | `detectEncodings` | function | Feature-detects which of `candidates` the runtime's `CompressionStream` actually supports — `createCompression`'s construction-time intersection. |
236
+ | `compressBytes` | function | Compresses bytes with the host-independent `CompressionStream` primitive. |
237
+ | `matchesUnbufferableResponse` | function | Checks whether a response must skip the compression and ETag buffering pipeline — the shared cheap-skip predicate both batteries apply before ever touching `response.arrayBuffer()`, true for a `HEAD` request, a `204`/`304` or otherwise bodyless response, an `event-stream` response, and a response already carrying the header the caller is about to set. |
238
+ | `isCompressionNegotiated` | function | Checks whether a negotiated `Accept-Encoding` outcome is worth acting on — `createCompression`'s negotiation-eligibility half of the skip list. |
239
+ | `rebuildResponse` | function | Rebuilds a `Response` around a replacement body while preserving its status/statusText — the buffered-response reconstruction shared by the compression and ETag batteries after they have consumed `response.arrayBuffer()`. |
240
+ | `compressResponse` | function | Runs the shared negotiate → skip → threshold → compress → header-set skeleton both faces' `createCompression` batteries compose — response-body compression over a caller-supplied set of feature-detected codings. |
241
+ | `transferSessionState` | function | Copies every entry of one session's `state` into another — the regenerate state-carry `createSession`'s `control.regenerate()` applies. |
242
+ | `sessionExpired` | function | Checks whether a session has aged past its idle timeout or absolute lifetime as of `now` — the pure expiry predicate `MemorySessionStore` delegates to. |
243
+ | `snapshotSession` | function | Snapshots a session's `state` into a plain, serializable record — the projection a durable store's `set` writes to disk. |
244
+ | `validateSessionLimits` | function | Validates a store's idle and absolute-lifetime thresholds, throwing when either is present and malformed — the shared construction gate `MemorySessionStore` and `DatabaseSessionStore` both apply, so one malformed `ttl` is refused identically by whichever store receives it. |
245
+ | `isPreflight` | function | Determines whether a request is a CORS preflight — an `OPTIONS` request carrying an `Access-Control-Request-Method` header. |
246
+ | `buildClient` | function | Builds the `Client` slice `createForwarded` stashes, from the resolved client IP — a leaf shaping helper. |
247
+ | `equalsConstantTime` | function | Compares two strings in constant time — `createCSRF`'s double-submit token comparison, avoiding a timing oracle on the submitted-vs-cookie match. |
215
248
 
216
249
  ### Validators — core
217
250
 
@@ -297,6 +330,10 @@ The public methods of `AssetSourceInterface`, `SessionInterface`,
297
330
  compose (their `readonly` data members, where any exist, stay Surface rows
298
331
  in the preceding section).
299
332
 
333
+ The multipart guard requires an Error subclass with its own identity brand,
334
+ a declared code, a numeric status, and a context of the declared type. It accepts
335
+ subclasses across package copies and refuses transparent proxies and plain objects.
336
+
300
337
  #### `AssetSourceInterface`
301
338
 
302
339
  The in-memory lookup seam. `createAssets` validates a request key before it
@@ -357,6 +394,20 @@ returning onion makes "before send" automatic).
357
394
  | `write` | `void \| Promise<void>` | Writes a freshly minted or regenerated session id onto the response, together with the request's encrypted-transport fact. |
358
395
  | `clear` | `void` | Clears the transport's credential on `destroy()`. |
359
396
 
397
+ #### `LimiterStoreInterface`
398
+
399
+ | Method | Returns | Summary |
400
+ | --------- | ------------------------ | ------------------------------------------------------------------------- |
401
+ | `consume` | `Promise<LimiterResult>` | Checks and consumes a budget without interleaving its admission decision. |
402
+
403
+ #### `AssetStoreInterface`
404
+
405
+ | Method | Returns | Summary |
406
+ | -------- | ----------------------------------- | ----------------------------------------------- |
407
+ | `get` | `Promise<AssetRecord \| undefined>` | Reads a cached representation by key. |
408
+ | `set` | `Promise<void>` | Stores a representation under its own key. |
409
+ | `delete` | `Promise<void>` | Removes a cached key; an absent key is a no-op. |
410
+
360
411
  ## Contract
361
412
 
362
413
  These invariants hold across `src/core` / `src/server` ↔ `middleware.md`.
@@ -484,7 +535,8 @@ prevents:
484
535
  22. **Assets.** `createAssets` decodes a browser-relative key and refuses
485
536
  malformed escapes, backslashes, empty segments, `.`/`..`, and dotfiles
486
537
  before it calls `AssetSourceInterface.read`. A successful value is copied
487
- and cached. A Brotli value is decompressed once; Brotli and identity share
538
+ and cached through the configured store. Concurrent misses can decompress
539
+ and hash the same key independently. Brotli and identity share
488
540
  the identity body's `computeBodyETag` validator and vary on
489
541
  `Accept-Encoding`. Gzip is not offered. `Range` is ignored and serves the
490
542
  selected complete representation as `200`.
@@ -857,6 +909,122 @@ still served through the fallback, because the operator configured that path.
857
909
  boundary (default; headers only on returned responses) or above it
858
910
  (headers on every response, thrown errors included) — see Contract §7.
859
911
 
912
+ ### Session control intent
913
+
914
+ ```ts
915
+ import { Session, SessionControl } from '@orkestrel/middleware'
916
+
917
+ const control = new SessionControl(new Session('original'))
918
+ control.regenerate()
919
+ console.log(control.successor?.id)
920
+ control.destroy()
921
+ console.log(control.destroyed) // true
922
+ ```
923
+
924
+ ### Atomic limiter store
925
+
926
+ A fresh window takes the current maximum and duration. An active window retains
927
+ its budget. Share a store when middleware instances must enforce the same quota.
928
+
929
+ ```ts
930
+ import { createBudget } from '@orkestrel/budget'
931
+ import { createLimiter, createMemoryLimiterStore, MemoryLimiterStore } from '@orkestrel/middleware'
932
+ import type {
933
+ LimiterEntry,
934
+ LimiterLimits,
935
+ LimiterResult,
936
+ LimiterStoreInterface,
937
+ MemoryLimiterStoreOptions,
938
+ } from '@orkestrel/middleware'
939
+
940
+ const options: MemoryLimiterStoreOptions = { capacity: 100 }
941
+ const store: LimiterStoreInterface = createMemoryLimiterStore(options)
942
+ const limits: LimiterLimits = { max: 3, window: 1000 }
943
+ const result: LimiterResult = await store.consume('client', Date.now(), limits)
944
+ const entry: LimiterEntry = {
945
+ budget: createBudget({ max: limits.max, consumer: Number }),
946
+ expiry: result.expiry,
947
+ }
948
+ const limiter = createLimiter({ ...limits, store })
949
+ console.log(result.admitted, entry.expiry, limiter, new MemoryLimiterStore(options))
950
+ ```
951
+
952
+ ### Asset store and response stages
953
+
954
+ The default store retains successful records until replacement or deletion.
955
+ Concurrent cache misses can read, decompress, and hash the same key independently.
956
+
957
+ ```ts
958
+ import {
959
+ buildAssetResponse,
960
+ createAssets,
961
+ createMemoryAssetStore,
962
+ MemoryAssetStore,
963
+ readAssetRecord,
964
+ resolveAssetKey,
965
+ } from '@orkestrel/middleware/server'
966
+ import type {
967
+ AssetRecord,
968
+ AssetSourceInterface,
969
+ AssetStoreInterface,
970
+ } from '@orkestrel/middleware/server'
971
+
972
+ const source: AssetSourceInterface = {
973
+ read: (path) =>
974
+ path === 'index.html' ? { body: new TextEncoder().encode('<h1>Home</h1>') } : undefined,
975
+ }
976
+ const store: AssetStoreInterface = createMemoryAssetStore()
977
+ const key = resolveAssetKey('/')
978
+ const record: AssetRecord | undefined =
979
+ key === undefined ? undefined : await readAssetRecord(source, key)
980
+ if (record !== undefined) {
981
+ await store.set(record)
982
+ console.log(await store.get(record.key))
983
+ console.log(buildAssetResponse(new Request('https://example.test/'), 'HEAD', record))
984
+ await store.delete(record.key)
985
+ }
986
+ console.log(createAssets({ source, store }), new MemoryAssetStore())
987
+ ```
988
+
989
+ ### Static file response stages
990
+
991
+ The opened handle supplies response metadata. Close it after a bodiless response;
992
+ a streamed response transfers ownership to `streamFile`.
993
+
994
+ ```ts
995
+ import { realpath } from 'node:fs/promises'
996
+ import { join } from 'node:path'
997
+ import { openStaticFile, planStaticResponse, resolveStaticFile } from '@orkestrel/middleware/server'
998
+ import type { StaticFile, StaticPlan } from '@orkestrel/middleware/server'
999
+
1000
+ const root = await realpath('./public')
1001
+ const path = await resolveStaticFile(join(root, 'index.html'), root, 'index.html')
1002
+ const file: StaticFile | undefined = path === undefined ? undefined : await openStaticFile(path)
1003
+ if (file !== undefined) {
1004
+ try {
1005
+ const plan: StaticPlan = planStaticResponse(
1006
+ new Request('https://example.test/', { method: 'HEAD' }),
1007
+ 'HEAD',
1008
+ file.info,
1009
+ file.path,
1010
+ { etag: true },
1011
+ )
1012
+ console.log(new Response(null, { status: plan.status, headers: plan.headers }))
1013
+ } finally {
1014
+ await file.handle.close()
1015
+ }
1016
+ }
1017
+ ```
1018
+
1019
+ ### Token extraction
1020
+
1021
+ ```ts
1022
+ import { extractBearerToken, extractFieldToken } from '@orkestrel/middleware'
1023
+
1024
+ console.log(extractBearerToken('Bearer credential', 'Bearer'))
1025
+ console.log(extractFieldToken({ csrf: 'credential' }, 'csrf'))
1026
+ ```
1027
+
860
1028
  ## Tests
861
1029
 
862
1030
  - [`tests/guides.test.ts`](../tests/guides.test.ts) — the `## Surface` ↔ `src/core` +