agentfootprint 14.6.0-rc.0 → 14.6.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.
Files changed (89) hide show
  1. package/CAPABILITIES.md +4 -4
  2. package/dist/esm/mcp/pool/pool/contracts.d.ts +20 -0
  3. package/dist/esm/mcp/pool/pool/contracts.js +2 -0
  4. package/dist/esm/mcp/pool/pool/contracts.js.map +1 -0
  5. package/dist/esm/mcp/pool/pool/drain.d.ts +48 -0
  6. package/dist/esm/mcp/pool/pool/drain.js +127 -0
  7. package/dist/esm/mcp/pool/pool/drain.js.map +1 -0
  8. package/dist/esm/mcp/pool/pool/endingLifecycle.d.ts +71 -0
  9. package/dist/esm/mcp/pool/pool/endingLifecycle.js +190 -0
  10. package/dist/esm/mcp/pool/pool/endingLifecycle.js.map +1 -0
  11. package/dist/esm/mcp/pool/pool/endings.d.ts +13 -0
  12. package/dist/esm/mcp/pool/pool/endings.js +28 -0
  13. package/dist/esm/mcp/pool/pool/endings.js.map +1 -0
  14. package/dist/esm/mcp/pool/pool/leases.d.ts +56 -0
  15. package/dist/esm/mcp/pool/pool/leases.js +147 -0
  16. package/dist/esm/mcp/pool/pool/leases.js.map +1 -0
  17. package/dist/esm/mcp/pool/pool/listing.d.ts +75 -0
  18. package/dist/esm/mcp/pool/pool/listing.js +204 -0
  19. package/dist/esm/mcp/pool/pool/listing.js.map +1 -0
  20. package/dist/esm/mcp/pool/pool/opening.d.ts +43 -0
  21. package/dist/esm/mcp/pool/pool/opening.js +162 -0
  22. package/dist/esm/mcp/pool/pool/opening.js.map +1 -0
  23. package/dist/esm/mcp/pool/pool/refusals.d.ts +6 -0
  24. package/dist/esm/mcp/pool/pool/refusals.js +16 -0
  25. package/dist/esm/mcp/pool/pool/refusals.js.map +1 -0
  26. package/dist/esm/mcp/pool/pool/requests.d.ts +9 -0
  27. package/dist/esm/mcp/pool/pool/requests.js +30 -0
  28. package/dist/esm/mcp/pool/pool/requests.js.map +1 -0
  29. package/dist/esm/mcp/pool/pool/responses.d.ts +6 -0
  30. package/dist/esm/mcp/pool/pool/responses.js +17 -0
  31. package/dist/esm/mcp/pool/pool/responses.js.map +1 -0
  32. package/dist/esm/mcp/pool/pool/transport.d.ts +35 -0
  33. package/dist/esm/mcp/pool/pool/transport.js +78 -0
  34. package/dist/esm/mcp/pool/pool/transport.js.map +1 -0
  35. package/dist/esm/mcp/pool/pool.d.ts +16 -184
  36. package/dist/esm/mcp/pool/pool.js +125 -893
  37. package/dist/esm/mcp/pool/pool.js.map +1 -1
  38. package/dist/esm/mcp/pool/work.d.ts +1 -1
  39. package/dist/mcp/pool/pool/contracts.js +3 -0
  40. package/dist/mcp/pool/pool/contracts.js.map +1 -0
  41. package/dist/mcp/pool/pool/drain.js +131 -0
  42. package/dist/mcp/pool/pool/drain.js.map +1 -0
  43. package/dist/mcp/pool/pool/endingLifecycle.js +194 -0
  44. package/dist/mcp/pool/pool/endingLifecycle.js.map +1 -0
  45. package/dist/mcp/pool/pool/endings.js +33 -0
  46. package/dist/mcp/pool/pool/endings.js.map +1 -0
  47. package/dist/mcp/pool/pool/leases.js +151 -0
  48. package/dist/mcp/pool/pool/leases.js.map +1 -0
  49. package/dist/mcp/pool/pool/listing.js +208 -0
  50. package/dist/mcp/pool/pool/listing.js.map +1 -0
  51. package/dist/mcp/pool/pool/opening.js +166 -0
  52. package/dist/mcp/pool/pool/opening.js.map +1 -0
  53. package/dist/mcp/pool/pool/refusals.js +22 -0
  54. package/dist/mcp/pool/pool/refusals.js.map +1 -0
  55. package/dist/mcp/pool/pool/requests.js +35 -0
  56. package/dist/mcp/pool/pool/requests.js.map +1 -0
  57. package/dist/mcp/pool/pool/responses.js +21 -0
  58. package/dist/mcp/pool/pool/responses.js.map +1 -0
  59. package/dist/mcp/pool/pool/transport.js +82 -0
  60. package/dist/mcp/pool/pool/transport.js.map +1 -0
  61. package/dist/mcp/pool/pool.js +123 -891
  62. package/dist/mcp/pool/pool.js.map +1 -1
  63. package/dist/types/mcp/pool/pool/contracts.d.ts +21 -0
  64. package/dist/types/mcp/pool/pool/contracts.d.ts.map +1 -0
  65. package/dist/types/mcp/pool/pool/drain.d.ts +49 -0
  66. package/dist/types/mcp/pool/pool/drain.d.ts.map +1 -0
  67. package/dist/types/mcp/pool/pool/endingLifecycle.d.ts +72 -0
  68. package/dist/types/mcp/pool/pool/endingLifecycle.d.ts.map +1 -0
  69. package/dist/types/mcp/pool/pool/endings.d.ts +14 -0
  70. package/dist/types/mcp/pool/pool/endings.d.ts.map +1 -0
  71. package/dist/types/mcp/pool/pool/leases.d.ts +57 -0
  72. package/dist/types/mcp/pool/pool/leases.d.ts.map +1 -0
  73. package/dist/types/mcp/pool/pool/listing.d.ts +76 -0
  74. package/dist/types/mcp/pool/pool/listing.d.ts.map +1 -0
  75. package/dist/types/mcp/pool/pool/opening.d.ts +44 -0
  76. package/dist/types/mcp/pool/pool/opening.d.ts.map +1 -0
  77. package/dist/types/mcp/pool/pool/refusals.d.ts +7 -0
  78. package/dist/types/mcp/pool/pool/refusals.d.ts.map +1 -0
  79. package/dist/types/mcp/pool/pool/requests.d.ts +10 -0
  80. package/dist/types/mcp/pool/pool/requests.d.ts.map +1 -0
  81. package/dist/types/mcp/pool/pool/responses.d.ts +7 -0
  82. package/dist/types/mcp/pool/pool/responses.d.ts.map +1 -0
  83. package/dist/types/mcp/pool/pool/transport.d.ts +36 -0
  84. package/dist/types/mcp/pool/pool/transport.d.ts.map +1 -0
  85. package/dist/types/mcp/pool/pool.d.ts +16 -184
  86. package/dist/types/mcp/pool/pool.d.ts.map +1 -1
  87. package/dist/types/mcp/pool/work.d.ts +1 -1
  88. package/dist/types/mcp/pool/work.d.ts.map +1 -1
  89. package/package.json +2 -2
