From b40f09e56f626e26df6f76a77e138ad363aaf3f5 Mon Sep 17 00:00:00 2001 From: venomade Date: Tue, 24 Nov 2026 00:52:30 +0000 Subject: [PATCH] Bump vendored T3 Code to 42c9107983 (v0.1.12-nightly) and catch up - vendor/t3code submodule pinned to 42c9107983; deps in package.json aligned with the upstream catalog, including upstream's effect@4.1.5 patch via patchedDependencies (patches/effect@4.1.5.patch) - nix flake.nix devShell provides bun locally (no guix home install) - scripts/link-vendor.ts now copies the vendored packages into node_modules/@t3tools and applies tscPatches for the spots where classic tsc can't infer what upstream's Effect language service can, so `bun run typecheck` runs clean under full strict mode - protocol drift fixes across model/ui/client: usage-limit copy, context window snapshot, checkpoint totals, turn diff summaries, alert observation, "once" schedules, composer trigger kinds, PR keying, thread menu state, secret request answers, terminal summaries, snapshot-required shell events, revert checkpoint lookup - new parity features over the typed RPC: fork a turn into a new thread, rewind a message with its attachments restored to the composer, guest share links and turn-into-project in the thread menu - tests updated and added (301 pass); typecheck, lint and build clean Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- README.md | 2 +- bun.lock | 257 ++- docs/development.md | 4 +- docs/reference.md | 6 +- flake.lock | 27 + flake.nix | 26 + package.json | 27 +- patches/effect@4.1.5.patch | 4140 ++++++++++++++++++++++++++++++++++++ scripts/link-vendor.ts | 52 +- src/client/session.ts | 36 +- src/model/alerts.ts | 28 +- src/model/automations.ts | 2 + src/model/composerMenu.ts | 6 +- src/model/details.ts | 3 +- src/model/pullRequests.ts | 4 + src/model/threadMenu.ts | 18 +- src/model/timeline.ts | 3 + src/model/turns.ts | 24 +- src/model/usage.ts | 3 +- src/pierre-words-wasm.d.ts | 6 + src/ui/App.tsx | 16 +- src/ui/SecretPanel.tsx | 5 +- src/ui/ThreadView.tsx | 7 +- src/ui/terminalAttach.ts | 1 + src/ui/useComposerMenu.ts | 1 - src/ui/useSecretRequest.ts | 4 +- src/ui/useThreadMenu.ts | 12 +- src/ui/useTurns.ts | 28 +- src/ui/useWorkspace.ts | 11 +- test/app/app.test.tsx | 45 + test/app/files.test.tsx | 2 +- test/app/harness.tsx | 8 +- test/details.test.ts | 2 +- test/threadMenu.test.ts | 18 +- test/turns.test.ts | 2 +- test/workspace.test.ts | 4 +- tsconfig.json | 7 +- vendor/t3code | 2 +- 38 files changed, 4786 insertions(+), 63 deletions(-) create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 patches/effect@4.1.5.patch create mode 100644 src/pierre-words-wasm.d.ts diff --git a/README.md b/README.md index 116bc74..9d2b2ed 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ The scopes, the protocol and how to update for a newer T3 Code are in [docs/deve ## Not yet supported -Plan follow-ups, forking threads, reviewing or commenting on diffs, rewinding messages with attachments, project settings and guest sharing. Use the T3 Code app for those. +Reviewing or commenting on pull request diffs, and the project settings editor. Use the T3 Code app for those. ## Licence diff --git a/bun.lock b/bun.lock index be7d623..45e64ff 100644 --- a/bun.lock +++ b/bun.lock @@ -7,12 +7,34 @@ "dependencies": { "@opentui/core": "0.8.1", "@opentui/react": "0.8.1", + "@pierre/diffs": "1.7.0-beta.4", + "@pierre/trees": "1.0.0-beta.6", + "@pierre/words": "file:vendor/t3code/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", "diff": "9.0.0", - "effect": "4.0.5", + "effect": "4.1.5", + "entities": "^6.0.1", + "get-east-asian-width": "^1.6.0", + "gt-i18n": "1.0.40", + "gt-react": "11.4.18", + "hast-util-sanitize": "^5.0.2", + "hast-util-to-html": "^9.0.5", "mdast-util-directive": "^3.2.0", + "mdast-util-to-hast": "13.2.1", "micromark-extension-directive": "^4.0.0", + "micromark-util-character": "2.1.1", + "micromark-util-decode-string": "2.0.1", + "micromark-util-types": "2.0.2", + "property-information": "^7.2.0", "react": "^19.2.0", + "rehype-raw": "7.0.0", + "rehype-sanitize": "6.0.0", + "remark-breaks": "4.0.0", + "remark-gfm": "4.0.1", + "remark-math": "6.0.0", "remark-parse": "^11.0.0", + "remark-rehype": "11.1.2", + "unified": "11.0.5", + "yaml": "^2.9.0", "zustand": "5.0.11", }, "devDependencies": { @@ -25,6 +47,9 @@ }, }, }, + "patchedDependencies": { + "effect@4.1.5": "patches/effect@4.1.5.patch", + }, "packages": { "@biomejs/biome": ["@biomejs/biome@2.5.15", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.15", "@biomejs/cli-darwin-x64": "2.5.15", "@biomejs/cli-linux-arm64": "2.5.15", "@biomejs/cli-linux-arm64-musl": "2.5.15", "@biomejs/cli-linux-x64": "2.5.15", "@biomejs/cli-linux-x64-musl": "2.5.15", "@biomejs/cli-win32-arm64": "2.5.15", "@biomejs/cli-win32-x64": "2.5.15" }, "bin": { "biome": "bin/biome" } }, "sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ=="], @@ -44,6 +69,14 @@ "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.5.15", "", { "os": "win32", "cpu": "x64" }, "sha512-yAzh4UqEImV6Hcy0zjUqNfJAsUhoD64FBQCdTG8Md/Z2wQeVP/ZmJ3XRYAs1g8J9fjTFyl2fCtc5FB5til47+g=="], + "@generaltranslation/api": ["@generaltranslation/api@0.5.6", "", {}, "sha512-rPcqH7BomEIRQKX6oyOagfqrfHddi3EcOkgWC/dgs2qSRhkoZYcpn68RWCr3ZFnmCMib7uDtSR9v8BjUI7AZLQ=="], + + "@generaltranslation/format": ["@generaltranslation/format@0.1.9", "", { "dependencies": { "@generaltranslation/icu": "0.1.2" } }, "sha512-GwXbdajc7pIBsnrxVXE4PqjBHRwgKef4GyauH7CLaXSormRLU8G58ahqfwmQRL6ie1xt5KMMb6UAekdj1i9Sxg=="], + + "@generaltranslation/icu": ["@generaltranslation/icu@0.1.2", "", {}, "sha512-2A0txUrZdAWAc42N58/PtoWv7vNB0U1Iyl+nDzf7RSswLHPMsonp7OmPnSraQgkoRSVSlueARVQK4T+zanWsyA=="], + + "@generaltranslation/react-core": ["@generaltranslation/react-core@11.4.18", "", { "dependencies": { "@generaltranslation/format": "0.1.9", "generaltranslation": "9.5.9", "gt-i18n": "1.0.40" }, "peerDependencies": { "react": ">=18.0.0" } }, "sha512-1fFrMeddHH0mUTvg2iCSzL2Bfsc34j2EtL9hc4wxI8Xkwh2umHHtuZcD2Z3H7uA94w2kXEShgXe1kX/HFxqlOg=="], + "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], "@opentui/core": ["@opentui/core@0.8.1", "", { "dependencies": { "bun-ffi-structs": "0.3.1", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.8.1", "@opentui/core-darwin-x64": "0.8.1", "@opentui/core-linux-arm64": "0.8.1", "@opentui/core-linux-arm64-musl": "0.8.1", "@opentui/core-linux-x64": "0.8.1", "@opentui/core-linux-x64-musl": "0.8.1", "@opentui/core-win32-arm64": "0.8.1", "@opentui/core-win32-x64": "0.8.1" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-WmnpnVZn2MdyYNEahQNn4k3OrIkQKfcwPVrX/DjguLtl/S2g5fPeXCqHZjCg2GLMf1N4HJap0LEkTPJEvfrDXw=="], @@ -66,10 +99,44 @@ "@opentui/react": ["@opentui/react@0.8.1", "", { "dependencies": { "@opentui/core": "0.8.1", "react-reconciler": "^0.33.0" }, "peerDependencies": { "react": ">=19.2.0", "react-devtools-core": "^7.0.1", "ws": "^8.18.0" } }, "sha512-2Suc127MY7iLkgzFjyKJVsML4PZHhtc+lOXgQhP4bP6zxgNCBlGm/FxX0fDbp5RpuogKyIix9s57YnpxQB54nw=="], + "@pierre/diffs": ["@pierre/diffs@1.7.0-beta.4", "", { "dependencies": { "@pierre/highlights": "0.5.1", "@pierre/patches": "0.0.1", "@pierre/theme": "2.0.0", "@pierre/theming": "1.0.2", "diff": "9.0.0", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0 || ^4.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-QtsUN1eO1hfAie0SUBRZ8xfjzybetaOzq3xFPw7UYl/XLkx9KxQ1uRDXHat4B44S2SW8HBt63yWKCSzQ6OQmEQ=="], + + "@pierre/highlights": ["@pierre/highlights@0.5.1", "", {}, "sha512-c2WF6sgwgKdxXU6FpWDLWUYHRca/cJy+3QJkWAqYqEAFxqlPf8eSH0ehHcFFjKBmT+9KBl9H7q6z7HMRU7+m6g=="], + + "@pierre/patches": ["@pierre/patches@0.0.1", "", {}, "sha512-NycJQVQNuqmBdr7u1LsUcmkiIz1fRm9xhWZyRbm21oJYd0MVVCa45t9Lsuj5IKrTMBonxOuh4LMv+R3BpL4bmQ=="], + + "@pierre/theme": ["@pierre/theme@2.0.0", "", {}, "sha512-yNDd9GYLQl1mEUJR8AneJ5e4ohLIHQd/wZLWr4fagt78vS2RwwZNW530vVgHqXFAyFVcFlRmGUD5ramXH46OXw=="], + + "@pierre/theming": ["@pierre/theming@1.0.2", "", { "peerDependencies": { "@pierre/theme": "^1.1.0 || ^2.0.0", "@shikijs/themes": "^3.0.0 || ^4.0.0", "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0", "shiki": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@pierre/theme", "@shikijs/themes", "react", "react-dom", "shiki"] }, "sha512-RmXLLqtx31UGcR8kZyO5hGAQ1EXz6loT1Cu0BFAGsbnBboIxp2BlomkLfWyvdT4WZXnBGyu25onL1gKpFQuSUw=="], + + "@pierre/trees": ["@pierre/trees@1.0.0-beta.6", "", { "dependencies": { "@pierre/theming": "1.0.0", "preact": "11.0.0-beta.0", "preact-render-to-string": "6.6.5" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-zxeuSFM9TveM7b5XofweJALCtm/tGYV9HZzdbf7Uf+kBxIlUyz24/EHaGRjB0dsmmfDQl2ETz7AWwJ15lhSnpw=="], + + "@pierre/words": ["@pierre/words@vendor/t3code/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", { "peerDependencies": { "@pierre/highlights": ">=0.5.1", "react": "^18.3.1 || ^19.0.0" }, "optionalPeers": ["@pierre/highlights", "react"] }, "sha512-EuIvU8imMY3c/deOHm9/gEh9VJga8R7jjWiIKfjKHbDXjgMo/O3NDN15H0dLc/vo+YTf/QpY0xinfnv7xpf7Rw=="], + + "@shikijs/core": ["@shikijs/core@4.6.0", "", { "dependencies": { "@shikijs/primitive": "4.6.0", "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5", "hast-util-to-html": "^9.0.6" } }, "sha512-bfd4OKgvoyXYiYmMRuleA656P4V7M/Du9lcTl38Ngm6KszMj7bq4J1IGZwSYR4c95Tv5UQALtYNWUwaI9UT3xw=="], + + "@shikijs/engine-javascript": ["@shikijs/engine-javascript@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "oniguruma-to-es": "^4.3.6" } }, "sha512-K0oqxFoL+kEMdz89mHLFO15Tsbv3kFZ6WR1cXZKMvLSc+oqaM00A6pyga1qSeXB22dP0tTiSApRcGBaKWsEccg=="], + + "@shikijs/engine-oniguruma": ["@shikijs/engine-oniguruma@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0" } }, "sha512-aggd6Q7SuJOXNnsUbfG2XesxBJKBMAw/PDTUo9PyRjMaaJJ2dNrI+q0C+25ARXAK9yLHAlwxc9oRT2u68YKZ7w=="], + + "@shikijs/langs": ["@shikijs/langs@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0" } }, "sha512-1yMEX3oCVV54LUq/ovfpRkDQoYDkcvjSWFFa/YLUDMiSoRzMi2uxLJYbv41ahT8Lu9lFMaa7hecd3Q39trqUyg=="], + + "@shikijs/primitive": ["@shikijs/primitive@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-c54+TQEo9ToqgfL/AU8FpjnV09+GA9Oa7M5ROkkXteZfp5XzpAJGXjjvZQFQioJOwm/w/6Z3lIzQstAkl8coag=="], + + "@shikijs/themes": ["@shikijs/themes@4.6.0", "", { "dependencies": { "@shikijs/types": "4.6.0" } }, "sha512-qHAVAs80RiGD+IRuH9G+JPDOEc9A/kHsng4EzCUCwB9bLzW6Z0y9WETh2YyCcADJBmfrIaJ1Jp7KBNP6FHkgtQ=="], + + "@shikijs/types": ["@shikijs/types@4.6.0", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-+ENG1adsKt/X7cRYw1Nl7BEpBmPOjmQ7bR/eGmHuMlT8gtOFf3KEi5l31DJYyAWhW6Y6bjP1plU7FmaxWGENFw=="], + + "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.1.0", "", {}, "sha512-cVBuhDQjBZaNMTwBquYfPydrUP+E3hE6oYGasx8h6ZrODIM7/r+gxLDXdd66oszbrggZHEntdE6j+5gYIVyMWQ=="], + "@types/bun": ["@types/bun@1.4.4", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="], "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], + "@types/hast": ["@types/hast@3.0.5", "", { "dependencies": { "@types/unist": "*" } }, "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g=="], + + "@types/katex": ["@types/katex@0.16.8", "", {}, "sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg=="], + "@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="], "@types/ms": ["@types/ms@2.1.0", "", {}, "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="], @@ -80,6 +147,8 @@ "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="], + "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], + "ansi-regex": ["ansi-regex@6.5.0", "", {}, "sha512-zhvbbbdt1kbw7EJ9OQoxmQcuaNR9P5kTj7e/YdmOSU10aHWbycofJxA6jKfoEy3vlLdctOF9ZHaxLtmSm998wQ=="], "bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="], @@ -98,6 +167,10 @@ "character-reference-invalid": ["character-reference-invalid@2.0.1", "", {}, "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw=="], + "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], + + "commander": ["commander@8.3.0", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="], + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], @@ -110,14 +183,42 @@ "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], - "effect": ["effect@4.0.5", "", {}, "sha512-BY4/28NlpOd99yzmV741xbVGmp+1U7tks4oB7F/Png64bTa5tm5eCA6W0RiXsnuLDDoJpjfVSo4Dnq4BZb/89Q=="], + "effect": ["effect@4.1.5", "", {}, "sha512-xyR20KhQI0vg2gD8ILUSQRTTESEYJ0JKdP+QD8J37xbwPTqXRxFM/l0+vUVD9fuSvoYruoTqyt33C4FZv1s4TQ=="], "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + "entities": ["entities@6.0.1", "", {}, "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g=="], + + "escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="], + "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], + "generaltranslation": ["generaltranslation@9.5.9", "", { "dependencies": { "@generaltranslation/api": "0.5.6", "@generaltranslation/format": "0.1.9", "@generaltranslation/icu": "0.1.2", "@noble/hashes": "^2.2.0" } }, "sha512-/R/MvEEiB+Us/fj/YfuSTfhvzUfmvFpiHxGx2f+C6Wv0O875T0yJI3RLGDopqZVbnKPimog9eXofJL7W0SOxJg=="], + "get-east-asian-width": ["get-east-asian-width@1.7.0", "", {}, "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q=="], + "gt-i18n": ["gt-i18n@1.0.40", "", { "dependencies": { "@generaltranslation/format": "0.1.9", "generaltranslation": "9.5.9" } }, "sha512-EbDhYhtyUrZI4iBSWpe1AMRoYrmEn52/hnVG6NAqVhVvY85t15JCJWMdVOkDoB1TRVH9nbSzAttaYwcv0LF3KQ=="], + + "gt-react": ["gt-react@11.4.18", "", { "dependencies": { "@generaltranslation/react-core": "11.4.18", "generaltranslation": "9.5.9", "gt-i18n": "1.0.40" }, "peerDependencies": { "react": ">=18.0.0", "react-dom": ">=18.0.0" } }, "sha512-c6T+oqvXdT2DSW6kXDc3HYj4MA9fR4B1VgSXaIVG8emAWhZ9Dih4npJBjRWBJNr1D3KrG0nU/+1FPxJ1Zzkhnw=="], + + "hast-util-from-parse5": ["hast-util-from-parse5@8.0.4", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "hastscript": "^9.0.0", "property-information": "^7.0.0", "vfile": "^6.0.0", "vfile-location": "^5.0.0", "web-namespaces": "^2.0.0" } }, "sha512-Yq7XlXor0Cpb71sI2E0zpv8QxQ5a6rfhDEETk4bcgrFX2SvJAY2PHocWwFtL6U9qyfiyByW3wZ6sZEfP2kW81g=="], + + "hast-util-parse-selector": ["hast-util-parse-selector@4.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A=="], + + "hast-util-raw": ["hast-util-raw@9.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "hast-util-from-parse5": "^8.0.0", "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "parse5": "^8.1.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-8P0PLAr5C7xCRb+tkhUTV4v6OSNcnccKwjBkH/r19R5CkVCgTWlv4vmTkxFH1CVCA2UJOvOPQdBBMC3c6qnuOg=="], + + "hast-util-sanitize": ["hast-util-sanitize@5.0.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "unist-util-position": "^5.0.0" } }, "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg=="], + + "hast-util-to-html": ["hast-util-to-html@9.0.7", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-HYNDA3qdnzUPitY/LcQm1nWs8z0cWFNH1Nz09jdI/tXifAqF7h3+jrLl4S/b9Mi4VSjn0Dsn54ctuTV6zhBthA=="], + + "hast-util-to-parse5": ["hast-util-to-parse5@8.0.1", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA=="], + + "hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="], + + "hastscript": ["hastscript@9.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-parse-selector": "^4.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0" } }, "sha512-1ALZXSmCGmW3h8AMz4R4+QKSKFi7sNgXLVwmwB8FYVtl1CwQ3WDkSAEY/d5tp1g/vbQgq2s1WlHgfO3jbw1TsA=="], + + "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="], + "is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="], "is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="], @@ -130,16 +231,42 @@ "jose": ["jose@6.2.14", "", {}, "sha512-3JasLuki1NRLQvY4wCoC37KZk4qxoBx2k2aFqLxT84IezqW0bkJKnNtxnZj/Fu1xsQivoc/lytxaRHJoGLjJ1A=="], + "katex": ["katex@0.16.47", "", { "dependencies": { "commander": "^8.3.0" }, "bin": { "katex": "cli.js" } }, "sha512-Eeo8Ys1doU1z+x8AZsPpQu+p/QcZBI5PeOo7QGQdy2x2m0MU/hYagBbGOmXwr5KVbEfVuWv9LpnQWeehogurjg=="], + "longest-streak": ["longest-streak@3.1.0", "", {}, "sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g=="], + "lru_map": ["lru_map@0.4.1", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="], + + "markdown-table": ["markdown-table@3.1.0", "", {}, "sha512-xpeSCdM+B+6P3ncfgaB7FoDbtJ30xAe6Z18TGT7AgXJsHqCElCICZovQqdRMm7kHgpTyYv36EupqewoFFSB8vw=="], + "marked": ["marked@17.0.1", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg=="], "mdast-util-directive": ["mdast-util-directive@3.2.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.2.0", "micromark-util-character": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0" } }, "sha512-Yxq+hH4pBEmtaLIJyMVcNbtBiCIKzdOK3HvDeM+JAqC8XVAT1e5PUYbHBpwFvQLIJuJfO2zCu7aNUXWoyZLmhw=="], + "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.5", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-of3wZLEBWpK8mSYy8wmKnwyxfUKjhCkXxGLz45DVBqfcahTP37LscCK+0oAZh+ReZ5OunPDkB2zdGMIxrojLhw=="], + "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + "mdast-util-gfm": ["mdast-util-gfm@3.1.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-gfm-autolink-literal": "^2.0.0", "mdast-util-gfm-footnote": "^2.0.0", "mdast-util-gfm-strikethrough": "^2.0.0", "mdast-util-gfm-table": "^2.0.0", "mdast-util-gfm-task-list-item": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ=="], + + "mdast-util-gfm-autolink-literal": ["mdast-util-gfm-autolink-literal@2.1.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "ccount": "^2.0.0", "devlop": "^1.0.0", "mdast-util-find-and-replace": "^3.0.0", "micromark-util-character": "^2.0.0" } }, "sha512-rAlbZBGZfv2YRr6lSFGHTN305KkNawOYRRlbldFyPHnTlHJZwlGdzVwyIDvr3fxbhRbmJOSZc06c8H5Fgfu8Ng=="], + + "mdast-util-gfm-footnote": ["mdast-util-gfm-footnote@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0" } }, "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ=="], + + "mdast-util-gfm-strikethrough": ["mdast-util-gfm-strikethrough@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw=="], + + "mdast-util-gfm-table": ["mdast-util-gfm-table@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "markdown-table": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "mdast-util-to-string": "^4.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-fiIjPrAy4kz68/eFbPHhsiWDGHhqUSVoU1XsfLM5DsEPXw7MxgiVVyulUggFRckVWeT1KXQXkg5vm3kv4oMSOA=="], + + "mdast-util-gfm-task-list-item": ["mdast-util-gfm-task-list-item@2.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-jXVO1hvB2hs82g1esi7I9nIJDqiijbQLIyH2jDUb5s7jIAZMr/79h0VHSq7XHKTqpLARRm+DDNjduB7S9+6XZA=="], + + "mdast-util-math": ["mdast-util-math@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "longest-streak": "^3.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.1.0", "unist-util-remove-position": "^5.0.0" } }, "sha512-Tl9GBNeG/AhJnQM221bJR2HPvLOSnLE/T9cJI9tlc6zwQk2nPk/4f0cHkOdEixQPC/j8UtKDdITswvLAy1OZ1w=="], + + "mdast-util-newline-to-break": ["mdast-util-newline-to-break@2.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-find-and-replace": "^3.0.0" } }, "sha512-MbgeFca0hLYIEx/2zGsszCSEJJ1JSCdiY5xQxRcLDDGa8EPvlLPupJ4DSajbMPAnC0je8jfb9TiUATnxxrHUog=="], + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], + "mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="], + "mdast-util-to-markdown": ["mdast-util-to-markdown@2.2.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "longest-streak": "^3.0.0", "mdast-util-phrasing": "^4.0.0", "mdast-util-to-string": "^4.0.0", "micromark-util-character": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "unist-util-visit": "^5.0.0", "zwitch": "^2.0.0" } }, "sha512-ThatlCBxG2GE+mljhNSfZPv56d3QrGiRh97jjYgIk80IzS4uU6d7cHAaexCYSAmUCCcOs3grJ07kX3oTGsFUOw=="], "mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="], @@ -150,6 +277,22 @@ "micromark-extension-directive": ["micromark-extension-directive@4.0.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "parse-entities": "^4.0.0" } }, "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg=="], + "micromark-extension-gfm": ["micromark-extension-gfm@3.0.0", "", { "dependencies": { "micromark-extension-gfm-autolink-literal": "^2.0.0", "micromark-extension-gfm-footnote": "^2.0.0", "micromark-extension-gfm-strikethrough": "^2.0.0", "micromark-extension-gfm-table": "^2.0.0", "micromark-extension-gfm-tagfilter": "^2.0.0", "micromark-extension-gfm-task-list-item": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w=="], + + "micromark-extension-gfm-autolink-literal": ["micromark-extension-gfm-autolink-literal@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw=="], + + "micromark-extension-gfm-footnote": ["micromark-extension-gfm-footnote@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw=="], + + "micromark-extension-gfm-strikethrough": ["micromark-extension-gfm-strikethrough@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw=="], + + "micromark-extension-gfm-table": ["micromark-extension-gfm-table@2.1.2", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA=="], + + "micromark-extension-gfm-tagfilter": ["micromark-extension-gfm-tagfilter@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg=="], + + "micromark-extension-gfm-task-list-item": ["micromark-extension-gfm-task-list-item@2.1.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw=="], + + "micromark-extension-math": ["micromark-extension-math@3.1.0", "", { "dependencies": { "@types/katex": "^0.16.0", "devlop": "^1.0.0", "katex": "^0.16.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-lvEqd+fHjATVs+2v/8kg9i5Q0AP2k85H0WUOwpIVvUML8BapsMvh1XAogmQjOCsLpoKRCVQqEkQBB3NhVBcsOg=="], + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], @@ -188,30 +331,70 @@ "micromark-util-symbol": ["micromark-util-symbol@2.0.1", "", {}, "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q=="], - "micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + "micromark-util-types": ["micromark-util-types@2.0.2", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + "oniguruma-parser": ["oniguruma-parser@0.12.2", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="], + + "oniguruma-to-es": ["oniguruma-to-es@4.3.6", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="], + "parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="], + "parse5": ["parse5@8.1.1", "", { "dependencies": { "entities": "^9.0.0" } }, "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w=="], + + "preact": ["preact@11.0.0-beta.0", "", {}, "sha512-IcODoASASYwJ9kxz7+MJeiJhvLriwSb4y4mHIyxdgaRZp6kPUud7xytrk/6GZw8U3y6EFJaRb5wi9SrEK+8+lg=="], + + "preact-render-to-string": ["preact-render-to-string@6.6.5", "", { "peerDependencies": { "preact": ">=10 || >= 11.0.0-0" } }, "sha512-O6MHzYNIKYaiSX3bOw0gGZfEbOmlIDtDfWwN1JJdc/T3ihzRT6tGGSEWE088dWrEDGa1u7101q+6fzQnO9XCPA=="], + + "property-information": ["property-information@7.2.0", "", {}, "sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg=="], + "react": ["react@19.3.1", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="], "react-devtools-core": ["react-devtools-core@7.0.1", "", { "dependencies": { "shell-quote": "^1.6.1", "ws": "^7" } }, "sha512-C3yNvRHaizlpiASzy7b9vbnBGLrhvdhl1CbdU6EnZgxPNbai60szdLtl+VL76UNOt5bOoVTOz5rNWZxgGt+Gsw=="], + "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], + "react-reconciler": ["react-reconciler@0.33.0", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }, "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA=="], + "regex": ["regex@6.1.0", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="], + + "regex-recursion": ["regex-recursion@6.0.2", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="], + + "regex-utilities": ["regex-utilities@2.3.0", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="], + + "rehype-raw": ["rehype-raw@7.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="], + + "rehype-sanitize": ["rehype-sanitize@6.0.0", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-sanitize": "^5.0.0" } }, "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg=="], + + "remark-breaks": ["remark-breaks@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-newline-to-break": "^2.0.0", "unified": "^11.0.0" } }, "sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ=="], + + "remark-gfm": ["remark-gfm@4.0.1", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="], + + "remark-math": ["remark-math@6.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-math": "^3.0.0", "micromark-extension-math": "^3.0.0", "unified": "^11.0.0" } }, "sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA=="], + "remark-parse": ["remark-parse@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="], + "remark-rehype": ["remark-rehype@11.1.2", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "mdast-util-to-hast": "^13.0.0", "unified": "^11.0.0", "vfile": "^6.0.0" } }, "sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw=="], + + "remark-stringify": ["remark-stringify@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="], + "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], "shell-quote": ["shell-quote@1.12.0", "", {}, "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q=="], + "shiki": ["shiki@4.6.0", "", { "dependencies": { "@shikijs/core": "4.6.0", "@shikijs/engine-javascript": "4.6.0", "@shikijs/engine-oniguruma": "4.6.0", "@shikijs/langs": "4.6.0", "@shikijs/themes": "4.6.0", "@shikijs/types": "4.6.0", "@shikijs/vscode-textmate": "^10.1.0", "@types/hast": "^3.0.5" } }, "sha512-imjLsVHgPuWhvpU3P+zOekvMYqnel7QmKsFC4Sn0fCuAvaaalBsxwKEsrU8Ko5BdFnZA6Go/8a0RzahS634UgA=="], + + "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], + "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], "stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="], "strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="], + "trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="], + "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], @@ -222,6 +405,10 @@ "unist-util-is": ["unist-util-is@6.0.1", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g=="], + "unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="], + + "unist-util-remove-position": ["unist-util-remove-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-Hp5Kh3wLxv0PHj9m2yZhhLt58KzPtEYKQQ4yxfYFEO7EvHwzyDYnduhHnY1mDxoqr7VUwVuHXk9RXKIiYS1N8Q=="], + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], "unist-util-visit": ["unist-util-visit@5.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], @@ -230,20 +417,84 @@ "vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="], + "vfile-location": ["vfile-location@5.0.4", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile": "^6.0.0" } }, "sha512-vEvxatYZCIpNvzGk2UD+u4I/sZkSKoOsdRCbkOIsN73QpJbriJ1qvvBAL1PeI0y55Leoqf7pORbaSPpG/smmOg=="], + "vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="], + "web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="], + "web-tree-sitter": ["web-tree-sitter@0.25.10", "", { "peerDependencies": { "@types/emscripten": "^1.40.0" }, "optionalPeers": ["@types/emscripten"] }, "sha512-Y09sF44/13XvgVKgO2cNDw5rGk6s26MgoZPXLESvMXeefBf7i6/73eFurre0IsTW6E14Y0ArIzhUMmjoc7xyzA=="], "ws": ["ws@8.22.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g=="], + "yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="], + "zustand": ["zustand@5.0.11", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg=="], "zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="], + "@pierre/diffs/hast-util-to-html": ["hast-util-to-html@9.0.5", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="], + + "@pierre/trees/@pierre/theming": ["@pierre/theming@1.0.0", "", { "peerDependencies": { "@pierre/theme": "^1.1.0", "@shikijs/themes": "^3.0.0 || ^4.0.0", "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0", "shiki": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@pierre/theme", "@shikijs/themes", "react", "react-dom", "shiki"] }, "sha512-WsdrnhKfjeyXGDikZmN9pkpeZ5S/cl6EE72feiSc0tlynT1tMYqXqouhuv/foK+PY9OEnebOAVRQn3+rAstR8g=="], + "@types/node/undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + "generaltranslation/@noble/hashes": ["@noble/hashes@2.4.0", "", {}, "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="], + + "mdast-util-from-markdown/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-core-commonmark/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-directive/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-gfm/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-gfm-autolink-literal/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-gfm-footnote/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-gfm-strikethrough/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-gfm-table/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-gfm-tagfilter/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-gfm-task-list-item/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-extension-math/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-factory-destination/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-factory-label/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-factory-space/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-factory-title/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-factory-whitespace/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-util-character/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-util-classify-character/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-util-combine-extensions/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-util-edit-map/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-util-resolve-all/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + + "micromark-util-subtokenize/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], + "parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="], + "parse5/entities": ["entities@9.0.0", "", {}, "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg=="], + "react-devtools-core/ws": ["ws@7.5.13", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA=="], + + "react-dom/scheduler": ["scheduler@0.28.0", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="], + + "remark-parse/micromark-util-types": ["micromark-util-types@2.0.3", "", {}, "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg=="], } } diff --git a/docs/development.md b/docs/development.md index c874962..600280a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -10,7 +10,7 @@ Set `T3TUI_DEBUG=/path/to/log` to log thread subscriptions and snapshots. - It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `T3TUI_SERVER`). - On first run it mints its own bearer session with `t3 auth session issue --label t3tui`, scoped to `orchestration:read`, `orchestration:operate` (attachments and automations ride on it), `filesystem:read` (diffs), `source-control:write` (git actions), `terminal:read` and `terminal:operate` (terminals, stopping servers), `diagnostics:read` (usage totals) and `providers:manage` (reset credits), and stores it in `~/.config/t3tui/credentials.json` (mode 600). A stored credential missing any of these scopes is replaced with a new one. Revoke it any time with `t3 auth session revoke`. For a remote server, pass a token in `T3TUI_TOKEN`. -- It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (`v0.1.6-nightly.20261030.3917`). +- It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (commit `42c9107983`, v0.1.12-nightly). ## Following the web app @@ -29,6 +29,8 @@ bun install && bun run typecheck && bun test Type errors after a bump point at the protocol changes to adapt to. +Two patches ride along with a bump: upstream's `patches/effect@*.patch` is applied to the installed `effect` package through `patchedDependencies` in `package.json` (copy the current patch file into `patches/` when the effect version changes), and `tscPatches` in `scripts/link-vendor.ts` fixes the spots where classic `tsc` can't infer what upstream's Effect language service can — the vendored packages are copied into `node_modules/@t3tools` for this, so `vendor/` itself stays pristine. + ## Releasing Releases are standalone binaries built with `bun build --compile`, so users don't need Bun or a checkout. To cut one, bump `version` in `package.json`, commit, and push a matching tag: diff --git a/docs/reference.md b/docs/reference.md index 62ea0d3..d5074dc 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -101,7 +101,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code - **Sidebar:** the same sections as the app (Pinned, Active, Working, then Snoozed and Settled folded to a count) and the same status words: `Working 2m`, `Waiting`, `Approval`, `Input`, `Request`, `Limited`, `Failed`, `Done`. Threads that need you are bold. - **Conversation:** each finished turn's work folds into one line (`Worked for 3m 12s`), your messages sit in a raised block with a bar down the left, and a running turn shows its live step and `Working for 12s`. Replies render as markdown while they stream, tables included, and settle into their final form when done; at the bottom the newest line stays in view, and scrolled up the text you're reading stays put. Threads open scrolled to the bottom. Long threads load as a window of recent turns; press `o` for older ones. -- **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds the chat and returns the prompt to the message box, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. Stop a running turn first. Rewinding messages with attachments still needs the app. +- **Turns:** `[`/`]` select a turn and mark its prompt. `R` or `Revert to this turn` asks `Edit from here?`, then rewinds the chat and returns the prompt — and its attachments — to the message box, keeping file changes. `Revert files too` in the palette also restores files, including your own edits. `Fork from this turn` in the palette or the prompt's right-click menu copies the run into a new thread and opens it. Stop a running turn first. - **Command output:** expand work with `e` / `Expand all work`, or click a command. Output streams while its expanded row is in view; collapsing it, scrolling away or opening another thread stops it. - **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation. A strip of tabs at its top reads `Details · Files`, then a tab for each file open in an editor or a preview and each terminal placed at the side: click one, or press `ctrl+\` then its number. - **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes in place of the conversation: side by side when the conversation is at least 140 columns wide, unified otherwise. `Toggle split diff` in the palette switches between the two for the rest of the session. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged lines; press it again to collapse. Diffs of past checkpoints show only the changed lines. @@ -133,9 +133,11 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code - Rename, regenerate the title, mark unread - Auto-settle on or off for the thread (on servers that support turning it off) - Copy the workspace path, branch, thread link or thread ID +- Share with guest (a link, copied to the clipboard) when the server's Guest links beta is on +- Turn into project, for a scratch thread with its own folder on a server that allows it - Archive or delete -Submenus open as their own list, and typing finds their items from the top (`thread id` finds `Copy › Thread ID`). A custom snooze takes a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`). Delete asks first; it leaves the thread's worktree alone, so remove that from the app or with `b`. Copying goes through the terminal (OSC 52, so it works over SSH), and through `wl-copy`, `xclip` or `pbcopy` on a local desktop. Project settings and guest sharing are only in the app. +Submenus open as their own list, and typing finds their items from the top (`thread id` finds `Copy › Thread ID`). A custom snooze takes a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`). Delete asks first; it leaves the thread's worktree alone, so remove that from the app or with `b`. Copying goes through the terminal (OSC 52, so it works over SSH), and through `wl-copy`, `xclip` or `pbcopy` on a local desktop. Project settings are only in the app. ## New threads diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..1e4f700 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1795371335, + "narHash": "sha256-oa2P5WZer1A4wuhatl92JyHHEjrrOdIyuvTuI5LUi9Q=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "619c39f6eac5d1ed6b8f073a9414baf7034b2356", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..93b88e4 --- /dev/null +++ b/flake.nix @@ -0,0 +1,26 @@ +{ + description = "t3tui local development dependencies (bun)"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; + + outputs = + { nixpkgs, ... }: + let + systems = [ + "x86_64-linux" + "aarch64-linux" + "x86_64-darwin" + "aarch64-darwin" + ]; + forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f (import nixpkgs { inherit system; })); + in + { + devShells = forAllSystems (pkgs: { + default = pkgs.mkShell { + packages = [ + pkgs.bun + ]; + }; + }); + }; +} diff --git a/package.json b/package.json index 816e441..a7a8138 100644 --- a/package.json +++ b/package.json @@ -22,12 +22,34 @@ "dependencies": { "@opentui/core": "0.8.1", "@opentui/react": "0.8.1", + "@pierre/diffs": "1.7.0-beta.4", + "@pierre/trees": "1.0.0-beta.6", + "@pierre/words": "file:vendor/t3code/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", "diff": "9.0.0", - "effect": "4.0.5", + "effect": "4.1.5", + "entities": "^6.0.1", + "get-east-asian-width": "^1.6.0", + "gt-i18n": "1.0.40", + "gt-react": "11.4.18", + "hast-util-sanitize": "^5.0.2", + "hast-util-to-html": "^9.0.5", "mdast-util-directive": "^3.2.0", + "mdast-util-to-hast": "13.2.1", "micromark-extension-directive": "^4.0.0", + "micromark-util-character": "2.1.1", + "micromark-util-decode-string": "2.0.1", + "micromark-util-types": "2.0.2", + "property-information": "^7.2.0", "react": "^19.2.0", + "rehype-raw": "7.0.0", + "rehype-sanitize": "6.0.0", + "remark-breaks": "4.0.0", + "remark-gfm": "4.0.1", + "remark-math": "6.0.0", "remark-parse": "^11.0.0", + "remark-rehype": "11.1.2", + "unified": "11.0.5", + "yaml": "^2.9.0", "zustand": "5.0.11" }, "devDependencies": { @@ -37,5 +59,8 @@ "@types/react": "^19.3.0", "jose": "^6.2.14", "typescript": "^5.9.0" + }, + "patchedDependencies": { + "effect@4.1.5": "patches/effect@4.1.5.patch" } } diff --git a/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch new file mode 100644 index 0000000..e1b4bfd --- /dev/null +++ b/patches/effect@4.1.5.patch @@ -0,0 +1,4140 @@ +diff --git a/dist/ai/McpSchema.d.ts b/dist/ai/McpSchema.d.ts +index 8f86c27..aed42ae 100644 +--- a/dist/ai/McpSchema.d.ts ++++ b/dist/ai/McpSchema.d.ts +@@ -941,6 +941,52 @@ export declare const HEADER_MISMATCH_ERROR_CODE: -32020; + * @since 4.0.6 + */ + export declare const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: -32022; ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const NOT_FOUND_ERROR_CODE: -32023; ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const FORBIDDEN_ERROR_CODE: -32024; ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const RESOURCE_EXHAUSTED_ERROR_CODE: -32025; ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const UNSUPPORTED_ERROR_CODE: -32026; ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const CALLBACK_ENDPOINT_ERROR_CODE: -32027; + declare const ParseError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"NotFound">; ++ readonly code: Schema.tag<-32023>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class NotFound extends NotFound_base { ++} ++declare const Forbidden_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Forbidden">; ++ readonly code: Schema.tag<-32024>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Forbidden extends Forbidden_base { ++} ++declare const ResourceExhausted_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"ResourceExhausted">; ++ readonly code: Schema.tag<-32025>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class ResourceExhausted extends ResourceExhausted_base { ++} ++declare const Unsupported_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Unsupported">; ++ readonly code: Schema.tag<-32026>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Unsupported extends Unsupported_base { ++} ++declare const CallbackEndpointError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"CallbackEndpointError">; ++ readonly code: Schema.tag<-32027>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class CallbackEndpointError extends CallbackEndpointError_base { ++} + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1880,6 +2001,66 @@ declare const Skill_base: Schema.Class; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type; ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventDescriptor: Schema.Struct<{ ++ readonly name: Schema.String; ++ readonly description: Schema.decodeTo>, Schema.optionalKey, never, never>; ++ readonly delivery: Schema.$Array>; ++ readonly inputSchema: Schema.$Record; ++ readonly payloadSchema: Schema.$Record; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type; ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventOccurrence: Schema.Struct<{ ++ readonly eventId: Schema.String; ++ readonly name: Schema.String; ++ readonly timestamp: Schema.String; ++ readonly data: Schema.$Record; ++ readonly cursor: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type; + declare const PromptArgument_base: Schema.Opaque Effect.Effect Layer.Layer; ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const registerEvent: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Effect.Effect>; ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; ++declare const CallbackRejected_base: new = {}>(args: import("../Types.ts").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("../Cause.ts").YieldableError & { ++ readonly _tag: "CallbackRejected"; ++} & Readonly; ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class CallbackRejected extends CallbackRejected_base<{ ++ readonly message: string; ++}> { ++} ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const CallbackGuard: Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect; ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined; ++}>; ++declare const EventWebhooks_base: Context.ServiceClass; ++}>; ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class EventWebhooks extends EventWebhooks_base { ++} ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect; ++} ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const layerEventWebhooks: (options: EventWebhooksOptions) => Layer.Layer; + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js +index 4bf6bca..5ad258e 100644 +--- a/dist/ai/McpServer.js ++++ b/dist/ai/McpServer.js +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.js"; + import * as Clock from "../Clock.js"; + import * as Context from "../Context.js"; + import * as Digest from "../crypto/Digest.js"; ++import * as Mac from "../crypto/Mac.js"; ++import * as SecureRandom from "../crypto/SecureRandom.js"; + import * as Data from "../Data.js"; + import * as Deferred from "../Deferred.js"; + import * as Duration from "../Duration.js"; +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.js"; + import * as Fiber from "../Fiber.js"; + import * as FindMyWay from "../http/FindMyWay.js"; + import * as Headers from "../http/Headers.js"; ++import * as HttpClient from "../http/HttpClient.js"; + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.js"; + import * as HttpRouter from "../http/HttpRouter.js"; + import * as HttpServerRequest from "../http/HttpServerRequest.js"; +@@ -55,6 +58,7 @@ import * as McpCore from "./internal/mcpCore.js"; + import * as McpProtocolInternal from "./internal/mcpProtocol.js"; + import * as McpRuntime from "./internal/mcpRuntime.js"; + import * as McpSkills from "./internal/mcpSkills.js"; ++import * as McpWebhooks from "./internal/mcpWebhooks.js"; + import * as InternalStructuredOutput from "./internal/structured-output.js"; + import * as McpSchema from "./McpSchema.js"; + import { CallToolResult, ElicitationDeclined, EnabledWhen, GetPromptResult, InternalError, InvalidParams, InvalidRequest, isParam, McpRequestContext, McpServerClient, McpServerClientMiddleware, MethodNotFound, Prompt, Resource, ResourceTemplate, ServerNotificationRpcs, TextContent, Tool as McpTool, ToolJson } from "./McpSchema.js"; +@@ -413,6 +417,9 @@ const notFound = (method, target) => { + return new McpCore.SkillNotFound({ + uri: target + }); ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target); + } + }; + const isHidden = error => error instanceof Hidden; +@@ -2637,6 +2644,155 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) + * @since 4.1.1 + */ + export const skill = options => Layer.effectDiscard(registerSkill(options)); ++// ============================================================================= ++// Events ++// ============================================================================= ++const DEFAULT_NEXT_POLL_MS = 30_000; ++/** ++* Registers an event type under the MCP Events extension (SEP-3415). ++* ++* **Details** ++* ++* The server declares `io.modelcontextprotocol/events` on revision ++* `2026-07-28` once any event type is registered, and answers `events/list`, ++* `events/poll`, `events/stream`, and with {@link EventWebhooks} ++* `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its ++* lifetime inside the request's middleware, sends heartbeats carrying the ++* last cursor, and ends when the client goes away. Services read by `poll` ++* and `stream` are request-level, as for tools. ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const registerEvent = Effect.fnUntraced(function* (options) { ++ const { name, poll, stream } = options; ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)); ++ } ++ const registry = yield* McpServer; ++ const { core, globalMiddleware } = internalState.get(registry); ++ const services = yield* Effect.context(); ++ const annotations = options.annotations ?? Context.empty(); ++ const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))); ++ const parameters = options.parameters ?? Schema.Struct({}); ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); ++ const argumentsOf = (args) => decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))); ++ const encodeEvent = (event) => encodePayload(event.data).pipe(Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), Effect.map((data) => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` }))); ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll"]), ++ ...(stream === undefined ? [] : ["push"]), ++ ...(webhooks === undefined ? [] : ["webhook"]) ++ ], ++ inputSchema: toolJsonSchema(parameters, false), ++ payloadSchema: toolJsonSchema(options.payload, false), ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, ++ poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }); ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ }; ++ }), invocation, { method: "events/poll", target: name, payload: request }), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { ++ const args = request.decoded !== undefined ? request.decoded.value : yield* argumentsOf(request.arguments); ++ const subscription = yield* stream(args, { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }); ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context(); ++ const items = subscription.items.pipe(Stream.mapEffect((item) => item._tag === "Event" ++ ? encodeEvent(item).pipe(Effect.map((event) => ({ ...event, _tag: "Event", cursor: item.cursor })), Effect.catch((error) => Effect.succeed({ _tag: "Error", error }))) ++ : Effect.succeed(item)), Stream.provideContext(context)); ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }); ++ })), invocation, { method: "events/stream", target: name, payload: request }) ++ }); ++}); ++/** ++* Creates a layer that registers an event type under the MCP Events ++* extension (SEP-3415). ++* ++* @see {@link registerEvent} for the Effect-level event registration API ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const event = (options) => Layer.effectDiscard(registerEvent(options)); ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends /*#__PURE__*/Data.TaggedError("CallbackRejected") {} ++/** ++ * Decides which webhook callback URLs may be reached. The default refuses ++ * every URL; see the source for the contract a platform guard keeps. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = /*#__PURE__*/Context.Reference("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}); ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends /*#__PURE__*/Context.Service()("effect/ai/McpServer/EventWebhooks") {} ++const webhooksState = /*#__PURE__*/new WeakMap(); ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = (options) => Layer.effect(EventWebhooks, Effect.gen(function* () { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }); ++ const service = EventWebhooks.of({ size: webhooks.size }); ++ webhooksState.set(service, webhooks); ++ return service; ++}).pipe(Effect.provide(Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto))))); + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/internal/mcpCore.js b/dist/ai/internal/mcpCore.js +index 4c416a8..50d2d34 100644 +--- a/dist/ai/internal/mcpCore.js ++++ b/dist/ai/internal/mcpCore.js +@@ -75,6 +75,15 @@ export const ClientNotification = /*#__PURE__*/Data.taggedEnum(); + * @internal + */ + export const ServerNotification = /*#__PURE__*/Data.taggedEnum(); ++/** ++ * @internal ++ */ ++export const eventNotFound = name => new McpSchema.NotFound({ ++ message: `Event '${name}' not found`, ++ data: { ++ kind: "event" ++ } ++}); + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a, b) => { + const rootA = a.slice(0, -"/SKILL.md".length); +@@ -90,6 +99,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + const resourceTemplateRegistrations = []; + const promptRegistrations = new Map(); + const skillRegistrations = new Map(); ++ const eventRegistrations = new Map(); + const skillFiles = new Set(); + const completionRegistrations = new Map(); + const filterList = (registrations, invocation) => Effect.map(Effect.filter(Arr.filter(registrations, entry => entry.isVisible(invocation.protocol)), entry => entry.visible === undefined ? Effect.succeed(true) : entry.visible(invocation)), entries => entries.map(entry => entry.descriptor)); +@@ -234,11 +244,22 @@ export const make = /*#__PURE__*/Effect.sync(() => { + return Array.from(children.values()).sort((a, b) => a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0); + }) + }; ++ const events = { ++ register: registration => Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration); ++ }), ++ list: invocation => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => Effect.suspend(() => { ++ const registration = eventRegistrations.get(name); ++ return registration !== undefined && registration.isVisible(invocation.protocol) ? Effect.succeed(registration) : Effect.fail(eventNotFound(name)); ++ }) ++ }; + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })); + return { + tools, +@@ -246,6 +267,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + prompts, + completions, + skills, ++ events, + registrationPresence + }; + }); +diff --git a/dist/ai/internal/mcpEvents.d.ts b/dist/ai/internal/mcpEvents.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpEvents.js b/dist/ai/internal/mcpEvents.js +new file mode 100644 +index 0000000..d875046 +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.js +@@ -0,0 +1,265 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.js"; ++import * as Clock from "../../Clock.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Option from "../../Option.js"; ++import * as Queue from "../../Queue.js"; ++import * as Result from "../../Result.js"; ++import * as Rpc from "../../rpc/Rpc.js"; ++import * as RpcGroup from "../../rpc/RpcGroup.js"; ++import * as Schema from "../../Schema.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import * as McpProtocol from "./mcpProtocol.js"; ++import * as Stateless from "./mcpSchema/v2026_07_28.js"; ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events"; ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = (extensions, servesEvents) => servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions; ++const methodNotFound = (method) => new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++}); ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core, method) => Effect.flatMap(core.registrationPresence, (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method))); ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value) => new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++}); ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++const optional = Stateless.optional; ++const Cursor = Schema.NullOr(Schema.String); ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest(Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) { ++} ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++}; ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++}), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) { ++} ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make(EventsActiveNotification, EventsEventNotification, EventsHeartbeatNotification, EventsErrorNotification, EventsTerminatedNotification) { ++} ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++const DEFAULT_HEARTBEAT_MS = 30_000; ++const MIN_HEARTBEAT_MS = 1_000; ++const MAX_HEARTBEAT_MS = 300_000; ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16; ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested) => Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)); ++const isJson = Schema.is(Schema.Json); ++/** ++ * @internal ++ */ ++export const wireError = (failure) => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}); ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function* (options) { ++ const { heartbeatMs, name, subscription } = options; ++ let cursor = subscription.cursor; ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0; ++ const send = (tag, payload) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at; ++ })); ++ const active = (truncated) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }); ++ yield* active(subscription.truncated); ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }); ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)); ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result); ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }); ++ } ++ return; ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }); ++ continue; ++ } ++ const item = next.success.value; ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor; ++ const { _meta, _tag, ...occurrence } = item; ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }); ++ break; ++ } ++ case "Position": { ++ cursor = item.cursor; ++ break; ++ } ++ case "Gap": { ++ cursor = item.cursor; ++ yield* active(true); ++ break; ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }); ++ break; ++ } ++ } ++ } ++}, Effect.scoped); +diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js +index af1ceed..ea29279 100644 +--- a/dist/ai/internal/mcpProtocol/v2026_07_28.js ++++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js +@@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; + import * as Scope from "../../../Scope.js"; + import * as PublicMcpSchema from "../../McpSchema.js"; + import * as McpCore from "../mcpCore.js"; ++import * as McpEvents from "../mcpEvents.js"; + import * as McpProtocol from "../mcpProtocol.js"; + import * as McpSchema from "../mcpSchema/v2026_07_28.js"; + import * as McpSkills from "../mcpSkills.js"; +@@ -242,7 +243,7 @@ const unsupported = operation => new PublicMcpSchema.McpReverseOperationUnsuppor + /** + * @internal + */ +-export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs); ++export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs, McpEvents.StatelessRpcs); + /** + * @internal + */ +@@ -260,6 +261,10 @@ export const makeHandlers = (core, _lifecycle, context) => { + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema); ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema); + const sendNotification = context.sendNotification; + const supportsSubscriptions = sendNotification !== undefined; + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -277,8 +282,11 @@ export const makeHandlers = (core, _lifecycle, context) => { + completions: {}, + logging: {} + }; +- const declared = McpSkills.declareExtension(extensions, presence.skills); ++ const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); + if (declared !== undefined) capabilities.extensions = declared; ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {}; + if (presence.tools) capabilities.tools = { + listChanged: supportsSubscriptions + }; +@@ -297,6 +305,26 @@ export const makeHandlers = (core, _lifecycle, context) => { + serverInfo: context.serverInfo + }; + }); ++ const requireEvents = (method) => McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))); ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function* (registration, args) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest); ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); ++ } ++ }); ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function* (method, name, args) { ++ yield* requireEvents(method); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(name, invocation); ++ const { stream, webhooks } = registration; ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ } ++ yield* validateEventHeaders(registration, args); ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments }; ++ }); + const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); + const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); + const getInputInvocation = Effect.fnUntraced(function* (request) { +@@ -592,6 +620,97 @@ export const makeHandlers = (core, _lifecycle, context) => { + }, context.serverInfo); + return yield* decodeReadResourceDirectoryResult(result); + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/list"); ++ yield* McpProtocol.rejectCursor(request.cursor); ++ const events = yield* core.events.list(yield* getInvocation); ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push"); ++ return delivery.length === 0 ? [] : [{ ...event, delivery }]; ++ }); ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo); ++ return yield* decodeListEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/poll"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation); ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ })), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo); ++ return yield* decodePollEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function* (request, { client, requestId }) { ++ yield* requireEvents("events/stream"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId }; ++ const send = (tag, payload) => sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }); ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs); ++ yield* Effect.raceFirst(registration.stream({ arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, invocation, (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send })), context.awaitClientEnd ?? Effect.never); ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo); ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }); ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function* (request) { ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration("events/subscribe", request.name, request.arguments); ++ const args = request.arguments ?? {}; ++ const cursor = request.cursor ?? null; ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => stream({ arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, invocation, deliver) ++ }); ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo); ++ return yield* decodeSubscribeEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function* (request) { ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments); ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }); ++ const result = yield* projectCompleteResult({}, context.serverInfo); ++ return yield* decodeUnsubscribeEventsResult(result); ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function* (_request) { + return yield* Effect.void; + }) +@@ -613,10 +732,10 @@ const runtime = { + export const protocol = /*#__PURE__*/McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: /*#__PURE__*/McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js +index 88238ff..721ff28 100644 +--- a/dist/ai/internal/mcpRuntime.js ++++ b/dist/ai/internal/mcpRuntime.js +@@ -39,6 +39,10 @@ const routingNameKey = method => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name"; + case "resources/read": + return "uri"; +@@ -178,7 +182,10 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey]; + const header = headers[MCP_NAME_HEADER]; +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe"); ++ if (!optional && (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name)) { + return headerMismatch("Mcp-Name header does not match request parameters"); + } + } +@@ -340,7 +347,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && (input.method === "subscriptions/listen" || input.method === "events/stream") + }; + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/dist/ai/internal/mcpWebhooks.d.ts b/dist/ai/internal/mcpWebhooks.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpWebhooks.js b/dist/ai/internal/mcpWebhooks.js +new file mode 100644 +index 0000000..4e2871a +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.js +@@ -0,0 +1,456 @@ ++import * as Clock from "../../Clock.js"; ++import * as Digest from "../../crypto/Digest.js"; ++import * as Mac from "../../crypto/Mac.js"; ++import * as SecureRandom from "../../crypto/SecureRandom.js"; ++import * as Deferred from "../../Deferred.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Base64 from "../../encoding/Base64.js"; ++import * as Base64Url from "../../encoding/Base64Url.js"; ++import * as Fiber from "../../Fiber.js"; ++import * as FetchHttpClient from "../../http/FetchHttpClient.js"; ++import * as HttpClient from "../../http/HttpClient.js"; ++import * as HttpClientRequest from "../../http/HttpClientRequest.js"; ++import * as Option from "../../Option.js"; ++import * as Result from "../../Result.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import { wireError } from "./mcpEvents.js"; ++const MINUTE_MS = 6e4; ++const MIN_TTL_MS = MINUTE_MS; ++const MAX_TTL_MS = 60 * MINUTE_MS; ++const DEFAULT_TTL_MS = 15 * MINUTE_MS; ++const MAX_ATTEMPTS = 5; ++const FIRST_RETRY_MS = 3e4; ++const REQUEST_TIMEOUT_MS = 1e4; ++const ROTATION_GRACE_MS = 5 * MINUTE_MS; ++const VERIFIED_FOR_MS = MAX_TTL_MS; ++const FAILED_FOR_MS = 5 * MINUTE_MS; ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10; ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100; ++const MAX_CHALLENGE_RESPONSE_BYTES = 8192; ++const SECRET_PREFIX = "whsec_"; ++const invalid = (message) => new PublicMcpSchema.InvalidParams({ message }); ++const grantTtl = (suggested) => suggested === void 0 ? DEFAULT_TTL_MS : suggested === null ? MAX_TTL_MS : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)); ++const canonicalJson = (value) => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0); ++ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; ++ } ++ return JSON.stringify(value) ?? "null"; ++}; ++const encoder = new TextEncoder(); ++const parseUrl = (value, guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")); ++ let url; ++ try { ++ url = new URL(value); ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")); ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")); ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")); ++ } ++ url.hash = ""; ++ return Effect.succeed(url); ++}; ++const parseSecret = (value) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")); ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail; ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)); ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail; ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))); ++}; ++const statusCategory = (status) => status >= 500 ? "http_5xx" : "http_4xx"; ++const transportCategory = (error) => { ++ let current = error; ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = current.code; ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error"; ++ current = current.cause ?? current.reason; ++ } ++ return "connection_refused"; ++}; ++const readCapped = (response) => Effect.suspend(() => { ++ const chunks = []; ++ let total = 0; ++ let oversized = false; ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true; ++ return false; ++ } ++ total += chunk.length; ++ chunks.push(chunk); ++ return true; ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return void 0; ++ const bytes = new Uint8Array(total); ++ let offset = 0; ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset); ++ offset += chunk.length; ++ } ++ return new TextDecoder().decode(bytes); ++ }) ++ ); ++}); ++const echoedChallenge = (body) => { ++ try { ++ const parsed = JSON.parse(body); ++ const challenge = typeof parsed === "object" && parsed !== null ? parsed.challenge : void 0; ++ return typeof challenge === "string" ? challenge : void 0; ++ } catch { ++ return void 0; ++ } ++}; ++const callbackError = (category) => new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++}); ++const iso = (millis) => new Date(millis).toISOString(); ++const make = Effect.fnUntraced(function* (options) { ++ const scope = yield* Effect.scope; ++ const mac = yield* Mac.Mac; ++ const digest = yield* Digest.Digest; ++ const random = yield* SecureRandom.SecureRandom; ++ const { guard } = options; ++ const client = HttpClient.withScope(options.client); ++ const subscriptions = /* @__PURE__ */ new Map(); ++ const pending = /* @__PURE__ */ new Map(); ++ const verified = /* @__PURE__ */ new Map(); ++ const failedVerifications = /* @__PURE__ */ new Map(); ++ const verifying = /* @__PURE__ */ new Map(); ++ const verificationsByHost = /* @__PURE__ */ new Map(); ++ const forget = (subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id); ++ }; ++ const subscriptionId = (principal, url, name, args) => digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ); ++ const messageId = (prefix) => Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`); ++ const deliveryId = (subscription, eventId) => Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ); ++ const MAX_CURSORS_SINCE_GAP = 1024; ++ const advance = (subscription, cursor) => { ++ subscription.watermark = cursor; ++ const since = subscription.cursorsSinceGap; ++ if (since === void 0) return; ++ since.add(cursor); ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value); ++ }; ++ const sign = (keys, webhookId, timestamp, body) => Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ); ++ const send = Effect.fnUntraced(function* (subscription, body, webhookId, readBody) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)); ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true }; ++ } ++ const now = yield* Clock.currentTimeMillis; ++ const timestamp = Math.floor(now / 1e3); ++ const previous = subscription.previous; ++ const keys = previous !== void 0 && now < previous.until ? [subscription.key, previous.key] : [subscription.key]; ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ); ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response) => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }); ++ } ++ return readBody ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) : Effect.succeed({ _tag: "Delivered", body: void 0 }); ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch( ++ (error) => Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ); ++ return Option.getOrElse(outcome, () => ({ _tag: "Failed", category: "timeout", retryable: true })); ++ }); ++ const deliver = Effect.fnUntraced(function* (subscription, body, webhookId) { ++ for (let attempt = 1; ; attempt++) { ++ const current = subscriptions.get(subscription.id); ++ if (current !== void 0 && current !== subscription) return false; ++ const startedAt = yield* Clock.currentTimeMillis; ++ const outcome = yield* send(subscription, body, webhookId, false); ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis; ++ subscription.lastError = void 0; ++ return true; ++ } ++ subscription.lastError = outcome.category; ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false; ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis); ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)); ++ } ++ }); ++ const control = (subscription, type, fields) => Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ); ++ const run = (subscription, name, events) => events.items.pipe( ++ Stream.runForEach((item) => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...item._meta === void 0 ? {} : { _meta: item._meta } ++ }); ++ return deliver(subscription, body, webhookId); ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))); ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)); ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = /* @__PURE__ */ new Set(); ++ advance(subscription, item.cursor); ++ }) ++ ); ++ case "Error": ++ return Effect.void; ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch( ++ (failure) => Effect.suspend(() => { ++ forget(subscription); ++ return control(subscription, "terminated", { error: wireError(failure) }); ++ }) ++ ) ++ ); ++ const expiry = (subscription) => Effect.gen(function* () { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis); ++ if (left <= 0) return forget(subscription); ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)); ++ } ++ }); ++ const handshake = Effect.fnUntraced(function* (subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)); ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ); ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category); ++ const echoed = outcome.body === void 0 ? void 0 : echoedChallenge(outcome.body); ++ if (echoed === void 0 || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed"); ++ } ++ }); ++ const verify = Effect.fnUntraced(function* (subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]); ++ const now = yield* Clock.currentTimeMillis; ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry); ++ for (const [entry, failure2] of failedVerifications) if (failure2.until <= now) failedVerifications.delete(entry); ++ if (verified.has(key)) return; ++ const failure = failedVerifications.get(key); ++ if (failure !== void 0) return yield* callbackError(failure.category); ++ const inFlight = verifying.get(key); ++ if (inFlight !== void 0) return yield* Deferred.await(inFlight); ++ const host = subscription.url.hostname; ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS); ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent); ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }); ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry); ++ } ++ verificationsByHost.set(host, [...recent, now]); ++ const done = Deferred.makeUnsafe(); ++ verifying.set(key, done); ++ return yield* handshake(subscription).pipe( ++ Effect.tap( ++ () => Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS); ++ }) ++ ), ++ Effect.tapError( ++ (category) => Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }); ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit( ++ (exit) => Effect.sync(() => { ++ verifying.delete(key); ++ Deferred.doneUnsafe(done, exit); ++ }) ++ ) ++ ); ++ }); ++ const refresh = Effect.fnUntraced(function* (request, subscription, secret, expiresAt, now) { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted); ++ const start = yield* Deferred.await(subscription.accepted); ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request); ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS }; ++ subscription.secret = secret.text; ++ subscription.key = secret.key; ++ } ++ subscription.expiresAt = expiresAt; ++ const moved = subscription.deadlineMoved; ++ subscription.deadlineMoved = Deferred.makeUnsafe(); ++ Deferred.doneUnsafe(moved, Effect.void); ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start }; ++ const since = subscription.cursorsSinceGap; ++ if (since !== void 0 && since.has(request.cursor)) subscription.cursorsSinceGap = void 0; ++ const truncated = subscription.cursorsSinceGap !== void 0; ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === void 0 ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ }; ++ }); ++ const subscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const mode = request.delivery.mode; ++ if (mode !== void 0 && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'"); ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const secret = yield* parseSecret(request.delivery.secret); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const now = yield* Clock.currentTimeMillis; ++ const expiresAt = now + grantTtl(request.ttlMs); ++ const live = subscriptions.get(id); ++ if (live !== void 0) return yield* refresh(request, live, secret, expiresAt, now); ++ let held = pending.get(principal) ?? 0; ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++; ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }); ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1); ++ let reserved = true; ++ const release = () => { ++ if (!reserved) return; ++ reserved = false; ++ const left = (pending.get(principal) ?? 1) - 1; ++ if (left === 0) pending.delete(principal); ++ else pending.set(principal, left); ++ }; ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ); ++ }); ++ const create = Effect.fnUntraced(function* (request, { expiresAt, id, now, principal, release, secret, url }) { ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")); ++ const subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: void 0, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: void 0, ++ lastError: void 0, ++ fiber: void 0, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: void 0 ++ }; ++ const decoded = yield* request.decode; ++ yield* verify(subscription); ++ const raced = subscriptions.get(id); ++ if (raced !== void 0) { ++ release(); ++ return yield* refresh(request, raced, secret, expiresAt, now); ++ } ++ release(); ++ subscriptions.set(id, subscription); ++ const { accepted } = subscription; ++ const lifetime = request.open( ++ decoded, ++ (events) => Effect.suspend(() => { ++ subscription.watermark = events.cursor; ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }); ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription); ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })); ++ })) ++ ); ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope); ++ const start = yield* Deferred.await(accepted); ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated }; ++ }); ++ const unsubscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const subscription = subscriptions.get(id); ++ if (subscription === void 0) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }); ++ } ++ subscriptions.delete(id); ++ if (subscription.fiber !== void 0) yield* Fiber.interrupt(subscription.fiber); ++ }); ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ }; ++}); ++export { ++ DEFAULT_TTL_MS, ++ MAX_ATTEMPTS, ++ MAX_TTL_MS, ++ MIN_TTL_MS, ++ canonicalJson, ++ grantTtl, ++ make ++}; +diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts +index ba6c830..1e58fb9 100644 +--- a/src/ai/McpSchema.ts ++++ b/src/ai/McpSchema.ts +@@ -740,6 +740,57 @@ export const HEADER_MISMATCH_ERROR_CODE = -32020 as const + */ + export const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE = -32022 as const + ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const NOT_FOUND_ERROR_CODE = -32023 as const ++ ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const FORBIDDEN_ERROR_CODE = -32024 as const ++ ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const RESOURCE_EXHAUSTED_ERROR_CODE = -32025 as const ++ ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const UNSUPPORTED_ERROR_CODE = -32026 as const ++ ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const CALLBACK_ENDPOINT_ERROR_CODE = -32027 as const ++ + /** + * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed. + * +@@ -852,6 +903,74 @@ export class InternalError extends Schema.Error("effect/ai/McpSch + static readonly notImplemented = new InternalError({ message: "Not implemented" }) + } + ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class NotFound extends Schema.Error("effect/ai/McpSchema/NotFound")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("NotFound"), ++ code: Schema.tag(NOT_FOUND_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Forbidden extends Schema.Error("effect/ai/McpSchema/Forbidden")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Forbidden"), ++ code: Schema.tag(FORBIDDEN_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class ResourceExhausted extends Schema.Error("effect/ai/McpSchema/ResourceExhausted")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("ResourceExhausted"), ++ code: Schema.tag(RESOURCE_EXHAUSTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Unsupported extends Schema.Error("effect/ai/McpSchema/Unsupported")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Unsupported"), ++ code: Schema.tag(UNSUPPORTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or ++ * could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class CallbackEndpointError ++ extends Schema.Error("effect/ai/McpSchema/CallbackEndpointError")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("CallbackEndpointError"), ++ code: Schema.tag(CALLBACK_ENDPOINT_ERROR_CODE) ++ }) ++{} ++ + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1501,6 +1620,76 @@ export class Skill extends Schema.Class( + _meta: optional(UnknownObject) + }) {} + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * How a client receives an event type's occurrences under the MCP Events ++ * extension (SEP-3415): by `events/poll`, an `events/stream` push stream, or ++ * a webhook registered with `events/subscribe`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDelivery = Schema.Literals(["poll", "push", "webhook"]) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type ++ ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDescriptor = Schema.Struct({ ++ name: Schema.String, ++ description: optional(Schema.String), ++ delivery: Schema.Array(EventDelivery), ++ inputSchema: UnknownObject, ++ payloadSchema: UnknownObject, ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type ++ ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventOccurrence = Schema.Struct({ ++ eventId: Schema.String, ++ name: Schema.String, ++ timestamp: Schema.String, ++ data: UnknownObject, ++ cursor: optional(Schema.NullOr(Schema.String)), ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type ++ + // ============================================================================= + // Prompts + // ============================================================================= +diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts +index 4c2e191..bedd064 100644 +--- a/src/ai/McpServer.ts ++++ b/src/ai/McpServer.ts +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.ts" + import * as Clock from "../Clock.ts" + import * as Context from "../Context.ts" + import * as Digest from "../crypto/Digest.ts" ++import * as Mac from "../crypto/Mac.ts" ++import * as SecureRandom from "../crypto/SecureRandom.ts" + import * as Data from "../Data.ts" + import * as Deferred from "../Deferred.ts" + import * as Duration from "../Duration.ts" +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.ts" + import * as Fiber from "../Fiber.ts" + import * as FindMyWay from "../http/FindMyWay.ts" + import * as Headers from "../http/Headers.ts" ++import * as HttpClient from "../http/HttpClient.ts" + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.ts" + import * as HttpRouter from "../http/HttpRouter.ts" + import * as HttpServerRequest from "../http/HttpServerRequest.ts" +@@ -59,6 +62,7 @@ import * as McpCore from "./internal/mcpCore.ts" + import * as McpProtocolInternal from "./internal/mcpProtocol.ts" + import * as McpRuntime from "./internal/mcpRuntime.ts" + import * as McpSkills from "./internal/mcpSkills.ts" ++import * as McpWebhooks from "./internal/mcpWebhooks.ts" + import * as InternalStructuredOutput from "./internal/structured-output.ts" + import type * as McpProtocol from "./McpProtocol.ts" + import * as McpSchema from "./McpSchema.ts" +@@ -344,6 +348,9 @@ export type MiddlewareMethod = + | "skills/list" + | "skills/get" + | "resources/directory/read" ++ | "events/list" ++ | "events/poll" ++ | "events/stream" + + /** + * Request metadata passed to MCP middleware. +@@ -819,7 +826,14 @@ const internalError = new InternalError({ message: "Internal error" }) + const rejectWith = (error: McpErrorBase) => + Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) + +-type CallMethod = "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "skills/get" ++type CallMethod = ++ | "tools/call" ++ | "resources/read" ++ | "prompts/get" ++ | "completion/complete" ++ | "skills/get" ++ | "events/poll" ++ | "events/stream" + + type ListMethod = Exclude + +@@ -829,6 +843,8 @@ interface NotFoundErrors { + readonly "prompts/get": McpCore.PromptNotFound + readonly "completion/complete": InvalidParams + readonly "skills/get": McpCore.SkillNotFound ++ readonly "events/poll": McpSchema.NotFound ++ readonly "events/stream": McpSchema.NotFound + } + + const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { +@@ -843,6 +859,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod + return new InvalidParams({ message: "Unknown completion reference or argument" }) + case "skills/get": + return new McpCore.SkillNotFound({ uri: target }) ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target) + } + } + +@@ -4134,6 +4153,404 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect => + Layer.effectDiscard(registerSkill(options)) + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++const DEFAULT_NEXT_POLL_MS = 30_000 ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll`, `events/stream`, and with {@link EventWebhooks} ++ * `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const registerEvent: < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions) => Effect.Effect> = ++ Effect.fnUntraced(function*(options: EventOptions, Schema.Codec, any>) { ++ const { name, poll, stream } = options ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)) ++ } ++ const registry = yield* McpServer ++ const { core, globalMiddleware } = internalState.get(registry)! ++ const services = yield* Effect.context() ++ const annotations = options.annotations ?? Context.empty() ++ const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))) ++ const parameters = options.parameters ?? Schema.Struct({}) ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) ++ const argumentsOf = (args: unknown) => ++ decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))) ++ const encodeEvent = (event: EventOccurrence) => ++ encodePayload(event.data).pipe( ++ Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), ++ Effect.map((data): McpCore.EncodedEvent => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), ++ Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` })) ++ ) ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll" as const]), ++ ...(stream === undefined ? [] : ["push" as const]), ++ ...(webhooks === undefined ? [] : ["webhook" as const]) ++ ], ++ inputSchema: toolJsonSchema(parameters, false) as Record, ++ payloadSchema: toolJsonSchema(options.payload, false) as Record, ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, ++ poll: poll === undefined ? undefined : (request, invocation) => ++ invoke( ++ Effect.gen(function*() { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }) ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ } ++ }), ++ invocation, ++ { method: "events/poll", target: name, payload: request } ++ ), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => ++ invoke( ++ Effect.scoped(Effect.gen(function*() { ++ const args = request.decoded !== undefined ++ ? request.decoded.value ++ : yield* argumentsOf(request.arguments) ++ const subscription = yield* stream(args, { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }) ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context() ++ const items = subscription.items.pipe( ++ Stream.mapEffect((item): Effect.Effect => ++ item._tag === "Event" ++ ? encodeEvent(item).pipe( ++ Effect.map((event) => ({ ...event, _tag: "Event" as const, cursor: item.cursor })), ++ Effect.catch((error) => Effect.succeed({ _tag: "Error" as const, error })) ++ ) ++ : Effect.succeed(item) ++ ), ++ Stream.provideContext(context) ++ ) ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }) ++ })), ++ invocation, ++ { method: "events/stream", target: name, payload: request } ++ ) ++ }) ++ }) as any ++ ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const event = < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions): Layer.Layer> => ++ Layer.effectDiscard(registerEvent(options)) ++ ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends Data.TaggedError("CallbackRejected")<{ ++ readonly message: string ++}> {} ++ ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++}>("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}) ++ ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends Context.Service ++}>()("effect/ai/McpServer/EventWebhooks") {} ++ ++const webhooksState = new WeakMap() ++ ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect ++} ++ ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = ( ++ options: EventWebhooksOptions ++): Layer.Layer => ++ Layer.effect( ++ EventWebhooks, ++ Effect.gen(function*() { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }) ++ const service = EventWebhooks.of({ size: webhooks.size }) ++ webhooksState.set(service, webhooks) ++ return service ++ }).pipe( ++ Effect.provide( ++ Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe( ++ Layer.provideMerge(SecureRandom.layerWebCrypto) ++ ) ++ ) ++ ) ++ ) ++ + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts +index 643982d..d705160 100644 +--- a/src/ai/internal/mcpCore.ts ++++ b/src/ai/internal/mcpCore.ts +@@ -8,6 +8,8 @@ import * as Data from "../../Data.ts" + import * as Effect from "../../Effect.ts" + import type * as McpProtocol from "../McpProtocol.ts" + import * as McpSchema from "../McpSchema.ts" ++import type * as Stream from "../../Stream.ts" ++import type * as McpWebhooks from "./mcpWebhooks.ts" + + /** + * @internal +@@ -330,6 +332,123 @@ export interface SkillRegistration { + readonly directory: (uri: string) => ReadonlyArray | undefined + } + ++/** ++ * A failure an event handler reports to the client as a JSON-RPC error, such ++ * as `McpSchema.Forbidden` or `McpSchema.InvalidParams`. ++ * ++ * @internal ++ */ ++export interface EventFailure { ++ readonly code: number ++ readonly message: string ++ readonly data?: unknown ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * An occurrence with its payload already encoded for the wire. ++ * ++ * @internal ++ */ ++export interface EncodedEvent { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: Readonly> ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollOutcome { ++ readonly events: ReadonlyArray ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly hasMore: boolean ++ readonly nextPollMs: number ++} ++ ++/** ++ * @internal ++ */ ++export interface EventStreamRequest { ++ readonly arguments: Readonly> ++ // Set when the arguments were already decoded, as a webhook subscribe does first. ++ readonly decoded?: { readonly value: unknown } | undefined ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries after `notifications/events/active`: occurrences, ++ * a position checked without a match (carried by the next heartbeat), a gap ++ * (a fresh `active` with `truncated`), or a recoverable error. ++ * ++ * @internal ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EncodedEvent) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventFailure } ++ ++/** ++ * A push subscription the handler accepted. A failure of `items` ends it with ++ * `notifications/events/terminated`. ++ * ++ * @internal ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly items: Stream.Stream ++} ++ ++/** ++ * @internal ++ */ ++export interface EventRegistration { ++ readonly descriptor: McpSchema.EventDescriptor ++ readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean ++ readonly visible?: Visible | undefined ++ // Set when webhook delivery is offered, which runs `stream`. ++ readonly webhooks?: McpWebhooks.Webhooks | undefined ++ readonly decodeArguments: (args: unknown) => Effect.Effect ++ readonly poll?: ++ | (( ++ request: EventPollRequest, ++ invocation: McpInvocation ++ ) => Effect.Effect) ++ | undefined ++ // Runs for the subscription's lifetime: `deliver` takes over once the ++ // handler accepts it, so a failure before that is the request's error. ++ readonly stream?: ++ | (( ++ request: EventStreamRequest, ++ invocation: McpInvocation, ++ deliver: (subscription: EventSubscription) => Effect.Effect ++ ) => Effect.Effect) ++ | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Events { ++ readonly register: (registration: EventRegistration) => Effect.Effect ++ readonly list: (invocation: McpInvocation) => Effect.Effect, RequestRejected> ++ readonly get: (name: string, invocation: McpInvocation) => Effect.Effect ++} ++ + /** + * @internal + */ +@@ -507,11 +626,13 @@ export interface McpCore { + readonly prompts: Prompts + readonly completions: Completions + readonly skills: Skills ++ readonly events: Events + readonly registrationPresence: Effect.Effect<{ + readonly tools: boolean + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +@@ -523,6 +644,12 @@ export interface McpCore { + */ + export type Visible = (invocation: McpInvocation) => Effect.Effect + ++/** ++ * @internal ++ */ ++export const eventNotFound = (name: string): McpSchema.NotFound => ++ new McpSchema.NotFound({ message: `Event '${name}' not found`, data: { kind: "event" } }) ++ + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a: string, b: string): boolean => { + const rootA = a.slice(0, -"/SKILL.md".length) +@@ -539,6 +666,7 @@ export const make: Effect.Effect = Effect.sync(() => { + const resourceTemplateRegistrations: Array = [] + const promptRegistrations = new Map() + const skillRegistrations = new Map() ++ const eventRegistrations = new Map() + const skillFiles = new Set() + const completionRegistrations = new Map< + string, +@@ -717,12 +845,28 @@ export const make: Effect.Effect = Effect.sync(() => { + }) + } + ++ const events: Events = { ++ register: (registration) => ++ Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration) ++ }), ++ list: (invocation) => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => ++ Effect.suspend(() => { ++ const registration = eventRegistrations.get(name) ++ return registration !== undefined && registration.isVisible(invocation.protocol) ++ ? Effect.succeed(registration) ++ : Effect.fail(eventNotFound(name)) ++ }) ++ } ++ + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })) + +- return { tools, resources, prompts, completions, skills, registrationPresence } ++ return { tools, resources, prompts, completions, skills, events, registrationPresence } + }) +diff --git a/src/ai/internal/mcpEvents.ts b/src/ai/internal/mcpEvents.ts +new file mode 100644 +index 0000000..54b2ca8 +--- /dev/null ++++ b/src/ai/internal/mcpEvents.ts +@@ -0,0 +1,315 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.ts" ++import * as Clock from "../../Clock.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Option from "../../Option.ts" ++import * as Queue from "../../Queue.ts" ++import * as Result from "../../Result.ts" ++import * as Rpc from "../../rpc/Rpc.ts" ++import * as RpcGroup from "../../rpc/RpcGroup.ts" ++import * as Schema from "../../Schema.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import * as McpProtocol from "./mcpProtocol.ts" ++import * as Stateless from "./mcpSchema/v2026_07_28.ts" ++ ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events" ++ ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = ( ++ extensions: Readonly> | undefined, ++ servesEvents: boolean ++): Readonly> | undefined => ++ servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions ++ ++const methodNotFound = (method: string) => ++ new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++ }) ++ ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core: McpCore.McpCore, method: string) => ++ Effect.flatMap( ++ core.registrationPresence, ++ (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method)) ++ ) ++ ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value: PublicMcpSchema.EventDelivery) => ++ new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++ }) ++ ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++ ++const optional = Stateless.optional ++const Cursor = Schema.NullOr(Schema.String) ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) ++ ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) {} ++ ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++} ++ ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++ }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), ++ [Stateless.UnknownObject] ++ ), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs ++ extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) ++{} ++ ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make( ++ EventsActiveNotification, ++ EventsEventNotification, ++ EventsHeartbeatNotification, ++ EventsErrorNotification, ++ EventsTerminatedNotification ++) {} ++ ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++ ++const DEFAULT_HEARTBEAT_MS = 30_000 ++const MIN_HEARTBEAT_MS = 1_000 ++const MAX_HEARTBEAT_MS = 300_000 ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16 ++ ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested: number | undefined): number => ++ Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)) ++ ++const isJson = Schema.is(Schema.Json) ++ ++/** ++ * @internal ++ */ ++export const wireError = (failure: McpCore.EventFailure): Stateless.McpError => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}) ++ ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function*(options: { ++ readonly name: string ++ readonly subscription: McpCore.EventSubscription ++ readonly heartbeatMs: number ++ readonly send: (tag: string, payload: Readonly>) => Effect.Effect ++}) { ++ const { heartbeatMs, name, subscription } = options ++ let cursor = subscription.cursor ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0 ++ const send = (tag: string, payload: Readonly>) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at ++ })) ++ const active = (truncated: boolean) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }) ++ yield* active(subscription.truncated) ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }) ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)) ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result) ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }) ++ } ++ return ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }) ++ continue ++ } ++ const item = next.success.value ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor ++ const { _meta, _tag, ...occurrence } = item ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }) ++ break ++ } ++ case "Position": { ++ cursor = item.cursor ++ break ++ } ++ case "Gap": { ++ cursor = item.cursor ++ yield* active(true) ++ break ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }) ++ break ++ } ++ } ++ } ++}, Effect.scoped) +diff --git a/src/ai/internal/mcpProtocol.ts b/src/ai/internal/mcpProtocol.ts +index 5393651..f40915b 100644 +--- a/src/ai/internal/mcpProtocol.ts ++++ b/src/ai/internal/mcpProtocol.ts +@@ -484,6 +484,7 @@ export interface HandlerInstallationContext { + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts +index a701ec8..8e4b36a 100644 +--- a/src/ai/internal/mcpProtocol/v2026_07_28.ts ++++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts +@@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" + import type * as PublicMcpProtocol from "../../McpProtocol.ts" + import * as PublicMcpSchema from "../../McpSchema.ts" + import * as McpCore from "../mcpCore.ts" ++import * as McpEvents from "../mcpEvents.ts" + import * as McpProtocol from "../mcpProtocol.ts" + import * as McpSchema from "../mcpSchema/v2026_07_28.ts" + import * as McpSkills from "../mcpSkills.ts" +@@ -344,7 +345,11 @@ const unsupported = ( + /** + * @internal + */ +-export const handlerRpcs = McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs) ++export const handlerRpcs = McpSchema.ClientRequestRpcs.merge( ++ McpSchema.ClientNotificationRpcs, ++ McpSkills.StatelessRpcs, ++ McpEvents.StatelessRpcs ++) + + /** + * @internal +@@ -370,6 +375,10 @@ export const makeHandlers = ( + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema) ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema) + const sendNotification = context.sendNotification + const supportsSubscriptions = sendNotification !== undefined + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -384,8 +393,14 @@ export const makeHandlers = ( + } + const getDiscovery = Effect.map(context.registrationPresence, (presence) => { + const capabilities: Types.Mutable = { completions: {}, logging: {} } +- const declared = McpSkills.declareExtension(extensions, presence.skills) ++ const declared = McpEvents.declareExtension( ++ McpSkills.declareExtension(extensions, presence.skills), ++ presence.events ++ ) + if (declared !== undefined) capabilities.extensions = declared ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {} + if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } + if (presence.resources) { + capabilities.resources = { listChanged: supportsSubscriptions, subscribe: supportsSubscriptions } +@@ -393,6 +408,30 @@ export const makeHandlers = ( + if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } + return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } + }) ++ const requireEvents = (method: string) => ++ McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))) ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function*( ++ registration: McpCore.EventRegistration, ++ args: unknown ++ ) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest) ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) ++ } ++ }) ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function*(method: string, name: string, args: unknown) { ++ yield* requireEvents(method) ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(name, invocation) ++ const { stream, webhooks } = registration ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ } ++ yield* validateEventHeaders(registration, args) ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments } ++ }) + const requireSkills = (method: string) => + McpSkills.requireSkills(core, method).pipe( + Effect.catch((error) => failWithHttpStatus(404, error)) +@@ -728,6 +767,121 @@ export const makeHandlers = ( + const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) + return yield* decodeReadResourceDirectoryResult(result) + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function*(request: typeof McpEvents.ListEvents.payloadSchema.Type) { ++ yield* requireEvents("events/list") ++ yield* McpProtocol.rejectCursor(request.cursor) ++ const events = yield* core.events.list(yield* getInvocation) ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push") ++ return delivery.length === 0 ? [] : [{ ...event, delivery }] ++ }) ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo) ++ return yield* decodeListEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function*(request: typeof McpEvents.PollEvents.payloadSchema.Type) { ++ yield* requireEvents("events/poll") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation) ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => ++ omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ }) ++ ), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo) ++ return yield* decodePollEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function*( ++ request: typeof McpEvents.StreamEvents.payloadSchema.Type, ++ { client, requestId }: { readonly client: Rpc.ServerClient; readonly requestId: RpcMessage.RequestId } ++ ) { ++ yield* requireEvents("events/stream") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId } ++ const send = (tag: string, payload: Readonly>) => ++ sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }) ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs) ++ yield* Effect.raceFirst( ++ registration.stream( ++ { arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send }) ++ ), ++ context.awaitClientEnd ?? Effect.never ++ ) ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo) ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }) ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration( ++ "events/subscribe", ++ request.name, ++ request.arguments ++ ) ++ const args = request.arguments ?? {} ++ const cursor = request.cursor ?? null ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => ++ stream( ++ { arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ deliver ++ ) ++ }) ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo) ++ return yield* decodeSubscribeEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function*( ++ request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type ++ ) { ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments) ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }) ++ const result = yield* projectCompleteResult({}, context.serverInfo) ++ return yield* decodeUnsubscribeEventsResult(result) ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function*( + _request: typeof McpSchema.CancelledNotification.payloadSchema.Type + ) { +@@ -751,10 +905,10 @@ const runtime = { + export const protocol = McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts +index 9d4c96e..0afe3ed 100644 +--- a/src/ai/internal/mcpRuntime.ts ++++ b/src/ai/internal/mcpRuntime.ts +@@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name" + case "resources/read": + return "uri" +@@ -319,7 +323,13 @@ export const make = Effect.fnUntraced(function*( + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey] + const header = headers[MCP_NAME_HEADER] +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe") ++ if ( ++ !optional && ++ (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) ++ ) { + return headerMismatch("Mcp-Name header does not match request parameters") + } + } +@@ -479,7 +489,9 @@ export const make = Effect.fnUntraced(function*( + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && ++ (input.method === "subscriptions/listen" || input.method === "events/stream") + } + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/internal/mcpWebhooks.ts b/src/ai/internal/mcpWebhooks.ts +new file mode 100644 +index 0000000..5b53d08 +--- /dev/null ++++ b/src/ai/internal/mcpWebhooks.ts +@@ -0,0 +1,692 @@ ++/** ++ * Webhook delivery for the Events extension (SEP-3415): `events/subscribe` ++ * validation, subscription identity, Standard Webhooks signing, the endpoint ++ * verification handshake and the delivery loop. ++ * ++ * Subscriptions live in memory. Every grant is finite, so a subscription lost ++ * in a restart comes back on the client's next refresh, from its cursor. ++ */ ++import * as Clock from "../../Clock.ts" ++import * as Digest from "../../crypto/Digest.ts" ++import * as Mac from "../../crypto/Mac.ts" ++import * as SecureRandom from "../../crypto/SecureRandom.ts" ++import * as Deferred from "../../Deferred.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Base64 from "../../encoding/Base64.ts" ++import * as Base64Url from "../../encoding/Base64Url.ts" ++import * as Fiber from "../../Fiber.ts" ++import * as FetchHttpClient from "../../http/FetchHttpClient.ts" ++import * as HttpClient from "../../http/HttpClient.ts" ++import * as HttpClientRequest from "../../http/HttpClientRequest.ts" ++import type * as HttpClientResponse from "../../http/HttpClientResponse.ts" ++import * as Option from "../../Option.ts" ++import * as Result from "../../Result.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import { wireError } from "./mcpEvents.ts" ++ ++const MINUTE_MS = 60_000 ++/** @internal */ ++export const MIN_TTL_MS = MINUTE_MS ++// Short grants because subscriptions live in memory: a restart loses them until the next refresh. ++/** @internal */ ++export const MAX_TTL_MS = 60 * MINUTE_MS ++/** @internal */ ++export const DEFAULT_TTL_MS = 15 * MINUTE_MS ++/** @internal */ ++export const MAX_ATTEMPTS = 5 ++// Retries wait 30 s, 1, 2 and 4 minutes: about 7.5 minutes in all. ++const FIRST_RETRY_MS = 30_000 ++const REQUEST_TIMEOUT_MS = 10_000 ++// Deliveries signed with the old secret before a rotation still verify for this long. ++const ROTATION_GRACE_MS = 5 * MINUTE_MS ++const VERIFIED_FOR_MS = MAX_TTL_MS ++// A failed challenge is answered from here, so repeated subscribes cannot flood the endpoint. ++const FAILED_FOR_MS = 5 * MINUTE_MS ++// Verification POSTs one destination host receives per minute, across all principals. ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10 ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100 ++// A verification reads this many bytes of the response at most; a delivery reads none. ++const MAX_CHALLENGE_RESPONSE_BYTES = 8_192 ++const SECRET_PREFIX = "whsec_" ++ ++/** ++ * The fixed categories `deliveryStatus.lastError` and `CallbackEndpointError` ++ * report; never the endpoint's own response. ++ * ++ * @internal ++ */ ++export type FailureCategory = ++ | "connection_refused" ++ | "timeout" ++ | "tls_error" ++ | "http_4xx" ++ | "http_5xx" ++ | "challenge_failed" ++ ++/** ++ * @internal ++ */ ++export interface Guard { ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Options { ++ readonly principal: Effect.Effect ++ readonly guard: Guard ++ readonly client: HttpClient.HttpClient ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++ readonly cursor: string | null ++ readonly ttlMs?: number | null | undefined ++ // The event's argument decoder, run before the endpoint is contacted. ++ readonly decode: Effect.Effect ++ // Runs the event's stream for the subscription's lifetime, as push delivery does. ++ readonly open: ( ++ decoded: unknown, ++ deliver: (subscription: McpCore.EventSubscription) => Effect.Effect ++ ) => Effect.Effect ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeResult { ++ readonly id: string ++ readonly refreshBefore: string ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly deliveryStatus?: { ++ readonly active: boolean ++ readonly lastDeliveryAt: string | null ++ readonly lastError: FailureCategory | null ++ } | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface UnsubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++} ++ ++/** ++ * @internal ++ */ ++export interface Webhooks { ++ readonly subscribe: ( ++ request: SubscribeRequest ++ ) => Effect.Effect ++ readonly unsubscribe: (request: UnsubscribeRequest) => Effect.Effect ++ readonly size: Effect.Effect ++} ++ ++interface Subscription { ++ readonly id: string ++ readonly principal: string ++ readonly url: URL ++ secret: string ++ key: Mac.Key ++ previous: { readonly key: Mac.Key; readonly until: number } | undefined ++ expiresAt: number ++ // Everything at or before it was acknowledged or given up on. ++ watermark: string | null ++ lastDeliveryAt: number | undefined ++ lastError: FailureCategory | undefined ++ fiber: Fiber.Fiber | undefined ++ // Completed when a refresh moves the deadline, so the expiry recomputes it. ++ deadlineMoved: Deferred.Deferred ++ // Where the event's stream started, or why it could not; a same-key refresh waits for it. ++ readonly accepted: Deferred.Deferred< ++ { readonly cursor: string | null; readonly truncated: boolean }, ++ McpCore.EventFailure | McpCore.RequestRejected ++ > ++ // After a gap whose envelope the endpoint never took: the cursors handed out since, any of ++ // which a refresh presents to say it saw past the gap. Until then every refresh is truncated. ++ cursorsSinceGap: Set | undefined ++} ++ ++type Outcome = ++ // `body` is read only for a verification, and is undefined when it was too long. ++ | { readonly _tag: "Delivered"; readonly body: string | undefined } ++ | { readonly _tag: "Failed"; readonly category: FailureCategory; readonly retryable: boolean } ++ ++const invalid = (message: string) => new PublicMcpSchema.InvalidParams({ message }) ++ ++/** ++ * The TTL granted for a suggested one: the default when none is suggested, and ++ * never unbounded, since subscriptions are not kept across restarts. ++ * ++ * @internal ++ */ ++export const grantTtl = (suggested: number | null | undefined): number => ++ suggested === undefined ++ ? DEFAULT_TTL_MS ++ : suggested === null ++ ? MAX_TTL_MS ++ : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)) ++ ++/** ++ * JSON with object keys sorted, so equal arguments serialize equally. ++ * ++ * @internal ++ */ ++export const canonicalJson = (value: unknown): string => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]` ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== undefined) ++ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}` ++ } ++ return JSON.stringify(value) ?? "null" ++} ++ ++const encoder = new TextEncoder() ++ ++const parseUrl = (value: unknown, guard: Guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")) ++ let url: URL ++ try { ++ url = new URL(value) ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")) ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")) ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")) ++ } ++ url.hash = "" ++ return Effect.succeed(url) ++} ++ ++const parseSecret = (value: unknown) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")) ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)) ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))) ++} ++ ++const statusCategory = (status: number): FailureCategory => (status >= 500 ? "http_5xx" : "http_4xx") ++ ++// Only codes and names are read, never what the endpoint sent. ++const transportCategory = (error: unknown): FailureCategory => { ++ let current: unknown = error ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = (current as { readonly code?: unknown }).code ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error" ++ current = (current as { readonly cause?: unknown }).cause ?? ++ (current as { readonly reason?: unknown }).reason ++ } ++ return "connection_refused" ++} ++ ++// Stops pulling past the cap; closing the request's scope then aborts the rest. ++const readCapped = (response: HttpClientResponse.HttpClientResponse) => ++ Effect.suspend(() => { ++ const chunks: Array = [] ++ let total = 0 ++ let oversized = false ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true ++ return false ++ } ++ total += chunk.length ++ chunks.push(chunk) ++ return true ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return undefined ++ const bytes = new Uint8Array(total) ++ let offset = 0 ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset) ++ offset += chunk.length ++ } ++ return new TextDecoder().decode(bytes) ++ }) ++ ) ++ }) ++ ++const echoedChallenge = (body: string): string | undefined => { ++ try { ++ const parsed: unknown = JSON.parse(body) ++ const challenge = typeof parsed === "object" && parsed !== null ++ ? (parsed as { readonly challenge?: unknown }).challenge ++ : undefined ++ return typeof challenge === "string" ? challenge : undefined ++ } catch { ++ return undefined ++ } ++} ++ ++const callbackError = (category: FailureCategory) => ++ new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++ }) ++ ++const iso = (millis: number) => new Date(millis).toISOString() ++ ++/** ++ * @internal ++ */ ++export const make = Effect.fnUntraced(function*(options: Options) { ++ const scope = yield* Effect.scope ++ const mac = yield* Mac.Mac ++ const digest = yield* Digest.Digest ++ const random = yield* SecureRandom.SecureRandom ++ const { guard } = options ++ // Closing a request's scope aborts its body, so a delivery never downloads what the endpoint sends. ++ const client = HttpClient.withScope(options.client) ++ const subscriptions = new Map() ++ // Subscribes past the principal check that have not created their subscription yet. ++ const pending = new Map() ++ const verified = new Map() ++ const failedVerifications = new Map() ++ const verifying = new Map>() ++ const verificationsByHost = new Map>() ++ ++ const forget = (subscription: Subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id) ++ } ++ ++ const subscriptionId = (principal: string, url: URL, name: string, args: unknown) => ++ digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ) ++ ++ // High entropy and unrelated to the eventId; a retry reuses it. ++ const messageId = (prefix: string) => ++ Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`) ++ ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They require an event's webhook-id to equal its eventId. Both become this id, derived per ++ // subscription so two subscriptions to one URL never share it; poll and push keep the eventId. ++ const deliveryId = (subscription: Subscription, eventId: string) => ++ Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ) ++ ++ const MAX_CURSORS_SINCE_GAP = 1_024 ++ const advance = (subscription: Subscription, cursor: string | null) => { ++ subscription.watermark = cursor ++ const since = subscription.cursorsSinceGap ++ if (since === undefined) return ++ since.add(cursor) ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value!) ++ } ++ ++ const sign = (keys: ReadonlyArray, webhookId: string, timestamp: number, body: string) => ++ Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ) ++ ++ // One POST. The timestamp and signature are fresh on every attempt. ++ const send = Effect.fnUntraced(function*( ++ subscription: Subscription, ++ body: string, ++ webhookId: string, ++ readBody: boolean ++ ) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)) ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true } satisfies Outcome ++ } ++ const now = yield* Clock.currentTimeMillis ++ const timestamp = Math.floor(now / 1000) ++ const previous = subscription.previous ++ const keys = previous !== undefined && now < previous.until ++ ? [subscription.key, previous.key] ++ : [subscription.key] ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ) ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response): Effect.Effect => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }) ++ } ++ return readBody ++ ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) ++ : Effect.succeed({ _tag: "Delivered", body: undefined }) ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch((error) => ++ Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ) ++ return Option.getOrElse(outcome, (): Outcome => ({ _tag: "Failed", category: "timeout", retryable: true })) ++ }) ++ ++ // Retries with backoff; gives up after a 410, a 413 or the last attempt. True once delivered. ++ const deliver = Effect.fnUntraced(function*(subscription: Subscription, body: string, webhookId: string) { ++ for (let attempt = 1;; attempt++) { ++ // A subscription that ended may have been replaced under its id; this one speaks no longer. ++ const current = subscriptions.get(subscription.id) ++ if (current !== undefined && current !== subscription) return false ++ const startedAt = yield* Clock.currentTimeMillis ++ const outcome = yield* send(subscription, body, webhookId, false) ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis ++ subscription.lastError = undefined ++ return true ++ } ++ subscription.lastError = outcome.category ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false ++ // Counted from the attempt's start, so a slow endpoint does not stretch the window. ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis) ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)) ++ } ++ }) ++ ++ const control = (subscription: Subscription, type: string, fields: Readonly>) => ++ Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ) ++ ++ // One delivery in flight per subscription, so the watermark only moves forward ++ // once everything before it is resolved. ++ const run = (subscription: Subscription, name: string, events: McpCore.EventSubscription) => ++ events.items.pipe( ++ Stream.runForEach((item): Effect.Effect => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...(item._meta === undefined ? {} : { _meta: item._meta }) ++ }) ++ return deliver(subscription, body, webhookId) ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))) ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)) ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = new Set() ++ advance(subscription, item.cursor) ++ }) ++ ) ++ case "Error": ++ // A webhook has no envelope for an error that leaves the subscription open. ++ return Effect.void ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch((failure) => ++ Effect.suspend(() => { ++ forget(subscription) ++ return control(subscription, "terminated", { error: wireError(failure) }) ++ }) ++ ) ++ ) ++ ++ const expiry = (subscription: Subscription) => ++ Effect.gen(function*() { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis) ++ if (left <= 0) return forget(subscription) ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)) ++ } ++ }) ++ ++ const handshake = Effect.fnUntraced(function*(subscription: Subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)) ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ) ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category) ++ const echoed = outcome.body === undefined ? undefined : echoedChallenge(outcome.body) ++ if (echoed === undefined || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed") ++ } ++ }) ++ ++ // Cached per (principal, url) either way; concurrent subscribes share one handshake. ++ const verify = Effect.fnUntraced(function*(subscription: Subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]) ++ const now = yield* Clock.currentTimeMillis ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry) ++ for (const [entry, failure] of failedVerifications) if (failure.until <= now) failedVerifications.delete(entry) ++ if (verified.has(key)) return ++ const failure = failedVerifications.get(key) ++ if (failure !== undefined) return yield* callbackError(failure.category) ++ const inFlight = verifying.get(key) ++ if (inFlight !== undefined) return yield* Deferred.await(inFlight) ++ const host = subscription.url.hostname ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS) ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent) ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }) ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry) ++ } ++ verificationsByHost.set(host, [...recent, now]) ++ const done = Deferred.makeUnsafe() ++ verifying.set(key, done) ++ return yield* handshake(subscription).pipe( ++ Effect.tap(() => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS) ++ }) ++ ), ++ Effect.tapError((category) => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }) ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit((exit) => ++ Effect.sync(() => { ++ verifying.delete(key) ++ Deferred.doneUnsafe(done, exit) ++ }) ++ ) ++ ) ++ }) ++ ++ // A caller that joins while the first subscribe's stream is opening waits for it and gets ++ // where it started; one whose subscription went away meanwhile subscribes afresh. ++ const refresh = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ subscription: Subscription, ++ secret: { readonly text: string; readonly key: Mac.Key }, ++ expiresAt: number, ++ now: number ++ ): Effect.fn.Return { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted) ++ const start = yield* Deferred.await(subscription.accepted) ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request) ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS } ++ subscription.secret = secret.text ++ subscription.key = secret.key ++ } ++ subscription.expiresAt = expiresAt ++ const moved = subscription.deadlineMoved ++ subscription.deadlineMoved = Deferred.makeUnsafe() ++ Deferred.doneUnsafe(moved, Effect.void) ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start } ++ // Kept until the client shows a cursor from past the gap, so a lost response hides nothing. ++ const since = subscription.cursorsSinceGap ++ if (since !== undefined && since.has(request.cursor)) subscription.cursorsSinceGap = undefined ++ const truncated = subscription.cursorsSinceGap !== undefined ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === undefined ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ } satisfies SubscribeResult ++ }) ++ ++ const subscribe: Webhooks["subscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const mode = request.delivery.mode ++ if (mode !== undefined && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'") ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const secret = yield* parseSecret(request.delivery.secret) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const now = yield* Clock.currentTimeMillis ++ const expiresAt = now + grantTtl(request.ttlMs) ++ const live = subscriptions.get(id) ++ if (live !== undefined) return yield* refresh(request, live, secret, expiresAt, now) ++ // The slot is taken before anything asynchronous, so concurrent subscribes cannot pass the cap. ++ let held = pending.get(principal) ?? 0 ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++ ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }) ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1) ++ let reserved = true ++ const release = () => { ++ if (!reserved) return ++ reserved = false ++ const left = (pending.get(principal) ?? 1) - 1 ++ if (left === 0) pending.delete(principal) ++ else pending.set(principal, left) ++ } ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ) ++ }) ++ ++ const create = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ { expiresAt, id, now, principal, release, secret, url }: { ++ readonly principal: string ++ readonly url: URL ++ readonly secret: { readonly text: string; readonly key: Mac.Key } ++ readonly id: string ++ readonly expiresAt: number ++ readonly now: number ++ readonly release: () => void ++ } ++ ) { ++ // One answer whether the host is private or does not resolve, so it reveals neither. ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")) ++ const subscription: Subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: undefined, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: undefined, ++ lastError: undefined, ++ fiber: undefined, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: undefined ++ } ++ const decoded = yield* request.decode ++ yield* verify(subscription) ++ // A concurrent subscribe for the same key may have finished while this one verified. ++ const raced = subscriptions.get(id) ++ if (raced !== undefined) { ++ release() ++ return yield* refresh(request, raced, secret, expiresAt, now) ++ } ++ release() ++ subscriptions.set(id, subscription) ++ const { accepted } = subscription ++ const lifetime = request.open(decoded, (events) => ++ Effect.suspend(() => { ++ subscription.watermark = events.cursor ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }) ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription) ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })) ++ })) ++ ) ++ // Forked from the request, so the event's stream keeps the request's services. ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope) ++ const start = yield* Deferred.await(accepted) ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated } ++ }) ++ ++ const unsubscribe: Webhooks["unsubscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const subscription = subscriptions.get(id) ++ if (subscription === undefined) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }) ++ } ++ subscriptions.delete(id) ++ if (subscription.fiber !== undefined) yield* Fiber.interrupt(subscription.fiber) ++ }) ++ ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ } satisfies Webhooks ++}) +diff --git a/dist/sql/SqlClient.js b/dist/sql/SqlClient.js +--- a/dist/sql/SqlClient.js ++++ b/dist/sql/SqlClient.js +@@ -238,6 +238,9 @@ + log: "Unhandled", + message: "Unhandled error in SqlClient.afterCommit callback" + }); ++// The transaction context extends the fiber's own, so merging the two would only copy every ++// service twice per transaction and savepoint. ++const provideTransactionContext = (effect, services, context) => Effect.updateContext(effect, current => current === services ? context : Context.merge(current, context)); + const makeAfterCommit = transactionService => effect => Effect.withFiber(fiber => { + const transaction = Context.getOrUndefined(fiber.context, transactionService); + const buffer = transaction && afterCommitBuffers.get(transaction); +@@ -328,7 +331,7 @@ + const transaction = Effect.flatMap(conn, ([scope, conn]) => start(conn).pipe(Effect.flatMap(() => { + const level = [conn, id]; + afterCommitBuffers.set(level, buffer); +- return Effect.onExitPrimitive(Effect.provideContext(restore(effect), services.pipe(Context.add(options.transactionService, level), Context.add(CurrentTransactionService, options.transactionService), reactivity ? Context.add(Reactivity, deferInvalidations(reactivity)) : identity, Context.add(transactionSemaphore, Semaphore.makeUnsafe(1)), Context.add(Tracer.ParentSpan, span))), exit => { ++ return Effect.onExitPrimitive(provideTransactionContext(restore(effect), services, services.pipe(Context.add(options.transactionService, level), Context.add(CurrentTransactionService, options.transactionService), reactivity ? Context.add(Reactivity, deferInvalidations(reactivity)) : identity, Context.add(transactionSemaphore, Semaphore.makeUnsafe(1)), Context.add(Tracer.ParentSpan, span))), exit => { + buffer.open = false; + // The savepoint ended with its parent, and the connection + // may already be in another transaction. +diff --git a/src/sql/SqlClient.ts b/src/sql/SqlClient.ts +--- a/src/sql/SqlClient.ts ++++ b/src/sql/SqlClient.ts +@@ -596,6 +596,17 @@ + const runAfterCommit = (effect: Effect.Effect): Effect.Effect => + Effect.ignoreCause(effect, { log: "Unhandled", message: "Unhandled error in SqlClient.afterCommit callback" }) + ++// The transaction context extends the fiber's own, so merging the two would only copy every ++// service twice per transaction and savepoint. ++const provideTransactionContext = ( ++ effect: Effect.Effect, ++ services: Context.Context, ++ context: Context.Context ++): Effect.Effect> => ++ Effect.updateContext(effect, (current: Context.Context>) => ++ (current === services ? context : Context.merge(current, context)) as Context.Context ++ ) ++ + const makeAfterCommit = + (transactionService: Context.Key) => + (effect: Effect.Effect): Effect.Effect => +@@ -747,8 +758,9 @@ + const level = [conn, id] as const + afterCommitBuffers.set(level, buffer) + return Effect.onExitPrimitive( +- Effect.provideContext( ++ provideTransactionContext( + restore(effect), ++ services, + services.pipe( + Context.add(options.transactionService, level), + Context.add(CurrentTransactionService, options.transactionService), diff --git a/scripts/link-vendor.ts b/scripts/link-vendor.ts index 763b506..e3dfc2e 100644 --- a/scripts/link-vendor.ts +++ b/scripts/link-vendor.ts @@ -1,14 +1,56 @@ // Exposes the pinned T3 Code workspace packages under node_modules/@t3tools so // their package export maps resolve. They are TypeScript sources Bun runs as-is. -import { lstat, mkdir, readdir, rm, symlink } from "node:fs/promises"; -import { join, relative } from "node:path"; +// The packages are copied (not symlinked) so the small set of classic-tsc +// false positives below can be patched in the copy; vendor/ itself stays pristine. +import { cp, lstat, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; const root = join(import.meta.dir, ".."); const packagesDir = join(root, "vendor/t3code/packages"); const scopeDir = join(root, "node_modules/@t3tools"); await mkdir(scopeDir, { recursive: true }); for (const name of await readdir(packagesDir)) { - const link = join(scopeDir, name); - await lstat(link).then(() => rm(link, { recursive: true, force: true }), () => {}); - await symlink(relative(scopeDir, join(packagesDir, name)), link, "dir"); + const dest = join(scopeDir, name); + await lstat(dest).then(() => rm(dest, { recursive: true, force: true }), () => {}); + await cp(join(packagesDir, name), dest, { recursive: true }); +} + +// Upstream type-checks these sources with effect-tsgo plus the Effect language +// service, which infers callback parameter types classic tsc cannot. Patch the +// copies so `bun run typecheck` (classic tsc) stays clean. Each entry is applied +// only if the original text is still present; if an upstream bump changes the +// code, re-run typecheck and update the list. +const tscPatches: ReadonlyArray<{ file: string; from: string; to: string }> = [ + { + file: "client-runtime/src/rpc/session.ts", + from: "send: (clientId, request, transferables) =>", + to: "send: (clientId: any, request: any, transferables: any) =>", + }, +]; +for (const { file, from, to } of tscPatches) { + const path = join(scopeDir, file); + const source = await readFile(path, "utf8"); + if (source.includes(from)) await writeFile(path, source.replace(from, to)); +} + +// Upstream resolves "@pierre/words/core" and "@pierre/words/wasm" through its web app's +// tsconfig paths (apps/web/tsconfig.json), not through the package's exports map. Bun does +// not apply those paths to files under vendor/, so add the two subpaths to the installed +// package's exports here. The files ship in the tgz (dist/core.js, dist/words.wasm.mjs). +const wordsManifest = join(root, "node_modules/@pierre/words/package.json"); +try { + const manifest = JSON.parse(await readFile(wordsManifest, "utf8")) as { + exports?: Record; + }; + if (manifest.exports && !("./core" in manifest.exports)) { + manifest.exports["./core"] = { + types: "./dist/core.d.ts", + import: "./dist/core.js", + default: "./dist/core.js", + }; + manifest.exports["./wasm"] = "./dist/words.wasm.mjs"; + await writeFile(wordsManifest, `${JSON.stringify(manifest, null, 2)}\n`); + } +} catch { + // @pierre/words not installed yet; nothing to patch. } diff --git a/src/client/session.ts b/src/client/session.ts index 8c25cfe..8aa5575 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -22,7 +22,7 @@ import { type OrchestrationV2Subagent, type RunId, type SecretRequestAnswerInput, - type ThreadId, + ThreadId, type DiscoveredLocalServer, type GitActionProgressEvent, type GitRunStackedActionResult, @@ -71,6 +71,8 @@ import { type PullRequestReviewVerdict, type PullRequestUpdateMethod, type ThreadPullRequestKey, + type GuestShareCreateResult, + type ProjectCreateFromThreadResult, WS_METHODS, } from "@t3tools/contracts"; import { applyOrchestrationV2ProjectionEvent } from "@t3tools/client-runtime/state/orchestration-v2-projection"; @@ -430,6 +432,32 @@ export class T3Session { }); } + /** Forks one run of a thread into a new thread, as the web's "fork from here" does; resolves with the new thread's id. */ + async forkThread(input: { readonly sourceThreadId: ThreadId; readonly runId: RunId; readonly title?: string }): Promise { + const targetThreadId = ThreadId.make(crypto.randomUUID()); + await this.dispatch({ + type: "thread.fork", + commandId: newCommandId(), + createdBy: "user", + creationSource: "web", + sourceThreadId: input.sourceThreadId, + targetThreadId, + sourcePoint: { type: "run", runId: input.runId }, + ...(input.title === undefined ? {} : { title: input.title }), + }); + return targetThreadId; + } + + /** Creates a guest share link for a thread, as the web's "Share with guest" does. */ + guestShareCreate(threadId: ThreadId): Promise { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.guestShareCreate]({ threadId })); + } + + /** Promotes a scratch thread's folder to a project, as the web's "Turn into project" does. */ + createProjectFromThread(threadId: ThreadId): Promise { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.projectsCreateFromThread]({ threadId })); + } + /** Runs a commit / push / PR action, reporting progress as it goes. Rejects with the server's message on failure. */ async runGitAction(request: GitActionRequest, onProgress: Listener): Promise { const rpc = this.requireConnection().rpc; @@ -1059,6 +1087,12 @@ export class T3Session { : mergeShellSnapshotProjects(previous, item.snapshot, { resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots }), }); return; + case "snapshot-required": + // t3tui never resumes with a cursor, so ask for a fresh full snapshot by + // reconnecting; the new subscription gets a plain "snapshot" item. + this.setShell({ snapshot: null }); + this.connectionLost("snapshot required"); + return; default: if (previous) this.setShell({ snapshot: applyShellStreamEvent(previous, item) }); } diff --git a/src/model/alerts.ts b/src/model/alerts.ts index c8257a3..6604570 100644 --- a/src/model/alerts.ts +++ b/src/model/alerts.ts @@ -1,7 +1,9 @@ import { presentThreadShell } from "@t3tools/client-runtime/state/models"; +import { monitorHoldsWakeCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import type { EnvironmentId, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts"; -import { createThreadNotificationGate, type ThreadNotificationKind, type ThreadNotificationObservation } from "../../vendor/t3code/apps/web/src/components/ThreadNotificationCoordinator.logic.ts"; +import { createThreadNotificationGate, isSnoozedForNotification, type ThreadNotificationKind, type ThreadNotificationObservation } from "../../vendor/t3code/apps/web/src/components/ThreadNotificationCoordinator.logic.ts"; +import { resolveBackgroundThreadRequest } from "../../vendor/t3code/apps/web/src/components/backgroundThreadAnnouncement.ts"; import { resolveStatus, type ThreadStatus } from "./threads.ts"; export type { ThreadNotificationKind }; @@ -17,6 +19,7 @@ export interface Alert { interface Observed extends ThreadNotificationObservation { readonly raw: OrchestrationV2ThreadShell; readonly status: ThreadStatus; + readonly shell: ReturnType; } const LOCAL_ENVIRONMENT = "local" as EnvironmentId; @@ -48,17 +51,30 @@ export function createAlerts(onAlert: (alert: Alert) => void) { const shell = presentThreadShell(LOCAL_ENVIRONMENT, raw); let status = resolveStatus(shell); if (status === "ready" && shell.latestRun?.status === "failed") status = "failed"; - const attention = status === "input" || status === "request" || status === "approval" || status === "failed" || status === "limited" ? `${shell.latestRun?.runId ?? ""}:${status}` : null; - const completedAt = Date.parse(shell.latestRun?.completedAt ?? ""); - const settled = status === "ready" && shell.latestRun?.status === "completed"; - const state: Observed = { raw, status, attention, settled, completedAt: settled && Number.isFinite(completedAt) ? completedAt : null }; + const needsAttention = status === "input" || status === "request" || status === "approval" || status === "failed" || status === "limited"; + const requestId = needsAttention ? resolveBackgroundThreadRequest(shell).requestId : null; + const attention = !needsAttention + ? null + : requestId !== null + ? `${status}:${requestId}` + : `${shell.latestRun?.runId ?? ""}:${status}`; + const completed = status === "ready" && shell.latestRun?.status === "completed"; + const settled = completed && !monitorHoldsWakeCompletion(raw); + const parsedCompletedAt = Date.parse(shell.latestRun?.completedAt ?? ""); + const completedAt = Number.isFinite(parsedCompletedAt) ? parsedCompletedAt : null; + const state: Observed = { raw, status, shell, attention, requestId, settled, completedAt: settled ? completedAt : null, backgroundWake: raw.latestRunBackgroundWake === true }; next.set(raw.id, state); changed.push([prior, state]); } previous = next; gate.retain(new Set(next.keys())); + const now = Date.now(); for (const [prior, state] of changed) { - gate.observe(state.raw.id, prior, state, { archived: state.raw.archivedAt !== null, quiet: state.raw.latestRunStopRequested === true }); + gate.observe(state.raw.id, prior, state, { + archived: state.raw.archivedAt !== null, + quiet: state.raw.latestRunStopRequested === true, + snoozed: isSnoozedForNotification(state.shell, state.completedAt, now), + }); } }, /** The shell went away: the next snapshot counts as a first sighting again. */ diff --git a/src/model/automations.ts b/src/model/automations.ts index bd31b2b..15238fc 100644 --- a/src/model/automations.ts +++ b/src/model/automations.ts @@ -117,6 +117,8 @@ function scheduleText(task: ScheduledTask): string { const days = weekdayNames.length > 0 && weekdayNames.length < 7 ? ` ${weekdayNames.join(",")}` : ""; return `fixed ${schedule.timeOfDay}${days}`; } + case "once": + return `once ${schedule.runAt}`; case "webhook": return "webhook"; } diff --git a/src/model/composerMenu.ts b/src/model/composerMenu.ts index 10d792b..e846afd 100644 --- a/src/model/composerMenu.ts +++ b/src/model/composerMenu.ts @@ -34,11 +34,9 @@ export interface ComposerItem { const THREAD_LIMIT = 5; export const PATH_SEARCH_LIMIT = 80; -/** The trigger the cursor sits in, or null. `/model` is a command here, as t3tui has no model-name search. */ +/** The trigger the cursor sits in, or null. `/model` arrives as a plain slash-command, as t3tui has no model-name search. */ export function composerTrigger(text: string, cursor: number): ComposerTrigger | null { - const trigger = detectComposerTrigger(text, cursor); - if (trigger?.kind === "slash-model") return { ...trigger, kind: "slash-command", query: "model" }; - return trigger; + return detectComposerTrigger(text, cursor); } /** diff --git a/src/model/details.ts b/src/model/details.ts index ec6688d..daeb337 100644 --- a/src/model/details.ts +++ b/src/model/details.ts @@ -18,7 +18,8 @@ import { tildify } from "./paths.ts"; import type { VcsState } from "../client/session.ts"; import { formatClock, type T3tuiConfig } from "../config.ts"; import { buildMenuItems, resolveQuickAction } from "../../vendor/t3code/apps/web/src/components/GitActionsControl.logic.ts"; -import { deriveLatestContextWindowSnapshot, formatContextWindowTokens, latestProviderTurnTokenUsage } from "../../vendor/t3code/apps/web/src/lib/contextWindow.ts"; +import { formatContextWindowTokens } from "../../vendor/t3code/apps/web/src/lib/contextWindow.ts"; +import { deriveLatestContextWindowSnapshot, latestProviderTurnTokenUsage } from "@t3tools/client-runtime/state/context-window"; import { statusLabel, threadState, type StatusTone } from "./threads.ts"; import { providerLimits, type LimitWindowLine } from "./usage.ts"; diff --git a/src/model/pullRequests.ts b/src/model/pullRequests.ts index 72fc3c2..3a83235 100644 --- a/src/model/pullRequests.ts +++ b/src/model/pullRequests.ts @@ -18,6 +18,7 @@ import type { import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { pullRequestLinkProject, resolveLinkPullRequestInput } from "@t3tools/client-runtime/pull-request-link-input"; import { composerPullRequestsFromLinks, filterComposerPullRequestMatches, withLinkedComposerPullRequestsFirst } from "@t3tools/shared/composerPullRequestMatches"; +import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests"; import { formatComposerContextReference, sanitizeComposerContextLabel, toKindScopedComposerContextId } from "@t3tools/shared/composerContextReferences"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; @@ -87,6 +88,7 @@ export function rankComposerPullRequests(input: { repository, query, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, + keyOf: threadPullRequestKeyOf, }); return filtered.map(toComposerPullRequest); } @@ -104,6 +106,7 @@ export function rankComposerPullRequests(input: { linked, query, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, + keyOf: threadPullRequestKeyOf, }); return ranked.map(toComposerPullRequest); } @@ -413,6 +416,7 @@ export const MERGE_METHOD_LABELS: Record = { merge: "Merge", squash: "Squash and merge", rebase: "Rebase and merge", + "fast-forward": "Fast-forward", }; /** The runAction actions to offer: what the host can do and the viewer may, for this state. */ diff --git a/src/model/threadMenu.ts b/src/model/threadMenu.ts index 78f0075..2b08a83 100644 --- a/src/model/threadMenu.ts +++ b/src/model/threadMenu.ts @@ -1,7 +1,9 @@ -import { EnvironmentId, type ContextMenuItem, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type ServerConfig } from "@t3tools/contracts"; +import { EnvironmentId, type ContextMenuItem, type OrchestrationProjectShell, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type ServerConfig } from "@t3tools/contracts"; import { presentThreadShell, threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; import { canSnooze, effectiveSnoozed, pickSnoozePreset, resolveSnoozePresets, type SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort"; +import { isScratchProject } from "@t3tools/client-runtime/state/projects"; +import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels"; import type { T3tuiConfig } from "../config.ts"; import { buildThreadActionMenuItems, type ThreadActionMenuId } from "../../vendor/t3code/apps/web/src/components/threadActionMenu.logic.ts"; @@ -10,8 +12,8 @@ export type { ThreadActionMenuId }; const LOCAL = EnvironmentId.make("local"); -/** Web-only actions: project settings, guest links, turning into a project. */ -const UNSUPPORTED: ReadonlySet = new Set(["project-settings", "share-guest", "turn-into-project", "filter-by-project"]); +/** Web-only actions: the project settings editor and the sidebar's project filter. */ +const UNSUPPORTED: ReadonlySet = new Set(["project-settings", "filter-by-project"]); export interface ThreadMenu { readonly items: readonly ContextMenuItem[]; @@ -19,7 +21,7 @@ export interface ThreadMenu { } /** The web sidebar's thread menu (right-click), from the same builder, less what t3tui can't do. */ -export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell; readonly config: ServerConfig | null; readonly timestampFormat: T3tuiConfig["timestampFormat"]; readonly now?: Date }): ThreadMenu { +export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell; readonly config: ServerConfig | null; readonly timestampFormat: T3tuiConfig["timestampFormat"]; readonly projects?: readonly OrchestrationProjectShell[]; readonly now?: Date }): ThreadMenu { const { config } = input; // The presented shell carries what the menu reads: pending requests, the runtime. const thread = presentThreadShell(config?.environment.environmentId ?? LOCAL, input.thread); @@ -38,8 +40,16 @@ export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell; canSnoozeNow: canSnooze(thread, { now: now.toISOString() }), isRegeneratingTitle: thread.titleRegeneration != null, isRunning: !threadRuntimeCanArchive(thread.runtime), + hasCompletedRun: thread.latestRun?.completedAt != null, supports: { settlement: loaded, autoSettleOptOut: config?.environment.capabilities.threadAutoSettleOptOut === true, snooze: loaded, pinning: loaded, titleRegeneration: loaded }, snoozePresets, + // Guest links need the Labs beta on and Connect allowed, as the web's availability check reads them. + canShareWithGuest: config?.settings.guestSharingEnabled === true && managedCapabilityDenial(config.managedPolicy, "connect") === undefined, + // A scratch thread with its own folder can become a project, when the server allows it. + canTurnIntoProject: + thread.worktreePath != null && + config?.environment.capabilities.threadProjectFromScratch === true && + (input.projects ?? []).some((project) => project.id === thread.projectId && isScratchProject(project, config?.scratchWorkspaceRoot)), }); return { items: items.filter((item) => !UNSUPPORTED.has(item.id)), snoozePresets }; } diff --git a/src/model/timeline.ts b/src/model/timeline.ts index b046982..505d941 100644 --- a/src/model/timeline.ts +++ b/src/model/timeline.ts @@ -38,6 +38,8 @@ export interface Timeline { readonly rows: readonly MessagesTimelineRow[]; readonly pending: PendingThreadRequests; readonly turns: readonly TurnTarget[]; + /** Checkpoint summaries by run; an assistant message's summary is the one whose `assistantMessageId` is its id. */ + readonly turnDiffSummaries: TurnDiffSummaries; readonly isWorking: boolean; /** When the current run started working, for "Working for 12s". */ readonly workStartedAt: string | null; @@ -124,6 +126,7 @@ export function buildTimeline( return { rows: stable.result, pending, + turnDiffSummaries, turns: turnTargets(projection, entries.entries, isWorking ? runtime?.activeRunId ?? null : null, options.historyComplete), isWorking, workStartedAt, diff --git a/src/model/turns.ts b/src/model/turns.ts index 8bce316..4457556 100644 --- a/src/model/turns.ts +++ b/src/model/turns.ts @@ -1,14 +1,28 @@ -import type { MessageId, OrchestrationV2ThreadProjection, RunId } from "@t3tools/contracts"; -import { checkpointFileTotals, deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; +import type { ChatAttachment, MessageId, OrchestrationV2CheckpointFileTotals, OrchestrationV2ThreadProjection, RunId } from "@t3tools/contracts"; +import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; import { deriveRevertTurnCountByUserMessageId, findRevertCheckpoint, type TimelineEntriesProjection } from "../../vendor/t3code/apps/web/src/session-logic.ts"; export { findRevertCheckpoint }; export type TurnCheckpoint = ReturnType[number]; + +/** Upstream inlined this into its diff views; the summary still carries `files`/`filesTotal`. */ +export function checkpointFileTotals( + checkpoint: Pick, +): OrchestrationV2CheckpointFileTotals { + if (checkpoint.filesTotal !== undefined) return checkpoint.filesTotal; + let additions = 0; + let deletions = 0; + for (const file of checkpoint.files) { + additions += file.additions; + deletions += file.deletions; + } + return { count: checkpoint.files.length, additions, deletions }; +} export interface TurnTarget { readonly messageId: MessageId; readonly runId: RunId; readonly text: string; - readonly hasAttachments: boolean; + readonly attachments: readonly ChatAttachment[]; readonly checkpoint: TurnCheckpoint | undefined; readonly revertTurnCount: number | undefined; } @@ -19,7 +33,7 @@ export function turnTargets(projection: OrchestrationV2ThreadProjection, entries const revertCounts = deriveRevertTurnCountByUserMessageId({ timelineEntries: entries, checkpoints, - threadStartCheckpointReady: historyComplete && findRevertCheckpoint(projection.checkpoints, 0) !== undefined, + threadStartCheckpointAvailable: historyComplete && findRevertCheckpoint(projection, 0) !== undefined, availableRevertTurnCounts: availableRevertTurnCounts(projection), unsettledRunId, }); @@ -29,7 +43,7 @@ export function turnTargets(projection: OrchestrationV2ThreadProjection, entries const message = entry.message; const runId = entry.message.runId; seen.add(runId); - return [{ messageId: message.id, runId, text: message.text, hasAttachments: (message.attachments?.length ?? 0) > 0, + return [{ messageId: message.id, runId, text: message.text, attachments: message.attachments ?? [], checkpoint: checkpoints.findLast((checkpoint) => checkpoint.runId === message.runId), revertTurnCount: revertCounts.get(message.id) }]; }); } diff --git a/src/model/usage.ts b/src/model/usage.ts index 0a56c93..931461d 100644 --- a/src/model/usage.ts +++ b/src/model/usage.ts @@ -1,5 +1,6 @@ import type { ProviderConsumeResetCreditInput, ProviderInstanceId, ServerConfig, ServerProviderResetCredits, UsageSummary } from "@t3tools/contracts"; -import { collectLimitAccounts, collectLimitNotices, collectProviderUsageLimits, formatDuration, limitsNotice, remainingPercent, type LimitPresentations } from "@t3tools/shared/usageLimits"; +import { collectLimitAccounts, collectProviderUsageLimits, remainingPercent, type LimitPresentations } from "@t3tools/shared/usageLimits"; +import { collectLimitNotices, formatDuration, limitsNotice } from "@t3tools/shared/usageLimitsCopy"; import { formatTokens, formatUsd } from "@t3tools/shared/usageFormat"; /** At or above this much of a window used, the status line calls the limit near. */ diff --git a/src/pierre-words-wasm.d.ts b/src/pierre-words-wasm.d.ts new file mode 100644 index 0000000..f956b3c --- /dev/null +++ b/src/pierre-words-wasm.d.ts @@ -0,0 +1,6 @@ +// Upstream declares this in apps/web/src/markdown/wordsWasm.d.ts; the tgz ships the wasm as +// an .mjs with no types, and t3tui's tsconfig has no `~/*` include root for that file. +declare module "@pierre/words/wasm" { + const bytes: Uint8Array; + export default bytes; +} diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 5b9cb8c..4579308 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -8,7 +8,7 @@ import { isAbsolute, join, relative } from "node:path"; import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts"; +import type { AttachmentCreateUploadUrlInput, ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts"; import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts"; import { createAlerts, type Alert } from "../model/alerts.ts"; import { pastedImagePath } from "../model/attachments.ts"; @@ -817,6 +817,20 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui drafts.current.set(id, next); if (id === activeComposerKey.current && composerRef.current) { chips.replaceText(composerRef.current, next); setMode("input"); } }, + restoreAttachments: (id, attachments) => { + // Re-upload each one from its signed URL, as the web's rewind does, then put them back on that composer. + void (async () => { + const restored: ChatAttachment[] = []; + for (const attachment of attachments) { + if (attachment.type !== "image" && attachment.type !== "file") continue; + const bytes = await session.attachmentImage(attachment); + restored.push(await session.uploadAttachment({ type: attachment.type, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: bytes.length } as AttachmentCreateUploadUrlInput, bytes)); + } + attach.restore(id, restored); + say(restored.length > 0 ? `Restored ${restored.length} attachment${restored.length === 1 ? "" : "s"}` : "No attachments could be restored.", restored.length === 0); + })().catch((error) => say(`Could not restore attachments: ${messageOf(error)}`, true)); + }, + openForkedThread: (id) => openThread(id), }); // Pull requests: the P view, link/unlink/watch, a draft checked out from one. diff --git a/src/ui/SecretPanel.tsx b/src/ui/SecretPanel.tsx index 59d0438..e740ea4 100644 --- a/src/ui/SecretPanel.tsx +++ b/src/ui/SecretPanel.tsx @@ -1,4 +1,4 @@ -import { SECRET_REQUEST_DEFAULT_PLACEHOLDER, secretRequestPrivacyNote, type SecretRequestItem } from "@t3tools/client-runtime/secret-request"; +import { secretRequestInputs, secretRequestPrivacyNote, type SecretRequestItem } from "@t3tools/client-runtime/secret-request"; import { Button, Buttons } from "./Button.tsx"; import { colors } from "./theme.ts"; @@ -11,13 +11,14 @@ export function SecretPanel(props: { readonly request: SecretRequestItem; readon const { actions } = props; const { request, value } = props; const focused = value !== null; + const placeholder = secretRequestInputs(request)[0]?.placeholder ?? "Paste the secret"; return ( {`🔒 ${request.label}`} {request.reason.trim() ? {request.reason} : null} - {focused ? {value ? "•".repeat(Math.min(value.length, 64)) : (request.placeholder ?? SECRET_REQUEST_DEFAULT_PLACEHOLDER)} : null} + {focused ? {value ? "•".repeat(Math.min(value.length, 64)) : placeholder} : null} {props.error ? {props.error} : null} {props.busy ? "Saving…" : secretRequestPrivacyNote(request)} diff --git a/src/ui/ThreadView.tsx b/src/ui/ThreadView.tsx index c62c669..cc374a3 100644 --- a/src/ui/ThreadView.tsx +++ b/src/ui/ThreadView.tsx @@ -8,7 +8,8 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts"; import { FindText } from "./FindText.tsx"; import { isLeftClick, isRightClick, useHover } from "./Button.tsx"; -import { checkpointFileTotals, type ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { checkpointFileTotals } from "../model/turns.ts"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import type { T3tuiConfig } from "../config.ts"; @@ -79,6 +80,7 @@ export function ThreadView(props: { findThreadSearchOccurrences(segment, props.findQuery).length > 0)) return ; } - const summary = row.assistantTurnDiffSummary; + const summary = props.turnDiffSummaries.findLast((candidate) => candidate.assistantMessageId === message.id); const menu = { kind: "message", messageId: message.id, role: message.role, text: message.text, ...(summary && summary.files.length > 0 ? { checkpointTurnCount: summary.checkpointTurnCount } : {}) } as const; if (message.role === "user") return mouse.selectTurn(message.id)} onMenu={() => mouse.menu(menu)} />; if (message.role === "system") return isRightClick(event) && mouse.menu(menu)}>{message.text}; diff --git a/src/ui/terminalAttach.ts b/src/ui/terminalAttach.ts index 122bf91..95d4370 100644 --- a/src/ui/terminalAttach.ts +++ b/src/ui/terminalAttach.ts @@ -16,6 +16,7 @@ export interface TerminalTarget { readonly cwd: string; readonly worktreePath: string | null; readonly label: string; + readonly hasRunningSubprocess: boolean; } /** diff --git a/src/ui/useComposerMenu.ts b/src/ui/useComposerMenu.ts index 364142a..43bf721 100644 --- a/src/ui/useComposerMenu.ts +++ b/src/ui/useComposerMenu.ts @@ -60,7 +60,6 @@ export function useComposerMenu(deps: { if (!trigger || triggerKey === dismissed) return null; switch (trigger.kind) { case "slash-command": - case "slash-model": return { items: slashItems({ provider, cwd, text: state.text, trigger }), empty: "No matching command.", loading: false }; case "skill": return { items: skillItems(provider, cwd, trigger.query), empty: "No skills found. Try / to browse provider commands.", loading: false }; diff --git a/src/ui/useSecretRequest.ts b/src/ui/useSecretRequest.ts index 67dc737..9ba8e82 100644 --- a/src/ui/useSecretRequest.ts +++ b/src/ui/useSecretRequest.ts @@ -36,7 +36,7 @@ export function useSecretRequest(input: { setValue(value + decoder.decode(event.bytes).replace(/[\r\n]+/g, "")); }); - const answer = (reply: { readonly type: "save"; readonly secret: string } | { readonly type: "decline" }) => { + const answer = (reply: { readonly type: "save"; readonly values: Readonly> } | { readonly type: "decline" }) => { const answerInput = request ? secretRequestAnswerInput(request, reply) : null; if (!answerInput || busy) return; setBusy(true); @@ -59,7 +59,7 @@ export function useSecretRequest(input: { const actions = { focus: () => setValue(""), cancel: () => setValue(null), - save: () => value !== null && answer({ type: "save", secret: value }), + save: () => value !== null && answer({ type: "save", values: { "": value } }), decline: () => answer({ type: "decline" }), }; diff --git a/src/ui/useThreadMenu.ts b/src/ui/useThreadMenu.ts index 620fd0f..ae2c911 100644 --- a/src/ui/useThreadMenu.ts +++ b/src/ui/useThreadMenu.ts @@ -115,6 +115,16 @@ export function useThreadMenu(deps: { } case "copy-thread-id": return copy(id, `Thread ID copied: ${id}`); + case "share-guest": + return run("Guest link created", async () => { + const result = await session.guestShareCreate(id); + copy(result.url, `Guest link copied: ${result.url}`); + }); + case "turn-into-project": + return run("Project created", async () => { + await session.createProjectFromThread(id); + say(`Project created from ${title}`); + }); case "archive": return run("Archived", async () => { await session.archiveThread(id); @@ -138,7 +148,7 @@ export function useThreadMenu(deps: { }; const open = (target: OrchestrationV2ThreadShell) => { - const menu = threadMenu({ thread: target, config, timestampFormat: deps.timestampFormat }); + const menu = threadMenu({ thread: target, config, timestampFormat: deps.timestampFormat, projects: deps.snapshot?.projects ?? [] }); const toPicker = (title: string, items: readonly ContextMenuItem[]): Picker => { const groups: { label: string; items: PickerItem[] }[] = [{ label: title, items: [] }]; for (const item of items) { diff --git a/src/ui/useTurns.ts b/src/ui/useTurns.ts index 4af613b..aeefa2f 100644 --- a/src/ui/useTurns.ts +++ b/src/ui/useTurns.ts @@ -1,5 +1,5 @@ import type { ScrollBoxRenderable } from "@opentui/core"; -import type { OrchestrationV2ThreadProjection, ServerConfig, ThreadId } from "@t3tools/contracts"; +import type { ChatAttachment, OrchestrationV2ThreadProjection, ServerConfig, ThreadId } from "@t3tools/contracts"; import { useEffect, useRef, useState, type Dispatch, type RefObject, type SetStateAction } from "react"; import type { T3Session } from "../client/session.ts"; import type { Binding } from "../model/keymap.ts"; @@ -27,6 +27,10 @@ export function useTurns(input: { readonly say: (text: string, bad?: boolean) => void; readonly showConversation: () => void; readonly restorePrompt: (threadId: ThreadId, text: string) => void; + /** Puts a rewound message's attachments back on that thread's composer. */ + readonly restoreAttachments: (threadId: ThreadId, attachments: readonly ChatAttachment[]) => void; + /** Opens a thread forked from one of this thread's turns. */ + readonly openForkedThread: (threadId: ThreadId) => void; }) { const [cursor, setCursor] = useState<{ threadId: ThreadId; messageId: string } | null>(null); const [reverting, setReverting] = useState(false); @@ -78,23 +82,37 @@ export function useTurns(input: { if (!provider || provider.supportsConversationRollback === false) return input.say("This provider does not support reverting conversation history. Start a new thread instead.", true); if (input.timeline?.isWorking) return input.say("Interrupt the current turn before reverting checkpoints.", true); const turnCount = target.revertTurnCount; - const checkpoint = turnCount === undefined ? undefined : findRevertCheckpoint(projection.checkpoints, turnCount); + const checkpoint = turnCount === undefined ? undefined : findRevertCheckpoint(projection, turnCount); if (turnCount === undefined || !checkpoint) return input.say("This message has no available checkpoint to rewind to.", true); - if (target.hasAttachments) return input.say("Use the T3 Code app to rewind a message with attachments.", true); input.confirm({ title: "Edit from here?", - detail: "Rewind chat to before this message. Your prompt returns to the composer. “Revert files too” also undoes your own edits.", + detail: "Rewind chat to before this message. Your prompt returns to the composer, with its attachments. “Revert files too” also undoes your own edits.", confirmLabel: restoreFiles ? "Revert files too" : "Revert and keep changes", run: () => { setReverting(true); input.session.rewind(projection, checkpoint, turnCount, restoreFiles).then(() => { input.restorePrompt(projection.thread.id, recallableComposerPrompt(target.text)); + if (target.attachments.length > 0) input.restoreAttachments(projection.thread.id, target.attachments); if (currentThread.current === projection.thread.id) { setCursor(null); input.setDiff(null); } input.say("Thread rewound"); }, (error) => input.say(`Could not rewind: ${messageOf(error)}`, true)).finally(() => setReverting(false)); }, }); }; + /** Forks the selected turn's run into a new thread and opens it, as the web's "fork from here" does. */ + const fork = (target = selected) => { + const projection = input.projection; + if (!target || !projection) return input.say("Select a turn with [ or ] first."); + if (input.timeline?.isWorking) return input.say("Interrupt the current turn before forking from a run.", true); + input.say("Forking this turn…"); + input.session.forkThread({ sourceThreadId: projection.thread.id, runId: target.runId, title: `${projection.thread.title || "Thread"} fork` }).then( + (forkedId) => { + input.say("Forked"); + input.openForkedThread(forkedId); + }, + (error) => input.say(`Could not fork: ${messageOf(error)}`, true), + ); + }; const turnKeys = input.enabled && turns.length > 0; /** * Turn keys in navigation. A diff's own keys come first: there, [ and ] step through its @@ -121,6 +139,7 @@ export function useTurns(input: { ...(turnKeys && selected ? [ { keys: [], run: () => revert(true), command: { id: "turn-revert-files", title: "Revert files too", keywords: ["rollback", "rewind", "turn"] } }, + { keys: [], run: () => fork(), command: { id: "turn-fork", title: "Fork from this turn", keywords: ["fork", "branch", "copy", "new thread"] } }, ...(input.diff ? [] : [{ keys: ["esc"], run: () => setCursor(null), command: { id: "turn-clear", title: "Clear turn selection" } }]), ] : []), @@ -137,6 +156,7 @@ export function useTurns(input: { { id: "turn-revert", title: "Revert to before this prompt…", hint: "R", run: run(() => revert(false, turn)) }, { id: "turn-revert-files", title: "Revert files too…", run: run(() => revert(true, turn)) }, ] : []), + { id: "turn-fork", title: "Fork from this turn…", run: run(() => fork(turn)) }, ]; }; return { selectedMessageId, bindings, diffContext, select, menuFor, openTurnDiff }; diff --git a/src/ui/useWorkspace.ts b/src/ui/useWorkspace.ts index ba94cc1..4b169e4 100644 --- a/src/ui/useWorkspace.ts +++ b/src/ui/useWorkspace.ts @@ -2,7 +2,7 @@ import type { CliRenderer, KeyEvent } from "@opentui/core"; import type { OrchestrationProjectShell, OrchestrationV2ThreadShell, ServerConfig, ServerLifecycleStreamEvent, TerminalSummary, ThreadId, WorktreeSetupSnapshot } from "@t3tools/contracts"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; import { deriveLocalBranchNameFromRemoteRef, sanitizeNewRefName } from "@t3tools/shared/git"; -import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels"; +import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabelsCopy"; import { useEffect, useRef, useState } from "react"; import type { FeedState, T3Session } from "../client/session.ts"; @@ -78,17 +78,18 @@ export function useWorkspace(input: { const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id); const cwd = thread?.worktreePath ?? project?.workspaceRoot; const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal); - const targetOf = (threadId: ThreadId, terminal: Pick): TerminalTarget => ({ + const targetOf = (threadId: ThreadId, terminal: Pick): TerminalTarget => ({ threadId, terminalId: terminal.terminalId, cwd: terminal.cwd, worktreePath: terminal.worktreePath, label: resolveTerminalSessionLabel(terminal.terminalId, terminal), + hasRunningSubprocess: terminal.hasRunningSubprocess, }); /** The drawer's tabs: the thread's terminals that haven't exited. */ const tabs = thread ? threadTerminals.filter((terminal) => terminal.status !== "exited").map((terminal) => targetOf(thread.id, terminal)) : []; /** In the drawer, or with the whole screen. */ - const enterTerminal = (terminal: Pick, fullScreen = false) => { + const enterTerminal = (terminal: Pick, fullScreen = false) => { if (!thread) return; const target = targetOf(thread.id, terminal); if (!fullScreen) return input.openPane(target); @@ -101,7 +102,7 @@ export function useWorkspace(input: { const request = newTerminalInput(thread.id, project.workspaceRoot, thread.worktreePath, threadTerminals, terminals?.status === "live"); run("Terminal opened", async () => { await session.openTerminal(request); - enterTerminal({ terminalId: request.terminalId, cwd: request.cwd, worktreePath: thread.worktreePath, label: "" }, fullScreen); + enterTerminal({ terminalId: request.terminalId, cwd: request.cwd, worktreePath: thread.worktreePath, label: "", hasRunningSubprocess: false }, fullScreen); }); }; /** The old way in: the terminal takes the screen until ctrl+j. */ @@ -115,7 +116,7 @@ export function useWorkspace(input: { }); }; /** Closing ends the shell and deletes its history, so it asks first. */ - const closeTerminal = (terminal: Pick) => { + const closeTerminal = (terminal: Pick) => { if (!thread) return; confirm({ title: `Close ${resolveTerminalSessionLabel(terminal.terminalId, terminal)}?`, diff --git a/test/app/app.test.tsx b/test/app/app.test.tsx index f340f6d..bc776cf 100644 --- a/test/app/app.test.tsx +++ b/test/app/app.test.tsx @@ -180,6 +180,51 @@ describe("a finished turn", () => { // The date half is locale- and timezone-shaped; the model and duration are not. expect(app.frame()).toMatch(/gpt-5\.4 · 3m 12s · /); }); + + test("forking a turn dispatches thread.fork and opens the new thread", async () => { + const app = await open({ session: fakeSession({ projection: withCompletedTurn(), results: { forkThread: "thread-fork-1" } }) }); + await app.press("]"); + await app.press("k", { ctrl: true }); + await app.type("fork from this turn"); + await app.press("return"); + await app.settle(50); + expect(app.calls("forkThread").map((call) => call.args[0])).toEqual([{ sourceThreadId: v2ThreadId, runId: "run-1", title: "Thread fork" }]); + }); + + test("rewinding a message with attachments puts the prompt and the attachments back", async () => { + const attachment = { type: "image", id: "att-1", name: "shot.png", mimeType: "image/png", sizeBytes: 3 }; + const projection = structuredClone(withCompletedTurn()) as unknown as { + messages: { attachments: unknown }[]; + turnItems: { type: string; attachments: unknown }[]; + visibleTurnItems: { item: { type?: string; attachments: unknown } }[]; + thread: Record; + checkpoints: Record[]; + providerThreads: unknown[]; + }; + projection.messages[0]!.attachments = [attachment]; + projection.turnItems.find((item) => item.type === "user_message")!.attachments = [attachment]; + for (const visible of projection.visibleTurnItems) if (visible.item.type === "user_message") visible.item.attachments = [attachment]; + // A thread-start checkpoint and a provider thread make turn 0 rewindable. + projection.thread.activeProviderThreadId = "pt-1"; + projection.providerThreads = [{ id: "pt-1", providerSessionId: "ps-1", providerInstanceId: "codex" }]; + projection.checkpoints.unshift({ id: "checkpoint-0", threadId: projection.thread.id, scopeId: "scope-1", runId: null, nodeId: null, parentCheckpointId: null, ordinalWithinScope: 0, appRunOrdinal: null, ref: "refs/t3/checkpoint-0", status: "ready", files: [], capturedAt: projection.checkpoints[0]!.capturedAt }); + const serverConfig = { providers: [{ instanceId: "codex", driver: "codex", enabled: true, auth: { status: "authenticated" }, models: [] }], settings: {}, environment: { capabilities: {} } }; + const app = await open({ + session: fakeSession({ + projection: projection as unknown as OrchestrationV2ThreadProjection, + serverConfig, + results: { attachmentImage: new Uint8Array([1, 2, 3]), uploadAttachment: { type: "image", id: "att-new", name: "shot.png", mimeType: "image/png", sizeBytes: 3 } }, + }), + }); + await app.press("]"); + await app.press("R"); + await app.settle(30); + await app.press("return"); + await app.settle(80); + expect(app.calls("rewind")).toHaveLength(1); + expect(app.calls("uploadAttachment").map((call) => call.args[0])).toEqual([{ type: "image", name: "shot.png", mimeType: "image/png", sizeBytes: 3 }]); + expect(app.hints()).toBe("Restored 1 attachment"); + }); }); describe("live status", () => { diff --git a/test/app/files.test.tsx b/test/app/files.test.tsx index 9a88a4e..67ca066 100644 --- a/test/app/files.test.tsx +++ b/test/app/files.test.tsx @@ -247,7 +247,7 @@ describe("acting on a file", () => { await prefix(app, "k"); await app.press("i"); await app.press("return"); - expect(app.calls("sendMessage")[0]?.args[1]).toBe("[src](src) [debug.log](debug.log)"); + expect(app.calls("sendMessage")[0]?.args[1]).toBe("[src](./src) [debug.log](debug.log)"); }); test("y copies the path", async () => { diff --git a/test/app/harness.tsx b/test/app/harness.tsx index a360c65..d832132 100644 --- a/test/app/harness.tsx +++ b/test/app/harness.tsx @@ -3,7 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { testRender } from "@opentui/react/test-utils"; import { createMockKeys, type KeyInput } from "@opentui/core/testing"; -import type { OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts"; +import { RunId, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadProjection, type ThreadId } from "@t3tools/contracts"; import type { ConnectionStatus, T3Session } from "../../src/client/session.ts"; import { DEFAULT_CONFIG, type T3tuiConfig } from "../../src/config.ts"; @@ -52,7 +52,11 @@ export function fakeSession( ) { const calls: Call[] = []; const threadListeners = new Set<(value: unknown) => void>(); - const snapshot = state.snapshot ?? v2ShellSnapshot; + // The default thread has a finished run, as upstream's menu tests assume: "Mark unread" + // only shows once the latest run completed. + const snapshot = + state.snapshot ?? + ({ ...v2ShellSnapshot, threads: v2ShellSnapshot.threads.map((thread) => ({ ...thread, latestRunId: RunId.make("run-v2") })) } as OrchestrationV2ShellSnapshot); const projection = state.projection ?? v2Projection; const live = (value: T) => (listener: (value: T) => void) => { listener(value); diff --git a/test/details.test.ts b/test/details.test.ts index 0f558a6..df4aecd 100644 --- a/test/details.test.ts +++ b/test/details.test.ts @@ -150,7 +150,7 @@ describe("threadDetails", () => { test("shows the run state, the context window left and the provider's limits", () => { const projection = { ...v2Projection, providerTurns: [{ tokenUsage: { usedTokens: 62_000, maxTokens: 100_000, updatedAt: "2026-06-20T00:00:00.000Z" } }] } as unknown as OrchestrationV2ThreadProjection; const serverConfig = { - providers: [{ instanceId: "codex", driver: "codex", enabled: true, usageLimits: { checkedAt: "2026-06-20T00:00:00.000Z", windows: [{ id: "5h", kind: "session", label: "5h", usedPercent: 39 }, { id: "week", kind: "weekly", label: "week", usedPercent: 95 }] } }], + providers: [{ instanceId: "codex", driver: "codex", enabled: true, auth: { status: "authenticated" }, usageLimits: { checkedAt: "2026-06-20T00:00:00.000Z", windows: [{ id: "5h", kind: "session", label: "5h", usedPercent: 39 }, { id: "week", kind: "weekly", label: "week", usedPercent: 95 }] } }], }; const details = detailsOf(thread({ status: "running", activeRunId: "run-1", latestRunId: "run-1" }), null, null, { projection, serverConfig } as never); expect(details.context).toEqual({ left: 38, used: "62k" }); diff --git a/test/threadMenu.test.ts b/test/threadMenu.test.ts index e2de4c5..f2d528e 100644 --- a/test/threadMenu.test.ts +++ b/test/threadMenu.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { OrchestrationV2Command, ThreadId, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type ServerConfig } from "@t3tools/contracts"; +import { OrchestrationV2Command, RunId, ThreadId, type OrchestrationProjectShell, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type ServerConfig } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; @@ -99,6 +99,7 @@ describe("thread menu", () => { await session.reorderThread(id, "pinned", "m"); await session.reorderThread(id, "active", "t"); await session.deleteThread(id, false); + await session.forkThread({ sourceThreadId: id, runId: RunId.make("run-1"), title: "Thread fork" }); expect(sent.filter((command) => !Schema.is(OrchestrationV2Command)(command))).toEqual([]); expect(sent.map((command) => (command as { type: string }).type)).toEqual([ "thread.settle", @@ -116,6 +117,21 @@ describe("thread menu", () => { "thread.pin.reorder", "thread.active.reorder", "thread.delete", + "thread.fork", ]); }); + + test("guest sharing shows only when the server's Labs beta is on", () => { + const guestConfig = { ...config, settings: { guestSharingEnabled: true } } as unknown as ServerConfig; + expect(ids(threadMenu({ thread, config: guestConfig, timestampFormat: "24-hour" }).items)).toContain("share-guest"); + expect(ids(threadMenu({ thread, config, timestampFormat: "24-hour" }).items)).not.toContain("share-guest"); + }); + + test("a scratch thread with its own folder can turn into a project when the server allows it", () => { + const scratch = { ...thread, worktreePath: "/tmp/scratch" } as unknown as OrchestrationV2ThreadShell; + const capConfig = { ...config, scratchWorkspaceRoot: "/tmp/scratch", environment: { environmentId: "env-1", capabilities: { threadProjectFromScratch: true } } } as unknown as ServerConfig; + const projects = [{ id: "p1", workspaceRoot: "/tmp/scratch" }] as unknown as OrchestrationProjectShell[]; + expect(ids(threadMenu({ thread: scratch, config: capConfig, timestampFormat: "24-hour", projects }).items)).toContain("turn-into-project"); + expect(ids(threadMenu({ thread, config, timestampFormat: "24-hour", projects }).items)).not.toContain("turn-into-project"); + }); }); diff --git a/test/turns.test.ts b/test/turns.test.ts index e06207f..faea173 100644 --- a/test/turns.test.ts +++ b/test/turns.test.ts @@ -33,7 +33,7 @@ describe("turn cursor and checkpoint targets", () => { test("rewinds before the prompt, using visible predecessors across ordinal gaps", () => { const turns = turnTargets(projection(), entries(), null, true); expect(turns.map((turn) => turn.revertTurnCount)).toEqual([0, 1, 2]); - expect(findRevertCheckpoint(projection().checkpoints, turns[2]!.revertTurnCount!)?.id).toBe(CheckpointId.make("cp-2")); + expect(findRevertCheckpoint(projection(), turns[2]!.revertTurnCount!)?.id).toBe(CheckpointId.make("cp-2")); }); test("does not mistake the first message in paged history for the thread start", () => { const turns = turnTargets(projection(), entries().slice(1), null, false); diff --git a/test/workspace.test.ts b/test/workspace.test.ts index e01a39a..a4f3de4 100644 --- a/test/workspace.test.ts +++ b/test/workspace.test.ts @@ -39,8 +39,8 @@ describe("workspace logic", () => { }); test("branch selection reuses worktrees and returns the default branch to the project", () => { - expect(resolveBranchSelectionTarget({ activeProjectCwd: "/repo", activeWorktreePath: "/old", refName: { isDefault: false, worktreePath: "/existing" } })).toEqual({ checkoutCwd: "/existing", nextWorktreePath: "/existing", reuseExistingWorktree: true }); - expect(resolveBranchSelectionTarget({ activeProjectCwd: "/repo", activeWorktreePath: "/old", refName: { isDefault: true, worktreePath: null } })).toEqual({ checkoutCwd: "/repo", nextWorktreePath: null, reuseExistingWorktree: false }); + expect(resolveBranchSelectionTarget({ activeProjectCwd: "/repo", activeWorktreePath: "/old", refName: { isDefault: false, worktreePath: "/existing" } })).toEqual({ checkoutCwd: "/existing", nextWorktreePath: "/existing", reuseExistingWorktree: true, staysInActiveCheckout: false }); + expect(resolveBranchSelectionTarget({ activeProjectCwd: "/repo", activeWorktreePath: "/old", refName: { isDefault: true, worktreePath: null } })).toEqual({ checkoutCwd: "/repo", nextWorktreePath: null, reuseExistingWorktree: false, staysInActiveCheckout: false }); }); test("setup progress names the web's stage, percent, details and failures", () => { diff --git a/tsconfig.json b/tsconfig.json index 4199002..a8135ac 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,7 +13,12 @@ "skipLibCheck": true, "types": [ "bun" - ] + ], + "preserveSymlinks": true, + "paths": { + "~/*": ["./vendor/t3code/apps/web/src/*"], + "@pierre/words/core": ["./node_modules/@pierre/words/dist/core.d.ts"] + } }, "include": [ "src", diff --git a/vendor/t3code b/vendor/t3code index 97e35bc..42c9107 160000 --- a/vendor/t3code +++ b/vendor/t3code @@ -1 +1 @@ -Subproject commit 97e35bcf23e4dcf34c2dcffadd37c08db0e01e52 +Subproject commit 42c9107983d8f65c38117501cbcde1ee5c82ef14