inspector/core/mcp/state/managedSkillsState.ts
cliffhall da8cc166ce fix: address Copilot review round 1 on #2251
- skills.ts: report a manifest that omits the skill's own SKILL.md
  (an empty list included), duplicate URIs, entries outside the skill
  root, and a missing size. `Conforms` was reachable for manifests that
  break invariants SEP-2640 states.
- skills.ts: cross-check the declared byte length before hashing. A size
  that disagrees fails verification on its own — the digest is taken over
  the bytes the server served, so agreeing with it says nothing about
  whether the manifest describes them.
- skills.ts: copy the view instead of slicing its backing store in
  `sha256Digest`. `SharedArrayBuffer.prototype.slice()` returns another
  SharedArrayBuffer, which `crypto.subtle.digest` rejects — the cast
  claimed to handle the exact input that would have thrown. No cast now.
- skills.ts: state the one obligation NOT checked here — that an entry's
  frontmatter matches the fetched SKILL.md's. The digest cannot cover it,
  and closing it needs a YAML parser, so it is tracked on #2248.
- managedSkillsState: cap the walk at LIST_MAX_PAGES. The repeated-cursor
  guard only catches a server stuck on one cursor; endlessly unique ones
  walked forever. Raises rather than truncating, like the salvage walk.
- managedSkillsState: gate every write on a session generation, so a walk
  that resolves after a disconnect or destroy cannot repopulate a cleared
  store or deliver the previous session's skills into the next.
- inspectorClient: send a cursor when it is `!== undefined`, not when it
  is truthy. An opaque cursor may be `""`, and dropping it re-requested
  page one — which the store then reported as a repeated-cursor failure.
- SkillsScreen: key verdict invalidation on the manifest (URI + digests +
  sizes), not the URI alone. A Refresh that changed the manifest left a
  green badge attached to a digest nothing had checked.
- SkillsScreen: epoch-guard every read continuation, so a fetch that
  resolves after the selection moved on cannot write into the new one.
- SkillsScreen: bound "Verify all" to 4 concurrent reads. A conforming
  manifest may hold 512 files.
- skillsSchemas: drop the guessed `resources/directory/read` result
  schema. Nothing calls it, so an unverified shape could sit wrong
  indefinitely; phase 3 adds it against the normative text.
- skills-http.json: declare the extension bare. It advertised
  `directoryRead: true` with no handler, so Connection Info reported
  "Supported" for a method that answers -32601.
- types.ts: restore the Tasks doc comment the Skills interface displaced.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018kfrH3uRNUM4JAk1reKtyY
Signed-off-by: cliffhall <cliff@futurescale.com>
2026-09-04 21:23:58 -04:00

222 lines
8.9 KiB
TypeScript