package/CAPABILITIES.md CHANGED
@@ -40,8 +40,8 @@ not in this table, search `src/index.ts` for the nearest noun before writing cod
40
40
  | calling an MCP server somebody deployed TO AWS Bedrock AgentCore Runtime (`--protocol MCP`) — through `InvokeAgentRuntime` with SigV4, or a bearer token over the documented HTTPS endpoint (the SDK has no bearer scheme); a fresh runtime session per call by default (`'per-call'` carries no session id, so one client can serve every user) or one per client (`'reuse'` keys each client's connection — its `runtimeSessionId` and the server's `Mcp-Session-Id` — by a handle the transport issues); what the MCP client reads of a failure rewritten from fixed sentences and safe ids (status, a plain error type, a JSON-RPC code), never the service's text (which can quote the signed request); a bearer token vended as a machine token only; the runtime's "Session operation in progress" refusal (JSON-RPC -32005 inside an HTTP 200, which MCP clients never retry; or the API's 409 `RetryableConflictException`) retried with bounded backoff by the SAME loop as the 429 retry, one small decision function — and nothing else re-sent: the SDK client's own retry is off, so a 5xx or a dropped connection is never replayed | `agentCoreRuntimeMcpTransport` + `agentCoreRuntimeUrl` + `AGENTCORE_RUNTIME_SESSION_HEADER` (`agentfootprint/providers`) | `src/adapters/mcp/agentcoreRuntime/` | 10.4.0 |
41
41
  | bundling an app that speaks MCP (esbuild, webpack, a Lambda zip without `node_modules`) — the MCP and AWS SDKs load through a lazy `require` a bundler cannot follow, so the caller hands over the modules it imported statically | `mcpClient({ sdk: { Client, StreamableHTTPClientTransport } })` · `agentCoreRuntimeMcpTransport({ sdk })` (SigV4 only; `_sdk` = the older name, both-different refused, `sdk` beside `{ bearer }` refused); a missing or wrong SDK is refused when the client/transport is BUILT, in words naming `sdk`, never at the first tool call. Docs: mcp-client "Bundling (esbuild, webpack)". Fenced by `test/mcp/bundling.test.ts` | `src/mcp/` | 10.5.0 |
42
42
  | serving agents to AG-UI frontends (CopilotKit, the AG-UI Dojo, an `@ag-ui/client` app) from any framework with no glue code — POST a `RunAgentInput`, stream AG-UI events back; the request is untrusted browser input: only the newest user message is conversation (the page's copy is never read), a system/developer message refused, an answer taken only for the pause the server keeps, frontend tools only by the app's name allow-list with its own contract (they run in the page, no server privilege), `state`/`context` only through the app's validators, no identity/credential/redaction from a request; a fresh runner per request, the thread bound to the caller the app authenticates, the conversation and paused runs kept server-side, one turn per thread, door guard, body ceiling, SSE keep-alive | `streamHandler` + `ProtocolAdapter` + `verifiedThreads` (`agentfootprint/hosting`) + `agUi` (`agentfootprint/ag-ui`) | `src/hosting/streamHandler.ts` | 10.4.0 |
43
- | restoring application context from retained source metadata during an admitted turn, without rows, scalar values or a fabricated tool call; fresh preparation admission, current producer and native permission checks, bounded paging, cancellation and a capability revoked before execution | `RunTurn.sourceEvidence.recent` + `SourceEvidencePreparation` / `SourceEvidencePreparationContext` / `SourceEvidenceMetadata` / `SourceEvidenceRecentArgs` / `SourceEvidenceRecentResult`; opt in with `sourceEvidence({ preparation: { admit } })` | `src/core/agent/sourceEvidence/preparation.ts` | unreleased |
44
- | serving AG-UI beside an existing JSON wire through one standing conversation owner, with a bounded per-session agent pool, shared identity/admission/lane/checkpoints, request-local served-event translation, explicit host-authorized terminal/custom delivery and bounded output; per-request frontend tools are explicitly unsupported in pooled mode | `protocolRoute` + `HttpProtocolRoute` + `ProtocolRouteOptions` (`agentfootprint/hosting`), `httpHost({ protocols })`; optional `agUi({ toolArguments, toolResults })` served-value projections | `src/hosting/protocolRoute.ts` | unreleased |
43
+ | restoring application context from retained source metadata during an admitted turn, without rows, scalar values or a fabricated tool call; fresh preparation admission, current producer and native permission checks, bounded paging, cancellation and a capability revoked before execution | `RunTurn.sourceEvidence.recent` + `SourceEvidencePreparation` / `SourceEvidencePreparationContext` / `SourceEvidenceMetadata` / `SourceEvidenceRecentArgs` / `SourceEvidenceRecentResult`; opt in with `sourceEvidence({ preparation: { admit } })` | `src/core/agent/sourceEvidence/preparation.ts` | 14.6.0 |
44
+ | serving AG-UI beside an existing JSON wire through one standing conversation owner, with a bounded per-session agent pool, shared identity/admission/lane/checkpoints, request-local served-event translation, explicit host-authorized terminal/custom delivery and bounded output; per-request frontend tools are explicitly unsupported in pooled mode | `protocolRoute` + `HttpProtocolRoute` + `ProtocolRouteOptions` (`agentfootprint/hosting`), `httpHost({ protocols })`; optional `agUi({ toolArguments, toolResults })` served-value projections | `src/hosting/protocolRoute.ts` | 14.6.0 |
45
45
  | serving an agent behind a GATEWAY that speaks AG-UI in its own request body and its own output envelope (`{"eventType":"…Event","event":{…,"eventSequence":n}}`) — `agUi()` as three replaceable strategies: a reader (the gateway's body → the turn), the translation (AG-UI vocabulary, unchanged) and the framing (the envelope; each frame's number in its own stream handed in by the host, never a shared counter); every untrusted-input rule stays in the core whichever reader ran (shape and ids, no system/developer message, frontend tools by allow-list, state/context by validators, answers only for the kept pause; each value read once) | `agUi({ reader, translation, framing })` + `AgUiRequestReader` / `AgUiTurnRequest` / `AgUiTranslationStrategy` (`agentfootprint/ag-ui`), `SseFraming.frame(event, { sequence })` + `SseFramePosition` (`agentfootprint/observe`) | `src/ag-ui/adapter.ts` | 10.5.0 |
46
46
  | checking forced tool choice per model without changing the existing boolean wire declaration; explicit requests refuse before transport, classifiers keep their strict parse alternative, wrappers preserve and fallback pairs intersect | `LLMProvider.supportsForcedToolChoice` + `forcedToolChoiceFor` + `UnsupportedToolChoiceError` (`agentfootprint/providers`) | `src/provider-contract/forcedToolChoice.ts` | 10.1.0 |
47
47
  | a typed answer constrained by the PROVIDER'S OWN structured output instead of asked for in prose — the schema sent as Anthropic's `output_config.format`, the agent keeping its tools; one function builds the API-compatible wire copy (objects closed, unsupported constraints moved into the description, recursion / external `$ref` / complex enums / open values / open-keyed maps refused at build by node), the parser still judges; explicit-native per-model capability with unknown ids read as the newest generation, refused by name at run start and before transport; a `'refusal'` / `'max_tokens'` stop fails the attempt by name even when it parses; `_findings` allowed on the format when the ledger is armed | `.outputSchema(parser, { strategy: 'native', jsonSchema })` + `LLMProvider.carriesNativeOutputSchema` / `supportsNativeOutputSchema` + `nativeOutputSchemaFor` + `UnsupportedNativeOutputError` (`agentfootprint/providers`) + `answerGuarantee: 'native'` + `OutputAttempt.stopReason` | `src/provider-contract/nativeOutputSchema.ts` | 10.3.0 |
@@ -93,7 +93,7 @@ not in this table, search `src/index.ts` for the nearest noun before writing cod
93
93
  | naming your own branches and nodes — which prefix is reserved, and telling framework plumbing from consumer structure in a trace | `RESERVED_SUBFLOW_PREFIX` + `isReservedSubflowSegment` | `src/lib/conventions.ts` | 9.49.0 |
94
94
  | keeping a large tool result out of the model's context | `artifacts` (bare store, or `{ store, placement: { maxInlineChars }, recordings }` — `placement` omitted ⇒ never placed; `recordings: true` / `{ label }`, default off) + `wants` + `placement` | `src/artifacts/` | 9.21.0 |
95
95
  | opening selected JSON from a host-admitted artifact without loading its whole payload into model context | `artifactDetailTool` + `ArtifactDetailError` — fresh host admission per call, small values, paginated child actions, whole-scalar omission and bounded context; no automatic store access, source read or claim authorization | `src/tools/artifactDetailTool.ts` | 10.7.0 |
96
- | retaining an exact historical source association across native continuation or window trimming, then finding and reading bounded permitted values under fresh host admission | `withSourceEvidence` + `AgentBuilder.sourceEvidence` + native `find_source_evidence` / `read_source_evidence`; explicit producer scope/fields, existing scoped artifacts, bounded reference-only checkpoint carrier, preserved status/coverage and current capability checks; no refresh or answer-completeness guarantee | `src/` | unreleased |
96
+ | retaining an exact historical source association across native continuation or window trimming, then finding and reading bounded permitted values under fresh host admission | `withSourceEvidence` + `AgentBuilder.sourceEvidence` + native `find_source_evidence` / `read_source_evidence`; explicit producer scope/fields, existing scoped artifacts, bounded reference-only checkpoint carrier, preserved status/coverage and current capability checks; no refresh or answer-completeness guarantee | `src/` | 14.6.0 |
97
97
  | the ticket placement just minted being REFUSED by your own `wants` argument as a kind mismatch — because the mint says `tool-result/<toolName>` and your consumer says `dataset/rows` | `Tool.resultKind` + `placedResultKind(toolName, declared?)` (the mint speaks the consumer's vocabulary; the exact-match matcher is untouched) | `src/artifacts/placement.ts` | 9.70.0 |
98
98
  | a viewer guessing which column of a dataset is time (epoch seconds under `ts`, wall-clock strings, a `bucket` column) and opening a series as a table | `timeAxis` on `PutArtifactInput` / `ArtifactMeta` (column · `'iso'`/`'epoch-s'`/`'epoch-ms'` · zone · interval · aggregate) + `readTimeAxis` + `describeTimeAxis` + `timeAxisIssues` (judged at mint, never repaired) | `src/time/axis.ts` | 9.128.0 |
99
99
  | a chart or check comparing a dataset's time values as spellings — epoch seconds beside ISO strings, `+02:00` beside `Z`, a wall-clock string with no offset silently read as UTC, two `01:30` rows in the hour the clocks go back; a READ-SIDE view (the stored rows are never rewritten): UTC instants at one precision, sorted, each with its row; an offset-less value under a zone-less axis is counted (`status: 'naive-values'`) or refused (`naive: 'refuse'`), never read as UTC; a fall-back wall time placed by row order and noted, else counted `dstAmbiguous`; a skipped one `dstGap` (the axis is re-exported from `src/artifacts/`) | `normaliseInstants` + `NormalisedAxis` | `src/time/axis.ts` | 9.129.0 |
@@ -166,7 +166,7 @@ not in this table, search `src/index.ts` for the nearest noun before writing cod
166
166
  | signing people in through the company's identity provider in the browser (OIDC authorization code + PKCE) — PENDING INDEPENDENT REVIEW: a sealed per-attempt transaction cookie (nothing on the server), `returnTo` pinned to the public origin, the person read from an ACCESS token by the strategy's own verify (one id for browser and bearer), private-key or secret client authentication, AD FS `resource`, 303 with no-referrer, end-session | `oidcSignIn` + `signInDoor({ redirect })` + `safeReturnTo` + `IDENTITY_CLIENT_ID` / `IDENTITY_CLIENT_KEY_FILE` / `IDENTITY_PKCE` (`identityFromConfig` → mode `redirect`) | `src/adapters/identity/oidcSignIn.ts` | 9.117.0 |
167
167
  | signing people in with their Windows password against plain Active Directory (no federation server) — LDAPS only, the empty password refused before the bind, RFC 4532 Who-am-I then exactly one entry (the rename collision closed), the id = objectGUID, a nested required group, one answer for every wrong credential, limits from AD's lockout threshold (a third per ACCOUNT via `PasswordChecker.budgetKey`, reset from the LAST failure; threshold 1–2 refused unless overridden), the MFA bypass stated — PENDING INDEPENDENT REVIEW | `directoryPasswords` + `ldapDirectory` + `IDENTITY_STRATEGY=directory-password` (`IDENTITY_LDAP_*`) | `src/adapters/identity/directory/` | 9.117.0 |
168
168
  | labelling a password sign-in form for the password it takes — "Windows username" for the company directory, "Username" for a local list — from the door's own answer, not a guess: `GET /auth/config` adds `passwordKind` (`'directory'` or `'local'`) beside `mode: 'password'`, the checker's declared `kind` (`directoryPasswords` declares `'directory'`, `localPasswords` `'local'`); a fact, the words stay the page's; no key when the checker declares none | `PasswordKind` + `PasswordChecker` (its `kind`) | `src/hosting/signin/door.ts` | 9.118.0 |
169
- | admitting a directory user through any one of several access groups with one bind and one escaped membership search; empty group lists refuse construction | `directoryPasswords` | `src/adapters/identity/directory/` | unreleased |
169
+ | admitting a directory user through any one of several access groups with one bind and one escaped membership search; empty group lists refuse construction | `directoryPasswords` | `src/adapters/identity/directory/` | 14.6.0 |
170
170
  | an audit trail of every sign-in — who tried, from which address, when, and why it was refused (AD's bind sub-code and its name on `directory-password`), success included; one JSON log line per outcome with no code, a typed sink for your own store; never a password, cookie or token | `signInDoor({ onAudit, log })` + `SignInAuditRecord` + `PasswordChecker.check`'s `note` + `adSubCodeName` + `identityFromConfig(…, { onSignInAudit, signInLog })` | `src/hosting/signin/audit.ts` | 9.135.0 |
171
171
  | trusting a DC certificate a PUBLIC CA issued, from Node's own store instead of a CA file (explicit, never unset-means-system), and refusing — not only delaying — a client address after N failed sign-ins, opt-in | `systemCa` + `IDENTITY_LDAP_CA_FILE=system` + `refuseAddressAfter` + `IDENTITY_SIGN_IN_ADDRESS_REFUSE_AFTER` | `src/adapters/identity/directory/ldapDirectory.ts` | 9.135.0 |
172
172
  | trusting a company login proxy (oauth2-proxy, mod_auth_openidc, Pomerium) only as far as the signed ACCESS token it forwards — verified with a literal issuer and a JWKS URL (no discovery, no redirects), the person test and the proxy's client check; an ID token refused; the door guard required because the proxy's cookie rides along on forged requests | `proxyTokenChoice` + `IDENTITY_PROXY_TOKEN` + `IDENTITY_PROXY_HEADER` (strategy `proxy-token` of `identityFromConfig`, mode `proxy`) | `src/adapters/identity/strategies/proxyChoice.ts` | 9.117.0 |
@@ -0,0 +1,20 @@
1
+ import type { DefinitionList } from '../definitions.js';
2
+ import type { PooledClient } from '../pooledClient.js';
3
+ /** An app lease, as the pool tracks it for `maxLeaseMs`. */
4
+ export interface HeldLease {
5
+ readonly client: PooledClient;
6
+ readonly takenAt: number;
7
+ /** Revoked: its next use throws `lease-expired`. */
8
+ revoked: boolean;
9
+ /** Released: idempotent. */
10
+ released: boolean;
11
+ }
12
+ /** Where a list's definitions live: a client's own, or a shared entry. */
13
+ export interface ServedList {
14
+ readonly list: DefinitionList;
15
+ readonly shared: boolean;
16
+ /** The definitions context: `pc:` or `sh:`. */
17
+ readonly context: string;
18
+ }
19
+ /** What a failed request proved about its client, if anything. */
20
+ export type RequestEvidenceOutcome = 'expired' | 'handle-lost' | undefined;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=contracts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contracts.js","sourceRoot":"","sources":["../../../../../src/mcp/pool/pool/contracts.ts"],"names":[],"mappings":""}
@@ -0,0 +1,48 @@
1
+ import type { McpTerminateOutcome } from '../../types.js';
2
+ import { type ClientSet } from '../clientSet.js';
3
+ import type { PoolKey } from '../identityKey.js';
4
+ import type { PoolSettings } from '../options.js';
5
+ import type { EndReason, PooledClient } from '../pooledClient.js';
6
+ import type { OperationBudget } from '../work.js';
7
+ /** Existing pool owners and callbacks used while draining lifecycle work. */
8
+ export interface DrainHost {
9
+ readonly clients: ClientSet;
10
+ readonly budget: OperationBudget;
11
+ readonly settings: Pick<PoolSettings, 'maxEnding'>;
12
+ readonly idleWaiters: Set<() => void>;
13
+ readonly settleWaiters: Array<() => void>;
14
+ shutDown(): void;
15
+ endClient(client: PooledClient, reason: EndReason): void;
16
+ defer(client: PooledClient, reason: EndReason): void;
17
+ }
18
+ /** Drain and settlement work over the pool's authoritative state. */
19
+ export declare class PoolDrain {
20
+ private readonly host;
21
+ constructor(host: DrainHost);
22
+ notifyIdle(): void;
23
+ /**
24
+ * Stop new leases on every client `scope` names, at once; wait for their
25
+ * in-flight work up to `waitMs`; then end each one whose slots can be
26
+ * reserved. The rest are reported deferred and ended when they can be.
27
+ */
28
+ terminate(matches: (key: PoolKey) => boolean, reason: EndReason, waitMs: number): Promise<readonly McpTerminateOutcome[]>;
29
+ /** End each of `clients` whose slots can be reserved; the outcomes of those that started. */
30
+ private endNow;
31
+ /** Wait until every client in `clients` is idle, or `waitMs` passed. */
32
+ private waitIdle;
33
+ /**
34
+ * Close: refuse new work, revoke app leases, abort in-flight work through the
35
+ * pool's own signal, then end every client as slots can be reserved — at most
36
+ * `maxEnding` at a time — in rounds, each bounded by `waitMs` (and each
37
+ * ending's answer by its own deadline). What could not be ended yet is
38
+ * reported deferred and ended when slots free; work still unsettled stays
39
+ * charged until it settles.
40
+ */
41
+ closeAll(waitMs: number): Promise<readonly McpTerminateOutcome[]>;
42
+ /** Wait until an ending slot and an operation slot are free, or `waitMs` passed. */
43
+ private waitSlots;
44
+ /** Resolve once every charged operation and every ending has settled. */
45
+ settled(): Promise<void>;
46
+ private quiet;
47
+ notifySettled(): void;
48
+ }
@@ -0,0 +1,127 @@
1
+ import { previousOf } from '../clientSet.js';
2
+ /** Drain and settlement work over the pool's authoritative state. */
3
+ export class PoolDrain {
4
+ host;
5
+ constructor(host) {
6
+ this.host = host;
7
+ }
8
+ notifyIdle() {
9
+ for (const check of [...this.host.idleWaiters])
10
+ check();
11
+ }
12
+ /**
13
+ * Stop new leases on every client `scope` names, at once; wait for their
14
+ * in-flight work up to `waitMs`; then end each one whose slots can be
15
+ * reserved. The rest are reported deferred and ended when they can be.
16
+ */
17
+ async terminate(matches, reason, waitMs) {
18
+ const named = this.host.clients.openClients().filter((c) => matches(c.key));
19
+ for (const client of named) {
20
+ client.closedToNew = true;
21
+ this.host.clients.retire(client, previousOf(reason) ?? 'terminated');
22
+ }
23
+ await this.waitIdle(named, waitMs);
24
+ return this.endNow(named, reason);
25
+ }
26
+ /** End each of `clients` whose slots can be reserved; the outcomes of those that started. */
27
+ endNow(clients, reason) {
28
+ const outcomes = [];
29
+ for (const client of clients) {
30
+ if (client.state !== 'open')
31
+ continue;
32
+ this.host.endClient(client, reason);
33
+ if (client.state === 'ending' && client.endingOutcome !== undefined) {
34
+ outcomes.push(client.endingOutcome);
35
+ }
36
+ }
37
+ return Promise.all(outcomes);
38
+ }
39
+ /** Wait until every client in `clients` is idle, or `waitMs` passed. */
40
+ waitIdle(clients, waitMs) {
41
+ if (!clients.some((c) => c.busy))
42
+ return Promise.resolve();
43
+ return new Promise((resolve) => {
44
+ const done = () => {
45
+ clearTimeout(timer);
46
+ this.host.idleWaiters.delete(check);
47
+ resolve();
48
+ };
49
+ const check = () => {
50
+ if (!clients.some((c) => c.busy))
51
+ done();
52
+ };
53
+ const timer = setTimeout(done, waitMs);
54
+ timer.unref?.();
55
+ this.host.idleWaiters.add(check);
56
+ });
57
+ }
58
+ /**
59
+ * Close: refuse new work, revoke app leases, abort in-flight work through the
60
+ * pool's own signal, then end every client as slots can be reserved — at most
61
+ * `maxEnding` at a time — in rounds, each bounded by `waitMs` (and each
62
+ * ending's answer by its own deadline). What could not be ended yet is
63
+ * reported deferred and ended when slots free; work still unsettled stays
64
+ * charged until it settles.
65
+ */
66
+ async closeAll(waitMs) {
67
+ this.host.shutDown();
68
+ const all = this.host.clients.openClients();
69
+ for (const client of all) {
70
+ client.closedToNew = true;
71
+ this.host.clients.retire(client, 'terminated');
72
+ }
73
+ await this.waitIdle(all, waitMs);
74
+ const outcomes = [];
75
+ for (;;) {
76
+ const started = await this.endNow(all, 'closed');
77
+ if (started.length === 0)
78
+ break;
79
+ outcomes.push(...started);
80
+ if (!all.some((c) => c.state === 'open'))
81
+ break;
82
+ await this.waitSlots(waitMs);
83
+ }
84
+ for (const client of all) {
85
+ if (client.state === 'open' || client.state === 'opening')
86
+ this.host.defer(client, 'closed');
87
+ }
88
+ return outcomes;
89
+ }
90
+ /** Wait until an ending slot and an operation slot are free, or `waitMs` passed. */
91
+ waitSlots(waitMs) {
92
+ const free = () => this.host.clients.endingCount < this.host.settings.maxEnding && this.host.budget.hasRoom;
93
+ if (free())
94
+ return Promise.resolve();
95
+ return new Promise((resolve) => {
96
+ const done = () => {
97
+ clearTimeout(timer);
98
+ unsubscribe();
99
+ resolve();
100
+ };
101
+ const timer = setTimeout(done, waitMs);
102
+ timer.unref?.();
103
+ const unsubscribe = this.host.budget.whenReleased(() => {
104
+ if (free())
105
+ done();
106
+ });
107
+ });
108
+ }
109
+ /** Resolve once every charged operation and every ending has settled. */
110
+ settled() {
111
+ if (this.quiet())
112
+ return Promise.resolve();
113
+ return new Promise((resolve) => this.host.settleWaiters.push(resolve));
114
+ }
115
+ quiet() {
116
+ return (this.host.budget.count === 0 &&
117
+ this.host.clients.endingCount === 0 &&
118
+ !this.host.clients.openClients().some((c) => c.state === 'opening'));
119
+ }
120
+ notifySettled() {
121
+ if (!this.quiet())
122
+ return;
123
+ for (const resolve of this.host.settleWaiters.splice(0))
124
+ resolve();
125
+ }
126
+ }
127
+ //# sourceMappingURL=drain.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drain.js","sourceRoot":"","sources":["../../../../../src/mcp/pool/pool/drain.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAkB,MAAM,iBAAiB,CAAC;AAkB7D,qEAAqE;AACrE,MAAM,OAAO,SAAS;IACS;IAA7B,YAA6B,IAAe;QAAf,SAAI,GAAJ,IAAI,CAAW;IAAG,CAAC;IAEhD,UAAU;QACR,KAAK,MAAM,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC;YAAE,KAAK,EAAE,CAAC;IAC1D,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,SAAS,CACb,OAAkC,EAClC,MAAiB,EACjB,MAAc;QAEd,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QAC5E,KAAK,MAAM,MAAM,IAAI,KAAK,EAAE,CAAC;YAC3B,MAAM,CAAC,WAAW,GAAG,IAAI,CAAC;YAC1B,IAAI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,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IACzE,CAAC;IAEO,KAAK;QACX,OAAO,CACL,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,KAAK,CAAC;YAC5B,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,KAAK,CAAC;YACnC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,SAAS,CAAC,CACpE,CAAC;IACJ,CAAC;IAED,aAAa;QACX,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE;YAAE,OAAO;QAC1B,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;YAAE,OAAO,EAAE,CAAC;IACrE,CAAC;CACF"}
@@ -0,0 +1,71 @@
1
+ /** Capacity reservation and ending against the pool's authoritative owners. */
2
+ import { type ClientSet } from '../clientSet.js';
3
+ import type { McpPoolLimit, PoolFullError } from '../errors.js';
4
+ import type { PoolKey } from '../identityKey.js';
5
+ import type { PoolSettings } from '../options.js';
6
+ import type { EndReason, PooledClient } from '../pooledClient.js';
7
+ import type { Reporter } from '../record.js';
8
+ import type { OperationBudget, Work } from '../work.js';
9
+ import type { RequestEvidenceOutcome } from './contracts.js';
10
+ /** Actual pool owners and synchronous callbacks needed to end clients. */
11
+ export interface EndingHost {
12
+ readonly clients: ClientSet;
13
+ readonly budget: OperationBudget;
14
+ readonly settings: PoolSettings;
15
+ readonly reporter: Reporter;
16
+ now(): number;
17
+ full(limit: McpPoolLimit): PoolFullError;
18
+ noteUnresolvedEnding(): void;
19
+ notifySettled(): void;
20
+ }
21
+ export declare class PoolEndingLifecycle {
22
+ private readonly host;
23
+ constructor(host: EndingHost);
24
+ /**
25
+ * Make room for a new client of `key`: the principal's least recently used
26
+ * idle client, then the pool's, moves to the ending set — or `PoolFullError`
27
+ * at once, naming the budget. There is no queue.
28
+ */
29
+ makeRoom(key: PoolKey): void;
30
+ /**
31
+ * Move `victim` to the ending set to make room. When the slots cannot be
32
+ * reserved, the arrival is refused at once, and the victim stays in the open
33
+ * set, counted, reported deferred — ended once slots free.
34
+ */
35
+ private evict;
36
+ /** An ending slot and an operation slot, both, or which one is full. */
37
+ private reserveEnding;
38
+ /**
39
+ * End `client` for `reason` — when it is idle and both slots can be reserved.
40
+ * Otherwise it stays in the open set, still counted, and is reported deferred
41
+ * (once); it is ended when its last lease ends or slots free.
42
+ */
43
+ endClient(client: PooledClient, reason: EndReason): void;
44
+ defer(client: PooledClient, reason: EndReason): void;
45
+ /**
46
+ * Move `client` into the ending set under `operation`, and end it through
47
+ * `terminate()` — or, for a lost handle, through its local close alone.
48
+ */
49
+ private startEnding;
50
+ private noteEnded;
51
+ /**
52
+ * A client whose handle this process lost: nothing can be sent for it, so it
53
+ * leaves its key at once — the next use opens the key's next client — and is
54
+ * ended under the ending rule like any other: its ending is its LOCAL close,
55
+ * charged an ending slot and an operation slot until that close settles, its
56
+ * remote outcome recorded unresolved. Busy, or with no slots free, it waits —
57
+ * still counted in the open set, reported deferred.
58
+ */
59
+ lostHandle(client: PooledClient): void;
60
+ /** A client whose session the server ended: no new lease; ended (through `terminate()`) when idle. */
61
+ expired(client: PooledClient): void;
62
+ sweepIdle(): void;
63
+ /** Retry every deferred ending whose client is now idle. */
64
+ retryDeferred(): void;
65
+ /**
66
+ * A request failed: when the pool's fetch read the server's own 404 for the
67
+ * session, or this process lost the handle, the client leaves its key — the
68
+ * next use opens the next client under the SAME key — and the error says so.
69
+ */
70
+ classifyFailure(client: PooledClient, work: Work, error: unknown): RequestEvidenceOutcome;
71
+ }
@@ -0,0 +1,190 @@
1
+ /** Capacity reservation and ending against the pool's authoritative owners. */
2
+ import { isLocalSessionHandleLost } from '../../../tools/toolSessions.js';
3
+ import { previousOf } from '../clientSet.js';
4
+ import { closeLocally } from './endings.js';
5
+ export class PoolEndingLifecycle {
6
+ host;
7
+ constructor(host) {
8
+ this.host = host;
9
+ }
10
+ // ─── Making room, and ending ───────────────────────────────────────
11
+ /**
12
+ * Make room for a new client of `key`: the principal's least recently used
13
+ * idle client, then the pool's, moves to the ending set — or `PoolFullError`
14
+ * at once, naming the budget. There is no queue.
15
+ */
16
+ makeRoom(key) {
17
+ if (this.host.clients.principalCount(key.principal) >= this.host.settings.maxClientsPerPrincipal) {
18
+ const victim = this.host.clients.leastRecentlyUsedIdle((c) => c.key.principal === key.principal);
19
+ if (victim === undefined)
20
+ throw this.host.full('principal');
21
+ this.evict(victim);
22
+ }
23
+ if (this.host.clients.openCount >= this.host.settings.maxClients) {
24
+ const victim = this.host.clients.leastRecentlyUsedIdle(() => true);
25
+ if (victim === undefined)
26
+ throw this.host.full('pool');
27
+ this.evict(victim);
28
+ }
29
+ }
30
+ /**
31
+ * Move `victim` to the ending set to make room. When the slots cannot be
32
+ * reserved, the arrival is refused at once, and the victim stays in the open
33
+ * set, counted, reported deferred — ended once slots free.
34
+ */
35
+ evict(victim) {
36
+ const reserved = this.reserveEnding();
37
+ if (typeof reserved === 'string') {
38
+ this.defer(victim, 'evicted');
39
+ throw this.host.full(reserved);
40
+ }
41
+ // A victim already waiting to end for a stronger reason ends for that one.
42
+ const waiting = victim.deferredEnd;
43
+ const reason = waiting !== undefined && waiting !== 'idle' ? waiting : 'evicted';
44
+ this.startEnding(victim, reason, reserved);
45
+ }
46
+ /** An ending slot and an operation slot, both, or which one is full. */
47
+ reserveEnding() {
48
+ if (this.host.clients.endingCount >= this.host.settings.maxEnding)
49
+ return 'ending';
50
+ return this.host.budget.admit('ending', 'ending', [], this.host.now()) ?? 'operations';
51
+ }
52
+ /**
53
+ * End `client` for `reason` — when it is idle and both slots can be reserved.
54
+ * Otherwise it stays in the open set, still counted, and is reported deferred
55
+ * (once); it is ended when its last lease ends or slots free.
56
+ */
57
+ endClient(client, reason) {
58
+ if (client.state !== 'open' || client.busy || client.port === undefined) {
59
+ this.defer(client, reason);
60
+ return;
61
+ }
62
+ const reserved = this.reserveEnding();
63
+ if (typeof reserved === 'string') {
64
+ this.defer(client, reason);
65
+ return;
66
+ }
67
+ this.startEnding(client, reason, reserved);
68
+ }
69
+ defer(client, reason) {
70
+ const first = client.deferredEnd === undefined;
71
+ // A stronger reason replaces a weaker one: terminated, closed or expired
72
+ // outrank an idle end or an eviction.
73
+ if (first || client.deferredEnd === 'idle' || client.deferredEnd === 'evicted') {
74
+ client.deferredEnd = reason;
75
+ }
76
+ if (!first || client.state === 'ending' || client.state === 'ended')
77
+ return;
78
+ this.host.reporter.report({
79
+ kind: 'deferred',
80
+ clientId: client.clientId,
81
+ keyHash: client.key.keyHash,
82
+ reason,
83
+ durationMs: 0,
84
+ });
85
+ }
86
+ /**
87
+ * Move `client` into the ending set under `operation`, and end it through
88
+ * `terminate()` — or, for a lost handle, through its local close alone.
89
+ */
90
+ startEnding(client, reason, operation) {
91
+ client.deferredEnd = undefined;
92
+ client.state = 'ending';
93
+ this.host.clients.moveToEnding(client, previousOf(reason));
94
+ client.phase = operation;
95
+ const ending = client.lost === 'handle-lost'
96
+ ? closeLocally(client)
97
+ : client.port.end();
98
+ client.endingOutcome = ending.outcome;
99
+ operation.track(ending.settled);
100
+ void ending.outcome.then((outcome) => {
101
+ this.noteEnded(client, reason, outcome);
102
+ operation.finish();
103
+ });
104
+ operation.onSettled(() => {
105
+ this.host.clients.ended(client);
106
+ client.state = 'ended';
107
+ client.phase = undefined;
108
+ // The ending slot is free only now: deferred endings may run, and a
109
+ // `settled()` waiting on the ending set may resolve.
110
+ this.retryDeferred();
111
+ this.host.notifySettled();
112
+ });
113
+ }
114
+ noteEnded(client, reason, outcome) {
115
+ if (!outcome.resolved)
116
+ this.host.noteUnresolvedEnding();
117
+ this.host.reporter.report({
118
+ kind: 'ended',
119
+ clientId: client.clientId,
120
+ keyHash: client.key.keyHash,
121
+ reason,
122
+ remote: outcome.remote,
123
+ resolved: outcome.resolved,
124
+ ...(outcome.status !== undefined && { status: outcome.status }),
125
+ ...(outcome.errorClass !== undefined && { errorClass: outcome.errorClass }),
126
+ durationMs: outcome.durationMs,
127
+ });
128
+ }
129
+ /**
130
+ * A client whose handle this process lost: nothing can be sent for it, so it
131
+ * leaves its key at once — the next use opens the key's next client — and is
132
+ * ended under the ending rule like any other: its ending is its LOCAL close,
133
+ * charged an ending slot and an operation slot until that close settles, its
134
+ * remote outcome recorded unresolved. Busy, or with no slots free, it waits —
135
+ * still counted in the open set, reported deferred.
136
+ */
137
+ lostHandle(client) {
138
+ if (client.lost !== undefined || client.state !== 'open')
139
+ return;
140
+ client.lost = 'handle-lost';
141
+ client.closedToNew = true;
142
+ this.host.clients.retire(client, 'handle-lost');
143
+ this.endClient(client, 'handle-lost');
144
+ }
145
+ /** A client whose session the server ended: no new lease; ended (through `terminate()`) when idle. */
146
+ expired(client) {
147
+ if (client.lost !== undefined)
148
+ return;
149
+ client.lost = 'expired';
150
+ client.closedToNew = true;
151
+ this.host.clients.retire(client, 'expired');
152
+ this.endClient(client, 'expired');
153
+ }
154
+ sweepIdle() {
155
+ const cutoff = this.host.now() - this.host.settings.idleMs;
156
+ for (const client of this.host.clients.openClients()) {
157
+ if (client.state !== 'open' || client.busy || client.deferredEnd !== undefined)
158
+ continue;
159
+ // Retired only once its ending starts (`startEnding`): while it waits
160
+ // for slots, its own conversation may still use it.
161
+ if (client.usedAt <= cutoff)
162
+ this.endClient(client, 'idle');
163
+ }
164
+ }
165
+ /** Retry every deferred ending whose client is now idle. */
166
+ retryDeferred() {
167
+ for (const client of this.host.clients.openClients()) {
168
+ if (client.deferredEnd === undefined || client.busy || client.state !== 'open')
169
+ continue;
170
+ this.endClient(client, client.deferredEnd);
171
+ }
172
+ }
173
+ /**
174
+ * A request failed: when the pool's fetch read the server's own 404 for the
175
+ * session, or this process lost the handle, the client leaves its key — the
176
+ * next use opens the next client under the SAME key — and the error says so.
177
+ */
178
+ classifyFailure(client, work, error) {
179
+ if (isLocalSessionHandleLost(error) || work.evidence === 'handle-lost') {
180
+ this.lostHandle(client);
181
+ return 'handle-lost';
182
+ }
183
+ if (work.evidence === 'server-404') {
184
+ this.expired(client);
185
+ return 'expired';
186
+ }
187
+ return undefined;
188
+ }
189
+ }
190
+ //# sourceMappingURL=endingLifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endingLifecycle.js","sourceRoot":"","sources":["../../../../../src/mcp/pool/pool/endingLifecycle.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAE/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAE1E,OAAO,EAAE,UAAU,EAAkB,MAAM,iBAAiB,CAAC;AAQ7D,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAc5C,MAAM,OAAO,mBAAmB;IACD;IAA7B,YAA6B,IAAgB;QAAhB,SAAI,GAAJ,IAAI,CAAY;IAAG,CAAC;IAEjD,sEAAsE;IAEtE;;;;OAIG;IACH,QAAQ,CAAC,GAAY;QACnB,IACE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,sBAAsB,EAC5F,CAAC;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,CACpD,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,KAAK,GAAG,CAAC,SAAS,CACzC,CAAC;YACF,IAAI,MAAM,KAAK,SAAS;gBAAE,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAC5D,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QACrB,CAAC;QACD,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,E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,CAAC,MAAM,CAAC;QAC3D,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;YACrD,IAAI,MAAM,CAAC,KAAK,KAAK,MAAM,IAAI,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,WAAW,KAAK,SAAS;gBAAE,SAAS;YACzF,sEAAsE;YACtE,oDAAoD;YACpD,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM;gBAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED,4DAA4D;IAC5D,aAAa;QACX,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;YACrD,IAAI,MAAM,CAAC,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,KAAK,KAAK,MAAM;gBAAE,SAAS;YACzF,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,eAAe,CAAC,MAAoB,EAAE,IAAU,EAAE,KAAc;QAC9D,IAAI,wBAAwB,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,QAAQ,KAAK,aAAa,EAAE,CAAC;YACvE,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YACxB,OAAO,aAAa,CAAC;QACvB,CAAC;QACD,IAAI,IAAI,CAAC,QAAQ,KAAK,YAAY,EAAE,CAAC;YACnC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YACrB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,13 @@
1
+ import type { ClientPort } from '../../clientPort.js';
2
+ import type { Ending } from '../../terminate.js';
3
+ import type { PooledClient } from '../pooledClient.js';
4
+ /** A port that can only end: what a half-opened session leaves the pool. */
5
+ export declare function endingOnly(halfOpen: {
6
+ end(): ReturnType<ClientPort['end']>;
7
+ }): ClientPort;
8
+ /**
9
+ * A lost handle's ending: nothing can be sent for it, so the remote outcome is
10
+ * known at once — `handle-lost`, unresolved — and the work is the local close
11
+ * alone, which the ending stays charged for until it settles.
12
+ */
13
+ export declare function closeLocally(client: PooledClient): Ending;
@@ -0,0 +1,28 @@
1
+ /** A port that can only end: what a half-opened session leaves the pool. */
2
+ export function endingOnly(halfOpen) {
3
+ return {
4
+ listing: () => Promise.reject(new Error('This client never opened.')),
5
+ bind: () => {
6
+ throw new Error('This client never opened.');
7
+ },
8
+ end: () => halfOpen.end(),
9
+ };
10
+ }
11
+ /**
12
+ * A lost handle's ending: nothing can be sent for it, so the remote outcome is
13
+ * known at once — `handle-lost`, unresolved — and the work is the local close
14
+ * alone, which the ending stays charged for until it settles.
15
+ */
16
+ export function closeLocally(client) {
17
+ const target = client.client;
18
+ const settled = target === undefined
19
+ ? Promise.resolve()
20
+ : Promise.resolve()
21
+ .then(() => target.close())
22
+ .then(() => undefined, () => undefined);
23
+ return {
24
+ outcome: Promise.resolve({ remote: 'handle-lost', resolved: false, durationMs: 0 }),
25
+ settled,
26
+ };
27
+ }
28
+ //# sourceMappingURL=endings.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endings.js","sourceRoot":"","sources":["../../../../../src/mcp/pool/pool/endings.ts"],"names":[],"mappings":"AAIA,4EAA4E;AAC5E,MAAM,UAAU,UAAU,CAAC,QAAkD;IAC3E,OAAO;QACL,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;QACrE,IAAI,EAAE,GAAG,EAAE;YACT,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;QAC/C,CAAC;QACD,GAAG,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE;KAC1B,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,MAAoB;IAC/C,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC;IAC7B,MAAM,OAAO,GACX,MAAM,KAAK,SAAS;QAClB,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE;QACnB,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE;aACd,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;aAC1B,IAAI,CACH,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;IACV,OAAO;QACL,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;QACnF,OAAO;KACR,CAAC;AACJ,CAAC"}
@@ -0,0 +1,56 @@
1
+ import type { ClientSet } from '../clientSet.js';
2
+ import type { McpPoolRefusedError } from '../errors.js';
3
+ import type { PoolKey } from '../identityKey.js';
4
+ import type { PoolSettings } from '../options.js';
5
+ import type { ClientPlan } from '../plan.js';
6
+ import type { EndReason, PooledClient } from '../pooledClient.js';
7
+ import type { Reporter, UseFacts } from '../record.js';
8
+ import type { Operation } from '../work.js';
9
+ import type { HeldLease } from './contracts.js';
10
+ /** Existing pool owners and callbacks used by lease lifecycle work. */
11
+ export interface LeasesHost {
12
+ readonly clients: ClientSet;
13
+ readonly leases: Set<HeldLease>;
14
+ readonly settings: Pick<PoolSettings, 'maxLeaseMs'>;
15
+ readonly reporter: Reporter;
16
+ readonly closed: boolean;
17
+ now(): number;
18
+ refused(reason: McpPoolRefusedError['reason'], cause?: unknown): McpPoolRefusedError;
19
+ openFor(key: PoolKey, operation: Operation, facts: UseFacts, resolved: ClientPlan | undefined): PooledClient;
20
+ waitOpen(client: PooledClient, operation: Operation): Promise<void>;
21
+ endClient(client: PooledClient, reason: EndReason): void;
22
+ retryDeferred(): void;
23
+ notifyIdle(): void;
24
+ }
25
+ /** Lease lifecycle work over the pool's authoritative state. */
26
+ export declare class PoolLeases {
27
+ private readonly host;
28
+ constructor(host: LeasesHost);
29
+ /**
30
+ * A library lease on `key`'s client for `operation`, opening one when the key
31
+ * has none (inside the operation's slot). `plan` is the plan resolved for a
32
+ * new client; a key that already has one keeps its own. The lease is
33
+ * released when the operation SETTLES.
34
+ */
35
+ leaseClient(key: PoolKey, operation: Operation, facts: UseFacts, plan?: ClientPlan): Promise<PooledClient>;
36
+ /**
37
+ * Wait for `client`'s open inside `operation`, holding a reservation on it
38
+ * all the while — between the open settling and this lease the client is
39
+ * busy, so nobody can evict, idle-end or end it — then check it again and
40
+ * lease it in the same step, with no wait between. `undefined` when it no
41
+ * longer serves: the caller's next round finds the key's next client.
42
+ */
43
+ private leaseOnceOpen;
44
+ /** `client` may have just become idle: a deferred ending may run, and a waiter for idleness may go on. */
45
+ private becameIdle;
46
+ private takeLease;
47
+ /** One lease ended: the client may now be idle, and a deferred ending may run. */
48
+ releaseLease(client: PooledClient): void;
49
+ /** An app lease: a hold on a client for as long as the app keeps it, at most `maxLeaseMs`. */
50
+ holdLease(client: PooledClient): HeldLease;
51
+ /** End an app lease — at most once, whether released or revoked. */
52
+ endLease(lease: HeldLease): void;
53
+ revokeExpiredLeases(): void;
54
+ /** Every app lease is revoked: the pool is closing. */
55
+ revokeAllLeases(): void;
56
+ }