/**
* ManagedSkillsState: holds the full skill list (SEP-2640), in sync with the
* server. Loaded on connect, cleared on disconnect, re-walked on refresh.
*
* Deliberately NOT a `ManagedListState` subclass, despite the family
* resemblance. That base is built around two things the Skills extension does
* not have: a top-level `ServerCapabilities` key to gate on (skills is a
* *server-declared extension*, read from `capabilities.extensions`), and a
* per-list `list_changed` notification to debounce and turn into a sidebar
* indicator
* (SEP-2640 defines none). Subclassing would mean widening the base's
* capability gate and inventing a list-changed event nothing dispatches — two
* changes to shared machinery to serve one caller. The cursor walk below is the
* only behavior actually shared, and it is nine lines.
*
* The walk is done here rather than through an SDK `listAll*` verb for the same
* reason the request is a plain `client.request`: the SDK has no high-level verb
* for a consumer-owned extension method, so there is no cache-aware wrapper to
* delegate to and no `cacheMode` to honor.
*/
import type { InspectorClientProtocol } from "../inspectorClientProtocol.js";
import type { SkillEntry } from "../skillsSchemas.js";
import { LIST_MAX_PAGES } from "../listSalvage.js";
import { isTerminalStatus } from "../types.js";
import type { RequestMetadata } from "../types.js";
import { TypedEventTarget } from "../typedEventTarget.js";
export interface SkillsPaginationState {
/** Pages walked on the last completed refresh (a one-page list is 1). */
pageCount: number;
}
export interface ManagedSkillsStateEventMap {
skillsChange: SkillEntry[];
paginationChange: SkillsPaginationState;
/** The last walk's failure, or `null` once one succeeds. */
errorChange: Error | null;
}
/**
* Thrown when a server hands back a cursor it already handed back, which would
* otherwise walk forever. Surfaced as the store's error so the panel reports the
* server bug instead of hanging — the same "report, don't swallow" posture the
* conformance checks take.
*/
export const REPEATED_CURSOR_MESSAGE =
"Server repeated a pagination cursor in skills/list; stopped to avoid an infinite walk.";
/**
* Page cap for the `skills/list` walk. Mirrors `LIST_MAX_PAGES`, the bound the
* SDK's aggregate verbs and the #1909 salvage re-walks already use, so the two
* pagination paths in this repo cannot drift to different limits.
*/
export const SKILLS_MAX_PAGES = LIST_MAX_PAGES;
/** The error a walk raises when it hits {@link SKILLS_MAX_PAGES}. */
export const SKILLS_PAGE_LIMIT_MESSAGE = `skills/list exceeded ${SKILLS_MAX_PAGES} pages without the server's pagination converging`;
export class ManagedSkillsState extends TypedEventTarget<ManagedSkillsStateEventMap> {
private skills: SkillEntry[] = [];
private pageCount = 0;
private error: Error | null = null;
private client: InspectorClientProtocol | null = null;
private unsubscribe: (() => void) | null = null;
// Overlap guard: a walk in flight makes a second one a no-op so a slow older
// walk can't clobber a newer list via last-write-wins.
private running = false;
// Session counter, advanced by `reset` (disconnect) and by `destroy`. A walk
// captures it and abandons its writes when it no longer matches.
private generation = 0;
constructor(client: InspectorClientProtocol) {
super();
this.client = client;
const onConnect = (): void => {
// No caller to await the connect-time load, so its rejection is caught
// here rather than left to become an unhandled rejection. Not a swallow:
// `refresh` has already recorded the failure via `setError`, and the
// panel renders it.
void this.refresh().catch(() => {});
};
const onStatusChange = (): void => {
if (isTerminalStatus(this.client?.getStatus())) {
this.reset();
}
};
this.client.addEventListener("connect", onConnect);
this.client.addEventListener("statusChange", onStatusChange);
this.unsubscribe = () => {
if (this.client) {
this.client.removeEventListener("connect", onConnect);
this.client.removeEventListener("statusChange", onStatusChange);
}
this.client = null;
};
}
/** Defensive copy of the current list. */
getSkills(): SkillEntry[] {
return [...this.skills];
}
getPagination(): SkillsPaginationState {
return { pageCount: this.pageCount };
}
/** The last walk's failure, or `null` when it succeeded. */
getError(): Error | null {
return this.error;
}
// Compared by identity rather than message: two distinct failures with the
// same text are still two events, and a re-render on a repeat failure is
// cheap next to silently coalescing them.
private setError(value: Error | null): void {
if (this.error === value) return;
this.error = value;
this.dispatchTypedEvent("errorChange", value);
}
private reset(): void {
// Advance the session first, so an in-flight walk's continuation sees a
// stale generation and leaves the cleared state alone.
this.generation += 1;
this.skills = [];
this.pageCount = 0;
this.dispatchTypedEvent("skillsChange", this.getSkills());
this.dispatchTypedEvent("paginationChange", this.getPagination());
// A disconnect ends the session the error belonged to — a stale
// "couldn't load skills" must not outlive it into the next connect.
this.setError(null);
}
/**
* Walk every page of `skills/list` and commit the result.
*
* A failure is recorded as observable state (`getError`) AND re-thrown: the
* state drives the panel's error rendering, while the rejection is what a
* caller's auth-recovery wrapper keys off to detect a 401 and start a
* re-authorization. The connect-time load, which has no such caller, catches
* it above.
*/
async refresh(metadata?: RequestMetadata): Promise<SkillEntry[]> {
const client = this.client;
if (!client || client.getStatus() !== "connected") return this.getSkills();
// A server that never declared the extension answers `skills/list` with
// -32601, which would spam the console for a question we already know the
// answer to. An empty list is the right semantics.
if (!client.getSkillsExtension()) {
this.applyPages([], 0);
return this.getSkills();
}
if (this.running) return this.getSkills();
this.running = true;
// The session this walk belongs to. A disconnect, a `destroy()`, or a
// reconnect on the same client advances it, and every write below is
// gated on it still being current — otherwise a slow walk's continuation
// repopulates a store that has already been cleared, or delivers the
// previous session's skills into the next one.
const generation = this.generation;
const isCurrent = () => this.generation === generation;
try {
const collected: SkillEntry[] = [];
const seen = new Set<string>();
let cursor: string | undefined;
let pages = 0;
for (;;) {
const page = await client.listSkills(cursor, metadata);
if (!isCurrent()) return this.getSkills();
collected.push(...page.skills);
pages += 1;
if (page.nextCursor === undefined) break;
// Two distinct runaway shapes, and the repeated-cursor guard only
// catches one: a server stuck on a single cursor. A server that hands
// back an endlessly *unique* cursor walks forever and grows
// `collected` without bound, so the page cap is what stops it. The cap
// raises rather than truncating, for the reason `listPaginationExceeded`
// states: returning what we have would present a partial list as a
// complete one.
if (pages >= SKILLS_MAX_PAGES) {
throw new Error(SKILLS_PAGE_LIMIT_MESSAGE);
}
if (seen.has(page.nextCursor)) {
throw new Error(REPEATED_CURSOR_MESSAGE);
}
seen.add(page.nextCursor);
cursor = page.nextCursor;
}
this.setError(null);
this.applyPages(collected, pages);
return this.getSkills();
} catch (err) {
// Still re-thrown even when the session moved on — the caller's
// auth-recovery wrapper keys off the rejection — but the *state* is left
// alone, so a dead session's failure cannot surface in the live one.
if (isCurrent()) {
this.setError(err instanceof Error ? err : new Error(String(err)));
}
throw err;
} finally {
this.running = false;
}
}
private applyPages(skills: SkillEntry[], pageCount: number): void {
this.skills = skills;
this.pageCount = pageCount;
this.dispatchTypedEvent("skillsChange", this.getSkills());
this.dispatchTypedEvent("paginationChange", this.getPagination());
}
/** Unsubscribe from the client and drop the list; idempotent. */
destroy(): void {
this.generation += 1;
this.unsubscribe?.();
this.unsubscribe = null;
this.skills = [];
this.pageCount = 0;
this.error = null;
}
}