├── src ├── index.ts └── MPSInterfaceAdaptor │ ├── index.ts │ ├── replyNotice.ts │ ├── MatrixPromptForConfirmation.tsx │ ├── CommonRenderers.tsx │ ├── MPSMatrixInterfaceAdaptor.ts │ ├── MatrixPromptForAccept.tsx │ ├── MatrixReactionHandler.ts │ └── MatrixHelpRenderer.tsx ├── .github ├── renovate.json5 └── workflows │ ├── checks.yml │ └── release-package.yml ├── .prettierrc.yaml ├── eslint.config.mjs ├── tsconfig.json ├── .editorconfig ├── REUSE.toml ├── package.json ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── .gitignore └── LICENSES ├── CC0-1.0.txt ├── Apache-2.0.txt └── CC-BY-SA-4.0.txt /src/index.ts: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2025 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | export * from "./MPSInterfaceAdaptor"; 6 | -------------------------------------------------------------------------------- /.github/renovate.json5: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2024 Aminda Suomalainen 2 | // 3 | // SPDX-License-Identifier: CC0-1.0 4 | { 5 | extends: ["github>the-draupnir-project/.github:renovate-shared"], 6 | } 7 | -------------------------------------------------------------------------------- /.prettierrc.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Gnuxie 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | tabWidth: 2 6 | useTabs: false 7 | semi: true 8 | trailingComma: "es5" 9 | proseWrap: always 10 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2024 Gnuxie 2 | // 3 | // SPDX-License-Identifier: CC0-1.0 4 | 5 | import { gnuxieEslint } from "@gnuxie/tsconfig"; 6 | 7 | export default [ 8 | ...gnuxieEslint 9 | ]; 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@gnuxie/tsconfig/tsconfig.json", 3 | "compilerOptions": { 4 | "declarationDir": "dist", 5 | "jsx": "react", 6 | "jsxFactory": "DeadDocumentJSX.JSXFactory", 7 | "outDir": "dist", 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/index.ts: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2025 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | 5 | export * from "./CommonRenderers"; 6 | export * from "./MatrixHelpRenderer"; 7 | export * from "./MatrixPromptForAccept"; 8 | export * from "./MatrixPromptForConfirmation"; 9 | export * from "./MatrixReactionHandler"; 10 | export * from "./MPSMatrixInterfaceAdaptor"; 11 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Gnuxie 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | root = true 6 | 7 | [*] 8 | charset = utf-8 9 | indent_style = space 10 | indent_size = 2 11 | end_of_line = lf 12 | insert_final_newline = true 13 | trim_trailing_whitespace = true 14 | 15 | [LICENSES/**.txt] 16 | trim_trailing_whitespace = false 17 | indent_style = space 18 | indent_size = unset 19 | -------------------------------------------------------------------------------- /.github/workflows/checks.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Gnuxie 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | name: Checks 6 | 7 | on: 8 | push: 9 | branches: [main] 10 | pull_request: 11 | branches: [main] 12 | 13 | jobs: 14 | lint: 15 | name: Lint 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Specifically use node LTS. 20 | uses: actions/setup-node@v4 21 | with: 22 | node-version: "18" 23 | - run: npm install 24 | - run: npm run build 25 | - run: npm run lint 26 | -------------------------------------------------------------------------------- /.github/workflows/release-package.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Gnuxie 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | name: Node.js Package 6 | 7 | on: 8 | release: 9 | types: [created] 10 | 11 | jobs: 12 | publish-gpr: 13 | runs-on: ubuntu-latest 14 | permissions: 15 | packages: write 16 | contents: read 17 | steps: 18 | - uses: actions/checkout@v4 19 | - uses: actions/setup-node@v4 20 | with: 21 | node-version: 18 22 | registry-url: https://registry.npmjs.org 23 | - run: rm -rf node_modules && npm ci 24 | - run: npm publish --access public 25 | env: 26 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 27 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/replyNotice.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2025 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | // 5 | // SPDX-FileAttributionText: 6 | // This modified file incorporates work from Draupnir 7 | // https://github.com/the-draupnir-project/Draupnir 8 | // 9 | 10 | import { RoomMessageSender } from "matrix-protection-suite"; 11 | import { Result } from "@gnuxie/typescript-result"; 12 | import { 13 | StringEventID, 14 | StringRoomID, 15 | } from "@the-draupnir-project/matrix-basic-types"; 16 | 17 | export async function replyNoticeText( 18 | roomMessageSender: RoomMessageSender, 19 | roomID: StringRoomID, 20 | eventID: StringEventID, 21 | text: string 22 | ): Promise> { 23 | return await roomMessageSender.sendMessage(roomID, { 24 | body: text, 25 | msgtype: "m.notice", 26 | "m.relates_to": { 27 | "m.in_reply_to": { 28 | event_id: eventID, 29 | }, 30 | }, 31 | }); 32 | } 33 | -------------------------------------------------------------------------------- /REUSE.toml: -------------------------------------------------------------------------------- 1 | version = 1 2 | SPDX-PackageName = "@gnuxie/tsconfig" 3 | SPDX-PackageSupplier = "Gnuxie " 4 | SPDX-PackageDownloadLocation = "https://github.com/Gnuxie/tsconfig" 5 | 6 | [[annotations]] 7 | path = "REUSE.toml" 8 | precedence = "aggregate" 9 | SPDX-FileCopyrightText = "Gnuxie " 10 | SPDX-License-Identifier = "CC0-1.0" 11 | 12 | [[annotations]] 13 | path = "tsconfig.json" 14 | precedence = "aggregate" 15 | SPDX-FileCopyrightText = "Gnuxie " 16 | SPDX-License-Identifier = "CC0-1.0" 17 | 18 | [[annotations]] 19 | path = "package-lock.json" 20 | precedence = "aggregate" 21 | SPDX-FileCopyrightText = "Gnuxie " 22 | SPDX-License-Identifier = "CC0-1.0" 23 | 24 | [[annotations]] 25 | path = "yarn.lock" 26 | precedence = "aggregate" 27 | SPDX-FileCopyrightText = "Gnuxie " 28 | SPDX-License-Identifier = "CC0-1.0" 29 | 30 | [[annotations]] 31 | path = "package.json" 32 | precedence = "aggregate" 33 | SPDX-FileCopyrightText = "Gnuxie " 34 | SPDX-License-Identifier = "Apache-2.0" 35 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@the-draupnir-project/mps-interface-adaptor", 3 | "version": "0.5.3", 4 | "description": "", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "files": [ 8 | "dist" 9 | ], 10 | "scripts": { 11 | "build": "tsc --project tsconfig.json", 12 | "prepare": "npm run build", 13 | "lint": "eslint --cache src", 14 | "test": "echo \"Error: no test specified\" && exit 1" 15 | }, 16 | "author": { 17 | "name": "Gnuxie", 18 | "email": "Gnuxie@protonmail.com" 19 | }, 20 | "license": "Apache-2.0", 21 | "repository": { 22 | "url": "https://github.com/the-draupnir-project/mps-interface-adaptor.git", 23 | "type": "git" 24 | }, 25 | "private": false, 26 | "devDependencies": { 27 | "@eslint/js": "^9.28.0", 28 | "@gnuxie/tsconfig": "^2.1.0", 29 | "@types/node": "^20.17.57", 30 | "eslint": "^9.28.0", 31 | "typescript": "^5.8.3", 32 | "typescript-eslint": "^8.33.0" 33 | }, 34 | "peerDependencies": { 35 | "@gnuxie/typescript-result": "^1.0.0", 36 | "@sinclair/typebox": "^0.34.13", 37 | "@the-draupnir-project/interface-manager": "^4.2.3", 38 | "matrix-protection-suite": "npm:@gnuxie/matrix-protection-suite@^3.12.0" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Gnuxie 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | # See https://pre-commit.com for more information 6 | # See https://pre-commit.com/hooks.html for more hooks 7 | # See https://pre-commit.ci for more information 8 | ci: 9 | autoupdate_schedule: monthly 10 | skip: [yarn-lint] 11 | repos: 12 | - repo: https://github.com/pre-commit/pre-commit-hooks 13 | rev: v5.0.0 14 | hooks: 15 | - id: trailing-whitespace 16 | args: ["--markdown-linebreak-ext", "md"] 17 | exclude_types: [svg] 18 | - id: end-of-file-fixer 19 | - id: check-yaml 20 | - id: check-added-large-files 21 | - repo: https://github.com/editorconfig-checker/editorconfig-checker.python 22 | rev: "3.0.3" 23 | hooks: 24 | - id: editorconfig-checker 25 | alias: ec 26 | - repo: https://github.com/fsfe/reuse-tool 27 | rev: v4.0.3 28 | hooks: 29 | - id: reuse 30 | - repo: local 31 | hooks: 32 | - id: yarn-lint 33 | name: linter 34 | entry: npm run lint 35 | language: system 36 | - repo: https://github.com/python-jsonschema/check-jsonschema 37 | rev: 0.29.4 38 | hooks: 39 | - id: check-renovate 40 | additional_dependencies: ["pyjson5"] 41 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | # Changelog 8 | 9 | All notable changes to this project will be documented in this file. 10 | 11 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), 12 | and this project adheres to 13 | [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 14 | 15 | ## [0.5.3] - 2025-12-11 16 | 17 | ### Changed 18 | 19 | - Add an option to only show failed results in `renderRoomSetResult`. 20 | 21 | ## [0.5.2] - 2025-10-13 22 | 23 | ### Changed 24 | 25 | - Added some more logging in the `MatrixReactionHandler` when fetching the 26 | reaction map. 27 | 28 | ## [0.5.1] - 2025-09-29 29 | 30 | ### Added 31 | 32 | - Utility function to render errors to dead document nodes. 33 | 34 | ## [0.5.0] - 2025-09-25 35 | 36 | ### Changed 37 | 38 | - Updated MPS for new pagination API. 39 | 40 | ## [0.4.1] - 2025-06-03 41 | 42 | ### Fixed 43 | 44 | - Listeners for `ge.applied-langua.ge.draupnir.reaction_handler` were not being 45 | given the annotated event. And instead were being provided with a result 46 | object. 47 | 48 | ## [0.4.0] - 2025-06-03 49 | 50 | ### Changed 51 | 52 | - Previously we tried to install the matrix-protection-suite under it's scope 53 | `@gnuxie/matrix-protection-suite`. Unfortunatley, as far as we can tell, in 54 | Draupnir this peer dependency would not be satisfied unless we installed a 55 | duplicate package. Which we're just not going to do. So unfortunatley we will 56 | have to keep the name consistent with the other packages. 57 | 58 | ## [0.3.0] - 2025-06-03 59 | 60 | ### Changed 61 | 62 | - Forgot to add the `prepare` script smh. 63 | 64 | ## [0.2.0] - 2025-06-03 65 | 66 | ### Changed 67 | 68 | - Included package information. 69 | 70 | ## [0.1.0] - 2025-06-03 71 | 72 | - Initial release. 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Gnuxie 2 | # 3 | # SPDX-License-Identifier: CC0-1.0 4 | 5 | # Created by https://www.gitignore.io/api/node,macos,visualstudiocode 6 | # Edit at https://www.gitignore.io/?templates=node,macos,visualstudiocode 7 | 8 | ### macOS ### 9 | # General 10 | .DS_Store 11 | .AppleDouble 12 | .LSOverride 13 | 14 | # Icon must end with two \r 15 | Icon 16 | 17 | # Thumbnails 18 | ._* 19 | 20 | # Files that might appear in the root of a volume 21 | .DocumentRevisions-V100 22 | .fseventsd 23 | .Spotlight-V100 24 | .TemporaryItems 25 | .Trashes 26 | .VolumeIcon.icns 27 | .com.apple.timemachine.donotpresent 28 | 29 | # Directories potentially created on remote AFP share 30 | .AppleDB 31 | .AppleDesktop 32 | Network Trash Folder 33 | Temporary Items 34 | .apdisk 35 | 36 | ### Node ### 37 | # Logs 38 | logs 39 | *.log 40 | npm-debug.log* 41 | yarn-debug.log* 42 | yarn-error.log* 43 | lerna-debug.log* 44 | 45 | # Diagnostic reports (https://nodejs.org/api/report.html) 46 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 47 | 48 | # Runtime data 49 | pids 50 | *.pid 51 | *.seed 52 | *.pid.lock 53 | 54 | # Directory for instrumented libs generated by jscoverage/JSCover 55 | lib-cov 56 | 57 | # Coverage directory used by tools like istanbul 58 | coverage 59 | *.lcov 60 | 61 | # nyc test coverage 62 | .nyc_output 63 | 64 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 65 | .grunt 66 | 67 | # Bower dependency directory (https://bower.io/) 68 | bower_components 69 | 70 | # node-waf configuration 71 | .lock-wscript 72 | 73 | # Compiled binary addons (https://nodejs.org/api/addons.html) 74 | build/Release 75 | 76 | # Dependency directories 77 | node_modules/ 78 | jspm_packages/ 79 | 80 | # TypeScript v1 declaration files 81 | typings/ 82 | 83 | # TypeScript cache 84 | *.tsbuildinfo 85 | 86 | # Optional npm cache directory 87 | .npm 88 | 89 | # Optional eslint cache 90 | .eslintcache 91 | 92 | # Optional REPL history 93 | .node_repl_history 94 | 95 | # Output of 'npm pack' 96 | *.tgz 97 | 98 | # Yarn Integrity file 99 | .yarn-integrity 100 | 101 | # dotenv environment variables file 102 | .env 103 | .env.test 104 | 105 | # parcel-bundler cache (https://parceljs.org/) 106 | .cache 107 | 108 | # next.js build output 109 | .next 110 | 111 | # nuxt.js build output 112 | .nuxt 113 | 114 | # react / gatsby 115 | public/ 116 | 117 | # vuepress build output 118 | .vuepress/dist 119 | 120 | # Serverless directories 121 | .serverless/ 122 | 123 | # FuseBox cache 124 | .fusebox/ 125 | 126 | # DynamoDB Local files 127 | .dynamodb/ 128 | 129 | ### VisualStudioCode ### 130 | .vscode 131 | ### VisualStudioCode Patch ### 132 | # Ignore all local history of files 133 | .history 134 | 135 | # End of https://www.gitignore.io/api/node,macos,visualstudiocode 136 | 137 | docs 138 | dist 139 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/MatrixPromptForConfirmation.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2024 - 2025 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | // 5 | // SPDX-FileAttributionText: 6 | // This modified file incorporates work from Draupnir 7 | // https://github.com/the-draupnir-project/Draupnir 8 | // 9 | 10 | import { Result, isError } from "@gnuxie/typescript-result"; 11 | import { 12 | MatrixAdaptorContext, 13 | MatrixEventContext, 14 | sendMatrixEventsFromDeadDocument, 15 | } from "./MPSMatrixInterfaceAdaptor"; 16 | import { 17 | DocumentNode, 18 | MatrixInterfaceAdaptorCallbacks, 19 | MatrixInterfaceCommandDispatcher, 20 | TextPresentationRenderer, 21 | } from "@the-draupnir-project/interface-manager"; 22 | import { Logger, RoomEvent, Task, Value } from "matrix-protection-suite"; 23 | import { 24 | MatrixReactionHandler, 25 | ReactionListener, 26 | } from "./MatrixReactionHandler"; 27 | import { StringRoomID } from "@the-draupnir-project/matrix-basic-types"; 28 | import { 29 | CommandPromptContext, 30 | continueCommandAcceptingPrompt, 31 | } from "./MatrixPromptForAccept"; 32 | 33 | const log = new Logger("MatrixPromptForConfirmation"); 34 | 35 | export const COMMAND_CONFIRMATION_LISTENER = 36 | "me.marewolf.draupnir.command_confirmation"; 37 | 38 | export function makeConfirmationPromptListener( 39 | commandRoomID: StringRoomID, 40 | commandDispatcher: MatrixInterfaceCommandDispatcher, 41 | reactionHandler: MatrixReactionHandler 42 | ): ReactionListener { 43 | return (key, item, rawContext, _reactionMap, annotatedEvent) => { 44 | if (annotatedEvent.room_id !== commandRoomID) { 45 | return; 46 | } 47 | if (key === "Cancel") { 48 | void Task(reactionHandler.cancelPrompt(annotatedEvent)); 49 | return; 50 | } 51 | if (key !== "OK") { 52 | return; 53 | } 54 | const promptContext = Value.Decode(CommandPromptContext, rawContext); 55 | if (isError(promptContext)) { 56 | log.error( 57 | `malformed event context when trying to accept a prompted argument`, 58 | rawContext, 59 | promptContext.error 60 | ); 61 | return; 62 | } 63 | continueCommandAcceptingPrompt( 64 | { event: annotatedEvent, roomID: annotatedEvent.room_id }, 65 | promptContext.ok, 66 | "--no-confirm", 67 | commandDispatcher, 68 | reactionHandler 69 | ); 70 | }; 71 | } 72 | 73 | export type ConfirmationPromptSender = ( 74 | { 75 | commandDesignator, 76 | readItems, 77 | }: { commandDesignator: string[]; readItems: string[] }, 78 | document: DocumentNode, 79 | { 80 | roomID, 81 | event, 82 | }: { roomID?: StringRoomID | undefined; event?: RoomEvent | undefined } 83 | ) => Promise>; 84 | 85 | export function makeconfirmationPromptSender( 86 | adaptorContext: MatrixAdaptorContext 87 | ): ConfirmationPromptSender { 88 | return async function ( 89 | { commandDesignator, readItems }, 90 | document, 91 | { roomID, event } 92 | ) { 93 | return sendConfirmationPrompt( 94 | adaptorContext, 95 | { commandDesignator, readItems }, 96 | document, 97 | { roomID, event } 98 | ); 99 | }; 100 | } 101 | 102 | /** 103 | * This utility allows protections to send confirmation prompts that appear like confirmation prompts 104 | * for commands that have been sent without the `--no-confirm` option, but require confirmation. 105 | */ 106 | export async function sendConfirmationPrompt( 107 | { clientPlatform, reactionHandler }: MatrixAdaptorContext, 108 | { 109 | commandDesignator, 110 | readItems, 111 | }: { commandDesignator: string[]; readItems: string[] }, 112 | document: DocumentNode, 113 | { 114 | roomID, 115 | event, 116 | }: { roomID?: StringRoomID | undefined; event?: RoomEvent | undefined } 117 | ): Promise> { 118 | const roomIDToUse = roomID ?? event?.room_id; 119 | if (roomIDToUse === undefined) { 120 | throw new TypeError(`You must provide either a room ID or an event`); 121 | } 122 | const reactionMap = new Map( 123 | Object.entries({ OK: "OK", Cancel: "Cancel" }) 124 | ); 125 | const sendResult = await sendMatrixEventsFromDeadDocument( 126 | clientPlatform.toRoomMessageSender(), 127 | roomIDToUse, 128 | document, 129 | { 130 | replyToEvent: event, 131 | additionalContent: reactionHandler.createAnnotation( 132 | COMMAND_CONFIRMATION_LISTENER, 133 | reactionMap, 134 | { 135 | command_designator: commandDesignator, 136 | read_items: readItems, 137 | } 138 | ), 139 | } 140 | ); 141 | if (isError(sendResult)) { 142 | return sendResult as Result; 143 | } 144 | if (sendResult.ok[0] === undefined) { 145 | throw new TypeError(`We exepct to have sent at least one event`); 146 | } 147 | return await reactionHandler.addReactionsToEvent( 148 | roomIDToUse, 149 | sendResult.ok[0], 150 | reactionMap 151 | ); 152 | } 153 | 154 | export const matrixEventsFromConfirmationPrompt = async function ( 155 | adaptorContext, 156 | { event }, 157 | command, 158 | document 159 | ) { 160 | return await sendConfirmationPrompt( 161 | adaptorContext, 162 | { 163 | commandDesignator: command.designator, 164 | readItems: command 165 | .toPartialCommand() 166 | .stream.source.slice(command.designator.length) 167 | .map((p) => TextPresentationRenderer.render(p)), 168 | }, 169 | document, 170 | { event } 171 | ); 172 | } satisfies MatrixInterfaceAdaptorCallbacks< 173 | MatrixAdaptorContext, 174 | MatrixEventContext 175 | >["matrixEventsFromConfirmationPrompt"]; 176 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/CommonRenderers.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2022-2025 Gnuxie 2 | // Copyright 2019 2021 The Matrix.org Foundation C.I.C. 3 | // 4 | // SPDX-License-Identifier: Apache-2.0 5 | // 6 | // SPDX-FileAttributionText: 7 | // This modified file incorporates work from mjolnir 8 | // https://github.com/matrix-org/mjolnir 9 | // 10 | // SPDX-FileAttributionText: 11 | // This modified file incorporates work from Draupnir 12 | // https://github.com/the-draupnir-project/Draupnir 13 | // 14 | 15 | import { 16 | ActionError, 17 | ActionException, 18 | ActionResult, 19 | DescriptionMeta, 20 | ResultForUsersInRoom, 21 | RoomSetResult, 22 | isOk, 23 | } from "matrix-protection-suite"; 24 | import { 25 | StringRoomID, 26 | MatrixRoomReference, 27 | StringUserID, 28 | } from "@the-draupnir-project/matrix-basic-types"; 29 | import { 30 | DeadDocumentJSX, 31 | DocumentNode, 32 | } from "@the-draupnir-project/interface-manager"; 33 | import { renderMentionPill, renderRoomPill } from "./MatrixHelpRenderer"; 34 | 35 | export function renderElaborationTrail(error: ActionError): DocumentNode { 36 | return ( 37 |
38 | Elaboration trail 39 |
    40 | {error.getElaborations().map((elaboration) => ( 41 |
  • 42 |
    {elaboration}
    43 |
  • 44 | ))} 45 |
46 |
47 | ); 48 | } 49 | 50 | export function renderDetailsNotice(error: ActionError): DocumentNode { 51 | if (!(error instanceof ActionException)) { 52 | return ; 53 | } 54 | return ( 55 |

56 | Details can be found by providing the reference {error.uuid} 57 | to an administrator. 58 |

59 | ); 60 | } 61 | 62 | export function renderExceptionTrail(error: ActionError): DocumentNode { 63 | if (!(error instanceof ActionException)) { 64 | return ; 65 | } 66 | if (!(error.exception instanceof Error)) { 67 | return ; 68 | } 69 | return ( 70 |
71 | 72 | Stack Trace for: {error.exception.name} 73 | 74 |
{error.exception.toString()}
75 |
76 | ); 77 | } 78 | 79 | export function renderFailedSingularConsequence( 80 | description: DescriptionMeta, 81 | title: DocumentNode, 82 | error: ActionError 83 | ): DocumentNode { 84 | return ( 85 | 86 |
87 | 88 | {description.name}: {title} - {renderOutcome(false)} 89 | 90 | {error.mostRelevantElaboration} 91 | {renderDetailsNotice(error)} 92 | {renderElaborationTrail(error)} 93 | {renderExceptionTrail(error)} 94 |
95 |
96 | ); 97 | } 98 | 99 | export function renderOutcome(isOutcomeOk: boolean): DocumentNode { 100 | const colour = isOutcomeOk ? "#7cfc00" : "#E01F2B"; 101 | return ( 102 | 103 | {isOutcomeOk ? "OK" : "Failed"} 104 | 105 | ); 106 | } 107 | 108 | function renderRoomOutcomeOk(roomID: StringRoomID): DocumentNode { 109 | return ( 110 | 111 | {renderRoomPill(MatrixRoomReference.fromRoomID(roomID))} -{" "} 112 | {renderOutcome(true)} 113 | 114 | ); 115 | } 116 | 117 | function renderUserOutcomeOk( 118 | userID: StringUserID, 119 | _result: ActionResult 120 | ): DocumentNode { 121 | return ( 122 | 123 | {renderMentionPill(userID, userID)} - {renderOutcome(true)} 124 | 125 | ); 126 | } 127 | 128 | function renderOutcomeError( 129 | summary: DocumentNode, 130 | error: ActionError 131 | ): DocumentNode { 132 | return ( 133 | 134 |
135 | {summary} 136 | {renderDetailsNotice(error)} 137 | {renderElaborationTrail(error)} 138 | {renderExceptionTrail(error)} 139 |
140 |
141 | ); 142 | } 143 | 144 | function renderRoomOutcomeError( 145 | roomID: StringRoomID, 146 | error: ActionError 147 | ): DocumentNode { 148 | return renderOutcomeError( 149 | 150 | {renderRoomPill(MatrixRoomReference.fromRoomID(roomID))} -{" "} 151 | {renderOutcome(false)}: {error.mostRelevantElaboration} 152 | , 153 | error 154 | ); 155 | } 156 | 157 | function renderUserOutcomeError( 158 | userID: StringUserID, 159 | error: ActionError 160 | ): DocumentNode { 161 | return renderOutcomeError( 162 | 163 | {renderMentionPill(userID, userID)} - {renderOutcome(false)} 164 | , 165 | error 166 | ); 167 | } 168 | 169 | export function renderRoomOutcome( 170 | roomID: StringRoomID, 171 | result: ActionResult 172 | ): DocumentNode { 173 | if (isOk(result)) { 174 | return renderRoomOutcomeOk(roomID); 175 | } else { 176 | return renderRoomOutcomeError(roomID, result.error); 177 | } 178 | } 179 | 180 | export function renderUserOutcome( 181 | userID: StringUserID, 182 | result: ActionResult 183 | ): DocumentNode { 184 | if (isOk(result)) { 185 | return renderUserOutcomeOk(userID, result); 186 | } else { 187 | return renderUserOutcomeError(userID, result.error); 188 | } 189 | } 190 | 191 | export function renderRoomSetResult( 192 | roomResults: RoomSetResult, 193 | { 194 | summary, 195 | showOnlyFailed, 196 | }: { summary: DocumentNode; showOnlyFailed?: boolean } 197 | ): DocumentNode { 198 | return ( 199 |
200 | {summary} 201 |
    202 | {[...roomResults.map.entries()] 203 | .filter((entry) => (showOnlyFailed ? !entry[1].isOkay : true)) 204 | .map(([roomID, outcome]) => { 205 | return
  • {renderRoomOutcome(roomID, outcome)}
  • ; 206 | })} 207 |
208 |
209 | ); 210 | } 211 | 212 | export function renderResultForUsersInRoom( 213 | results: ResultForUsersInRoom, 214 | { summary }: { summary: DocumentNode } 215 | ): DocumentNode { 216 | return ( 217 |
218 | {summary} 219 |
    220 | {[...results.map.entries()].map(([userID, outcome]) => ( 221 |
  • {renderUserOutcome(userID, outcome)}
  • 222 | ))} 223 |
224 |
225 | ); 226 | } 227 | -------------------------------------------------------------------------------- /LICENSES/CC0-1.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/MPSMatrixInterfaceAdaptor.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2023 - 2025 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | // 5 | // SPDX-FileAttributionText: 6 | // This modified file incorporates work from Draupnir 7 | // https://github.com/the-draupnir-project/Draupnir 8 | // 9 | 10 | import { 11 | StringEventID, 12 | StringRoomID, 13 | StringUserID, 14 | } from "@the-draupnir-project/matrix-basic-types"; 15 | import { 16 | ActionException, 17 | ActionExceptionKind, 18 | ActionResult, 19 | ClientPlatform, 20 | Logger, 21 | Ok, 22 | RoomEvent, 23 | RoomMessageSender, 24 | isError, 25 | } from "matrix-protection-suite"; 26 | import { MatrixReactionHandler } from "./MatrixReactionHandler"; 27 | import { 28 | BasicInvocationInformation, 29 | CommandDispatcherCallbacks, 30 | DocumentNode, 31 | InvocationInformationFromEventContext, 32 | MatrixInterfaceAdaptorCallbacks, 33 | MatrixInterfaceEventsFromDeadDocument, 34 | MatrixInterfaceRendererFailedCB, 35 | StandardAdaptorContextToCommandContextTranslator, 36 | StandardMatrixInterfaceAdaptor, 37 | TextPresentationRenderer, 38 | renderMatrix, 39 | } from "@the-draupnir-project/interface-manager"; 40 | import { matrixCommandRenderer } from "./MatrixHelpRenderer"; 41 | import { promptDefault, promptSuggestions } from "./MatrixPromptForAccept"; 42 | import { Result } from "@gnuxie/typescript-result"; 43 | import { matrixEventsFromConfirmationPrompt } from "./MatrixPromptForConfirmation"; 44 | 45 | export interface MatrixEventContext { 46 | roomID: StringRoomID; 47 | event: RoomEvent; 48 | } 49 | 50 | export type MatrixAdaptorContext = { 51 | readonly clientPlatform: ClientPlatform; 52 | readonly clientUserID: StringUserID; 53 | readonly reactionHandler: MatrixReactionHandler; 54 | readonly commandRoomID: StringRoomID; 55 | }; 56 | 57 | export async function sendMatrixEventsFromDeadDocument( 58 | messageSender: RoomMessageSender, 59 | roomID: StringRoomID, 60 | document: DocumentNode, 61 | { 62 | replyToEvent, 63 | additionalContent = {}, 64 | }: { 65 | replyToEvent?: undefined | RoomEvent; 66 | additionalContent?: Record; 67 | } 68 | ): Promise> { 69 | const baseContent = (text: string, html: string) => { 70 | return { 71 | msgtype: "m.notice", 72 | body: text, 73 | format: "org.matrix.custom.html", 74 | formatted_body: html, 75 | }; 76 | }; 77 | const renderInitialReply = async ( 78 | text: string, 79 | html: string 80 | ): Promise> => { 81 | return await messageSender.sendMessage(roomID, { 82 | ...baseContent(text, html), 83 | ...additionalContent, 84 | ...(replyToEvent === undefined 85 | ? {} // if they don't supply a reply just send a top level event. 86 | : { 87 | "m.relates_to": { 88 | "m.in_reply_to": { 89 | event_id: replyToEvent["event_id"], 90 | }, 91 | }, 92 | }), 93 | }); 94 | }; 95 | const renderThreadReply = async ( 96 | eventId: string, 97 | text: string, 98 | html: string 99 | ) => { 100 | return await messageSender.sendMessage(roomID, { 101 | ...baseContent(text, html), 102 | "m.relates_to": { 103 | rel_type: "m.thread", 104 | event_id: eventId, 105 | }, 106 | }); 107 | }; 108 | let initialReplyEventID: StringEventID | undefined = undefined; 109 | return await renderMatrix( 110 | document, 111 | async ( 112 | text: string, 113 | html: string 114 | ): Promise> => { 115 | if (initialReplyEventID === undefined) { 116 | const replyResult = await renderInitialReply(text, html); 117 | if (isError(replyResult)) { 118 | return replyResult; 119 | } else { 120 | initialReplyEventID = replyResult.ok; 121 | return replyResult; 122 | } 123 | } else { 124 | return await renderThreadReply(initialReplyEventID, text, html); 125 | } 126 | } 127 | ); 128 | } 129 | 130 | export const matrixEventsFromDeadDocument: MatrixInterfaceEventsFromDeadDocument< 131 | MatrixAdaptorContext, 132 | MatrixEventContext 133 | > = async function matrixEventsFromDeadDocument( 134 | { clientPlatform }, 135 | { event }, 136 | document 137 | ) { 138 | const sendResult = await sendMatrixEventsFromDeadDocument( 139 | clientPlatform.toRoomMessageSender(), 140 | event.room_id, 141 | document, 142 | { replyToEvent: event } 143 | ); 144 | if (isError(sendResult)) { 145 | return sendResult as Result; 146 | } else { 147 | return Ok(undefined); 148 | } 149 | }; 150 | 151 | const log = new Logger("MPSInterfaceAdaptor"); 152 | 153 | export const MPSCommandDispatcherCallbacks = { 154 | commandFailedCB(_info, command, error) { 155 | log.error( 156 | `The command "${command.designator.join(" ")}" returned with an error:`, 157 | error 158 | ); 159 | }, 160 | commandUncaughtErrorCB(info, body, error) { 161 | log.error( 162 | `Caught an unexpcted error when attempting to process the command "${body}" send by the user ${info.commandSender}:`, 163 | error 164 | ); 165 | }, 166 | logCurrentCommandCB(info, commandParts) { 167 | log.info( 168 | `Command being processed for ${info.commandSender}:`, 169 | ...commandParts.map( 170 | TextPresentationRenderer.render.bind(TextPresentationRenderer) 171 | ) 172 | ); 173 | }, 174 | convertUncaughtErrorToResultError(error) { 175 | return new ActionException( 176 | ActionExceptionKind.Unknown, 177 | error, 178 | error.message 179 | ); 180 | }, 181 | commandNormaliser(body) { 182 | return body; 183 | }, 184 | } satisfies CommandDispatcherCallbacks; 185 | 186 | export const rendererFailedCB: MatrixInterfaceRendererFailedCB< 187 | MatrixAdaptorContext, 188 | MatrixEventContext 189 | > = function (_adaptor, _eventContext, command, rendererError) { 190 | log.error( 191 | `A renderer for the command "${command.designator.join( 192 | " " 193 | )}" returned with an error:`, 194 | rendererError 195 | ); 196 | }; 197 | 198 | export const MPSMatrixInterfaceAdaptorCallbacks = Object.freeze({ 199 | promptDefault, 200 | promptSuggestions, 201 | defaultRenderer: matrixCommandRenderer, 202 | matrixEventsFromDeadDocument, 203 | rendererFailedCB, 204 | matrixEventsFromConfirmationPrompt, 205 | }) satisfies MatrixInterfaceAdaptorCallbacks< 206 | MatrixAdaptorContext, 207 | MatrixEventContext 208 | >; 209 | 210 | export const invocationInformationFromMatrixEventcontext: InvocationInformationFromEventContext = 211 | function (eventContext) { 212 | return { 213 | commandEventID: eventContext.event.event_id, 214 | commandSender: eventContext.event.sender, 215 | }; 216 | }; 217 | 218 | export const MPSContextToCommandContextTranslator = 219 | new StandardAdaptorContextToCommandContextTranslator(); 220 | 221 | export const MPSMatrixInterfaceAdaptor = new StandardMatrixInterfaceAdaptor< 222 | MatrixAdaptorContext, 223 | MatrixEventContext 224 | >( 225 | MPSContextToCommandContextTranslator, 226 | invocationInformationFromMatrixEventcontext, 227 | MPSMatrixInterfaceAdaptorCallbacks, 228 | MPSCommandDispatcherCallbacks 229 | ); 230 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/MatrixPromptForAccept.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | // 5 | // SPDX-FileAttributionText: 6 | // This modified file incorporates work from Draupnir 7 | // https://github.com/the-draupnir-project/Draupnir 8 | // 9 | 10 | import { Logger, Task, Value, isError } from "matrix-protection-suite"; 11 | import { 12 | MatrixReactionHandler, 13 | ReactionListener, 14 | } from "./MatrixReactionHandler"; 15 | import { StaticDecode, Type } from "@sinclair/typebox"; 16 | import { 17 | MatrixAdaptorContext, 18 | MatrixEventContext, 19 | sendMatrixEventsFromDeadDocument, 20 | } from "./MPSMatrixInterfaceAdaptor"; 21 | import { 22 | DeadDocumentJSX, 23 | MatrixInterfaceCommandDispatcher, 24 | ParameterDescription, 25 | PartialCommand, 26 | Presentation, 27 | StandardPresentationArgumentStream, 28 | TextPresentationRenderer, 29 | readCommand, 30 | } from "@the-draupnir-project/interface-manager"; 31 | import { Ok, Result } from "@gnuxie/typescript-result"; 32 | import { StringRoomID } from "@the-draupnir-project/matrix-basic-types"; 33 | 34 | const log = new Logger("MatrixPromptForAccept"); 35 | 36 | export type CommandPromptContext = StaticDecode; 37 | 38 | export const CommandPromptContext = Type.Object({ 39 | command_designator: Type.Array(Type.String()), 40 | read_items: Type.Array(Type.String()), 41 | }); 42 | 43 | type DefaultPromptContext = StaticDecode; 44 | 45 | const DefaultPromptContext = Type.Composite([ 46 | CommandPromptContext, 47 | Type.Object({ 48 | default: Type.String(), 49 | }), 50 | ]); 51 | 52 | export function continueCommandAcceptingPrompt( 53 | eventContext: MatrixEventContext, 54 | promptContext: CommandPromptContext, 55 | serializedPrompt: string, 56 | commandDispatcher: MatrixInterfaceCommandDispatcher, 57 | reactionHandler: MatrixReactionHandler 58 | ): void { 59 | const stream = new StandardPresentationArgumentStream( 60 | readCommand( 61 | [ 62 | ...promptContext.command_designator, 63 | ...promptContext.read_items, 64 | serializedPrompt, 65 | ].join(" ") 66 | ) 67 | ); 68 | commandDispatcher.handleCommandFromPresentationStream(eventContext, stream); 69 | void Task( 70 | reactionHandler.completePrompt( 71 | eventContext.roomID, 72 | eventContext.event.event_id 73 | ) 74 | ); 75 | } 76 | 77 | export const DEFAUILT_ARGUMENT_PROMPT_LISTENER = 78 | "ge.applied-langua.ge.draupnir.default_argument_prompt"; 79 | export function makeListenerForPromptDefault( 80 | commandRoomID: StringRoomID, 81 | commandDispatcher: MatrixInterfaceCommandDispatcher, 82 | reactionHandler: MatrixReactionHandler 83 | ): ReactionListener { 84 | return function (reactionKey, item, context, reactionMap, annotatedEvent) { 85 | if (annotatedEvent.room_id !== commandRoomID) { 86 | return; 87 | } 88 | if (item !== "ok") { 89 | return; 90 | } 91 | const promptContext = Value.Decode(DefaultPromptContext, context); 92 | if (isError(promptContext)) { 93 | log.error( 94 | `malformed event context when trying to accept a default prompt`, 95 | context 96 | ); 97 | return; 98 | } 99 | continueCommandAcceptingPrompt( 100 | { event: annotatedEvent, roomID: annotatedEvent.room_id }, 101 | promptContext.ok, 102 | item, 103 | commandDispatcher, 104 | reactionHandler 105 | ); 106 | }; 107 | } 108 | 109 | export const ARGUMENT_PROMPT_LISTENER = 110 | "ge.applied-langua.ge.draupnir.argument_prompt"; 111 | export function makeListenerForArgumentPrompt( 112 | commandRoomID: StringRoomID, 113 | commandDispatcher: MatrixInterfaceCommandDispatcher, 114 | reactionHandler: MatrixReactionHandler 115 | ): ReactionListener { 116 | return function (reactionKey, item, context, reactionMap, annotatedEvent) { 117 | if (annotatedEvent.room_id !== commandRoomID) { 118 | return; 119 | } 120 | const promptContext = Value.Decode(CommandPromptContext, context); 121 | if (isError(promptContext)) { 122 | log.error( 123 | `malformed event context when trying to accept a prompted argument`, 124 | context 125 | ); 126 | return; 127 | } 128 | continueCommandAcceptingPrompt( 129 | { event: annotatedEvent, roomID: annotatedEvent.room_id }, 130 | promptContext.ok, 131 | item, 132 | commandDispatcher, 133 | reactionHandler 134 | ); 135 | }; 136 | } 137 | 138 | export async function promptDefault( 139 | { clientPlatform, reactionHandler }: MatrixAdaptorContext, 140 | eventContext: MatrixEventContext, 141 | parameter: ParameterDescription, 142 | command: PartialCommand, 143 | defaultPrompt: TPresentation, 144 | existingArguments: Presentation[] 145 | ): Promise> { 146 | const reactionMap = new Map( 147 | Object.entries({ 148 | Ok: "ok", 149 | }) 150 | ); 151 | const sendResult = await sendMatrixEventsFromDeadDocument( 152 | clientPlatform.toRoomMessageSender(), 153 | eventContext.event.room_id, 154 | 155 | No argument was provided for the parameter {parameter.name}, would you 156 | like to accept the default? 157 |
158 | {TextPresentationRenderer.render(defaultPrompt)} 159 |
, 160 | { 161 | replyToEvent: eventContext.event, 162 | additionalContent: reactionHandler.createAnnotation( 163 | DEFAUILT_ARGUMENT_PROMPT_LISTENER, 164 | reactionMap, 165 | { 166 | command_designator: command.designator, 167 | read_items: existingArguments.map((p) => 168 | TextPresentationRenderer.render(p) 169 | ), 170 | default: TextPresentationRenderer.render(defaultPrompt), 171 | } 172 | ), 173 | } 174 | ); 175 | if (isError(sendResult)) { 176 | return sendResult; 177 | } 178 | if (sendResult.ok[0] === undefined) { 179 | throw new TypeError(`Something is really wrong with the code`); 180 | } 181 | await reactionHandler.addReactionsToEvent( 182 | eventContext.event.room_id, 183 | sendResult.ok[0], 184 | reactionMap 185 | ); 186 | return Ok(undefined); 187 | } 188 | 189 | // FIXME:
    raw tags will not work if the message is sent across events. 190 | // If there isn't a start attribute for `ol` then we'll need to take this into our own hands. 191 | export async function promptSuggestions( 192 | { clientPlatform, reactionHandler }: MatrixAdaptorContext, 193 | eventContext: MatrixEventContext, 194 | parameter: ParameterDescription, 195 | command: PartialCommand, 196 | suggestions: TPresentation[], 197 | existingArguments: Presentation[] 198 | ): Promise> { 199 | const reactionMap = MatrixReactionHandler.createItemizedReactionMap( 200 | suggestions.map((suggestion) => TextPresentationRenderer.render(suggestion)) 201 | ); 202 | const sendResult = await sendMatrixEventsFromDeadDocument( 203 | clientPlatform.toRoomMessageSender(), 204 | eventContext.event.room_id, 205 | 206 | Please select one of the following options to provide as an argument for 207 | the parameter {parameter.name}: 208 |
      209 | {suggestions.map((suggestion) => { 210 | return
    1. {TextPresentationRenderer.render(suggestion)}
    2. ; 211 | })} 212 |
    213 |
    , 214 | { 215 | replyToEvent: eventContext.event, 216 | additionalContent: reactionHandler.createAnnotation( 217 | ARGUMENT_PROMPT_LISTENER, 218 | reactionMap, 219 | { 220 | command_designator: command.designator, 221 | read_items: existingArguments.map((p) => 222 | TextPresentationRenderer.render(p) 223 | ), 224 | } 225 | ), 226 | } 227 | ); 228 | if (isError(sendResult)) { 229 | return sendResult; 230 | } 231 | if (sendResult.ok[0] === undefined) { 232 | throw new TypeError(`Something is really wrong with the code`); 233 | } 234 | await reactionHandler.addReactionsToEvent( 235 | eventContext.event.room_id, 236 | sendResult.ok[0], 237 | reactionMap 238 | ); 239 | return Ok(undefined); 240 | } 241 | -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 30 | 31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 32 | 33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 34 | 35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and 36 | 37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and 38 | 39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | 41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 42 | 43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 44 | 45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 46 | 47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 48 | 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 52 | 53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 54 | 55 | END OF TERMS AND CONDITIONS 56 | 57 | APPENDIX: How to apply the Apache License to your work. 58 | 59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. 60 | 61 | Copyright [yyyy] [name of copyright owner] 62 | 63 | Licensed under the Apache License, Version 2.0 (the "License"); 64 | you may not use this file except in compliance with the License. 65 | You may obtain a copy of the License at 66 | 67 | http://www.apache.org/licenses/LICENSE-2.0 68 | 69 | Unless required by applicable law or agreed to in writing, software 70 | distributed under the License is distributed on an "AS IS" BASIS, 71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 72 | See the License for the specific language governing permissions and 73 | limitations under the License. 74 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/MatrixReactionHandler.ts: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2023 - 2025 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | // 5 | // SPDX-FileAttributionText: 6 | // This modified file incorporates work from Draupnir 7 | // https://github.com/the-draupnir-project/Draupnir 8 | // 9 | 10 | import { EventEmitter } from "events"; 11 | import { 12 | ActionResult, 13 | ClientPlatform, 14 | Logger, 15 | ReactionContent, 16 | ReactionEvent, 17 | RoomEvent, 18 | Task, 19 | Value, 20 | isError, 21 | } from "matrix-protection-suite"; 22 | import { 23 | StringRoomID, 24 | StringUserID, 25 | StringEventID, 26 | } from "@the-draupnir-project/matrix-basic-types"; 27 | import { Ok, Result } from "@gnuxie/typescript-result"; 28 | import { Type } from "@sinclair/typebox"; 29 | 30 | const log = new Logger("MatrixReactionHandler"); 31 | 32 | const REACTION_ANNOTATION_KEY = 33 | "ge.applied-langua.ge.draupnir.reaction_handler"; 34 | 35 | type ItemByReactionKey = Map< 36 | string /*reaction key*/, 37 | string /*serialized presentation*/ 38 | >; 39 | export type ReactionListener = ( 40 | key: string, 41 | item: string, 42 | additionalContext: unknown, 43 | reactionMap: ItemByReactionKey, 44 | annotatedEvent: RoomEvent 45 | ) => void; 46 | 47 | export declare interface MatrixReactionHandlerListeners { 48 | on(eventName: string, listener: ReactionListener): void; 49 | emit(eventName: string, ...args: Parameters): void; 50 | } 51 | 52 | export const ReactionAnnotatedContent = Type.Object({ 53 | [REACTION_ANNOTATION_KEY]: Type.Object({ 54 | reaction_map: Type.Record( 55 | Type.String({ description: "The reaction key" }), 56 | Type.String({ description: "A value associated with the reaction key" }) 57 | ), 58 | name: Type.String({ 59 | description: 60 | "The name of the listener this reaction annotation is associated witih", 61 | }), 62 | additional_context: Type.Optional(Type.Unknown()), 63 | }), 64 | }); 65 | 66 | /** 67 | * A utility that can be associated with an `MatrixEmitter` to listen for 68 | * reactions to Matrix Events. The aim is to simplify reaction UX. 69 | */ 70 | export class MatrixReactionHandler 71 | extends EventEmitter 72 | implements MatrixReactionHandlerListeners 73 | { 74 | public constructor( 75 | /** 76 | * The room the handler is for. Cannot be enabled for every room as the 77 | * OG event lookup is very slow. So usually draupnir's management room. 78 | */ 79 | public readonly roomID: StringRoomID, 80 | /** 81 | * The user id of the client. Ignores reactions from this user 82 | */ 83 | private readonly clientUserID: StringUserID, 84 | private readonly clientPlatform: ClientPlatform 85 | ) { 86 | super(); 87 | } 88 | 89 | /** 90 | * Handle an event from a `MatrixEmitter` and see if it is a reaction to 91 | * a previously annotated event. If it is a reaction to an annotated event, 92 | * then call its associated listener. 93 | * @param roomID The room the event took place in. 94 | * @param event The Matrix event. 95 | */ 96 | public async handleEvent( 97 | roomID: StringRoomID, 98 | event: RoomEvent 99 | ): Promise { 100 | if (roomID !== this.roomID) { 101 | return; 102 | } 103 | if (roomID !== event.room_id) { 104 | throw new TypeError( 105 | "The MatrixReactionHandler is being used incorrectly" 106 | ); 107 | } 108 | if (event.sender === this.clientUserID) { 109 | return; 110 | } 111 | if (!Value.Check(ReactionContent, event.content)) { 112 | return; 113 | } 114 | const relatesTo = event.content["m.relates_to"]; 115 | if (relatesTo === undefined) { 116 | return; 117 | } 118 | const reactionKey = relatesTo["key"]; 119 | const relatedEventId = relatesTo["event_id"]; 120 | if ( 121 | !(typeof relatedEventId === "string" && typeof reactionKey === "string") 122 | ) { 123 | return; 124 | } 125 | const annotatedEvent = await this.clientPlatform 126 | .toRoomEventGetter() 127 | .getEvent(roomID, relatedEventId); 128 | if (isError(annotatedEvent)) { 129 | log.error( 130 | "Unable to get annotated event", 131 | roomID, 132 | relatedEventId, 133 | annotatedEvent.error 134 | ); 135 | return; 136 | } 137 | if (!(REACTION_ANNOTATION_KEY in annotatedEvent.ok.content)) { 138 | return; // this event isn't annotated. 139 | } 140 | const decodedAnnotation = Value.Decode( 141 | ReactionAnnotatedContent, 142 | annotatedEvent.ok.content 143 | ); 144 | if (isError(decodedAnnotation)) { 145 | log.error( 146 | `Unable to decode the annotation on an annotated event that was reacted to ${relatedEventId} in ${roomID}`, 147 | decodedAnnotation.error 148 | ); 149 | return; 150 | } 151 | const reactionMap = 152 | decodedAnnotation.ok[REACTION_ANNOTATION_KEY].reaction_map; 153 | const listenerName = decodedAnnotation.ok[REACTION_ANNOTATION_KEY].name; 154 | const association = reactionKey in reactionMap && reactionMap[reactionKey]; 155 | if (association === undefined) { 156 | log.info( 157 | `There wasn't a defined key for ${reactionKey} on event ${relatedEventId} in ${roomID}` 158 | ); 159 | return; 160 | } 161 | this.emit( 162 | listenerName, 163 | reactionKey, 164 | association, 165 | decodedAnnotation.ok[REACTION_ANNOTATION_KEY]["additional_context"], 166 | new Map(Object.entries(reactionMap)), 167 | annotatedEvent.ok 168 | ); 169 | } 170 | 171 | /** 172 | * Create the annotation required to setup a listener for when a reaction is encountered for the list. 173 | * @param listenerName The name of the event to emit when a reaction is encountered for a matrix event that matches a key in the `reactionMap`. 174 | * @param reactionMap A map of reaction keys to items that will be provided to the listener. 175 | * @param additionalContext Any additional context that should be associated with a matrix event for the listener. 176 | * @returns An object that should be deep copied into a the content of a new Matrix event. 177 | */ 178 | public createAnnotation( 179 | listenerName: string, 180 | reactionMap: ItemByReactionKey, 181 | additionalContext: Record | undefined = undefined 182 | ): Record { 183 | return { 184 | [REACTION_ANNOTATION_KEY]: { 185 | name: listenerName, 186 | reaction_map: Object.fromEntries(reactionMap), 187 | additional_context: additionalContext, 188 | }, 189 | }; 190 | } 191 | 192 | /** 193 | * Use a reaction map to create the initial reactions to an event so that the user has access to quick reactions. 194 | * @param client A client to add the reactions with. 195 | * @param roomID The room id of the event to add the reactions to. 196 | * @param eventID The event id of the event to add reactions to. 197 | * @param reactionMap The reaction map. 198 | */ 199 | public async addReactionsToEvent( 200 | roomID: StringRoomID, 201 | eventID: StringEventID, 202 | reactionMap: ItemByReactionKey 203 | ): Promise> { 204 | for (const key of reactionMap.keys()) { 205 | const reactionResult = await this.clientPlatform 206 | .toRoomReactionSender() 207 | .sendReaction(roomID, eventID, key); 208 | if (isError(reactionResult)) { 209 | log.error( 210 | `Could not add reaction to event ${eventID}`, 211 | reactionResult.error 212 | ); 213 | return reactionResult; 214 | } 215 | } 216 | return Ok(undefined); 217 | } 218 | 219 | public async completePrompt( 220 | roomID: StringRoomID, 221 | eventID: StringEventID, 222 | reason?: string 223 | ): Promise> { 224 | const redacter = this.clientPlatform.toRoomEventRedacter(); 225 | return await this.clientPlatform 226 | .toRoomEventRelations() 227 | .toRoomEventRelationsIterator(roomID, eventID, { 228 | relationType: "m.annotation", 229 | eventType: "m.reaction", 230 | direction: "backwards", 231 | limit: 100, 232 | }) 233 | .forEachItem({ 234 | forEachItemCB: (event) => { 235 | if (!Value.Check(ReactionContent, event.content)) { 236 | return; 237 | } 238 | const key = event.content["m.relates_to"]?.key; 239 | // skip the bots own reactions that mark the event as complete 240 | if (key === "✅" || key === "❌") { 241 | return; 242 | } 243 | void Task( 244 | redacter.redactEvent(roomID, event.event_id, reason) as Promise< 245 | ActionResult 246 | > 247 | ); 248 | }, 249 | }); 250 | } 251 | 252 | /** 253 | * Removes all reactions from the prompt event in an attempt to stop it being used further. 254 | */ 255 | public async cancelPrompt( 256 | promptEvent: RoomEvent, 257 | cancelReason?: string 258 | ): Promise> { 259 | const completeResult = await this.completePrompt( 260 | promptEvent.room_id, 261 | promptEvent.event_id, 262 | cancelReason ?? "prompt cancelled" 263 | ); 264 | if (isError(completeResult)) { 265 | return completeResult; 266 | } 267 | const reactionResult = await this.clientPlatform 268 | .toRoomReactionSender() 269 | .sendReaction( 270 | promptEvent.room_id, 271 | promptEvent.event_id, 272 | `🚫 Cancelled by ${promptEvent.sender}` 273 | ); 274 | if (isError(reactionResult)) { 275 | log.error( 276 | `Could not send cancelled reaction event for prompt ${promptEvent.event_id} in ${promptEvent.room_id}`, 277 | reactionResult.error 278 | ); 279 | } 280 | return completeResult; 281 | } 282 | 283 | public static createItemizedReactionMap(items: string[]): ItemByReactionKey { 284 | return items.reduce((acc, item, index) => { 285 | const key = MatrixReactionHandler.numberToEmoji(index + 1); 286 | acc.set(key, item); 287 | return acc; 288 | }, new Map()); 289 | } 290 | 291 | public static numberToEmoji(number: number): string { 292 | // https://github.com/anton-bot/number-to-emoji 293 | // licensed with unlicense. 294 | const key = number.toString(); 295 | return key 296 | .replace(/0/g, "0️⃣") 297 | .replace(/1/g, "1️⃣") 298 | .replace(/2/g, "2️⃣") 299 | .replace(/3/g, "3️⃣") 300 | .replace(/4/g, "4️⃣") 301 | .replace(/5/g, "5️⃣") 302 | .replace(/6/g, "6️⃣") 303 | .replace(/7/g, "7️⃣") 304 | .replace(/8/g, "8️⃣") 305 | .replace(/9/g, "9️⃣"); 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /src/MPSInterfaceAdaptor/MatrixHelpRenderer.tsx: -------------------------------------------------------------------------------- 1 | // Copyright 2022 - 2025 Gnuxie 2 | // 3 | // SPDX-License-Identifier: Apache-2.0 4 | // 5 | // SPDX-FileAttributionText: 6 | // This modified file incorporates work from Draupnir 7 | // https://github.com/the-draupnir-project/Draupnir 8 | // 9 | 10 | import { 11 | ActionError, 12 | ActionException, 13 | ActionResult, 14 | Logger, 15 | Ok, 16 | RoomEvent, 17 | RoomMessageSender, 18 | Task, 19 | isError, 20 | isOk, 21 | } from "matrix-protection-suite"; 22 | import { MatrixRoomReference } from "@the-draupnir-project/matrix-basic-types"; 23 | import { 24 | ArgumentParseError, 25 | CommandDescription, 26 | BaseCommandTableEntry, 27 | DeadDocumentJSX, 28 | DocumentNode, 29 | ParameterDescription, 30 | RestDescription, 31 | TextPresentationRenderer, 32 | CommandTable, 33 | Command, 34 | CommandTableEntry, 35 | LeafNode, 36 | UnexpectedArgumentError, 37 | } from "@the-draupnir-project/interface-manager"; 38 | import { 39 | MatrixAdaptorContext, 40 | MatrixEventContext, 41 | sendMatrixEventsFromDeadDocument, 42 | } from "./MPSMatrixInterfaceAdaptor"; 43 | import { Result } from "@gnuxie/typescript-result"; 44 | import { printPresentationSchema } from "@the-draupnir-project/interface-manager/dist/Command/PresentationSchema"; 45 | import { RoomReactionSender } from "matrix-protection-suite/dist/Client/RoomReactionSender"; 46 | import { replyNoticeText } from "./replyNotice"; 47 | import { 48 | renderDetailsNotice, 49 | renderElaborationTrail, 50 | renderExceptionTrail, 51 | } from "./CommonRenderers"; 52 | 53 | const log = new Logger("MatrixHelpRenderer"); 54 | 55 | function requiredArgument(argumentName: string): string { 56 | return `<${argumentName}>`; 57 | } 58 | 59 | function keywordArgument(keyword: string): string { 60 | // ahh fuck what about defaults for keys? 61 | return `[--${keyword}]`; 62 | } 63 | 64 | // they should be allowed to name the rest argument... 65 | function restArgument(rest: RestDescription): string { 66 | return `[...${rest.name}]`; 67 | } 68 | 69 | export function renderParameterDescription( 70 | description: ParameterDescription 71 | ): DocumentNode { 72 | return ( 73 | 74 | {description.name} - {description.description ?? "no description"} 75 |
    76 |
    77 | ); 78 | } 79 | 80 | export function renderCommandSummary( 81 | command: CommandDescription, 82 | tableEntry: BaseCommandTableEntry 83 | ): DocumentNode { 84 | return ( 85 |
    86 | 87 | {renderCommandHelp(command, tableEntry.designator)} -{" "} 88 | {command.summary} 89 | 90 | {command.description ? ( 91 | 92 | Description: 93 |
    94 | {command.description} 95 |
    96 |
    97 | ) : ( 98 | 99 | )} 100 | {command.parametersDescription.descriptions.length > 0 ? ( 101 | 102 | Parameters: 103 |
    104 | {...command.parametersDescription.descriptions.map( 105 | renderParameterDescription 106 | )} 107 |
    108 | ) : ( 109 | 110 | )} 111 |
    112 | ); 113 | } 114 | 115 | export function renderCommandHelp( 116 | command: CommandDescription, 117 | designator: string[] 118 | ): string { 119 | const rest = command.parametersDescription.rest; 120 | const keywords = command.parametersDescription.keywords; 121 | return [ 122 | ...designator, 123 | ...command.parametersDescription.descriptions.map((d) => 124 | requiredArgument(d.name) 125 | ), 126 | ...(rest ? [restArgument(rest)] : []), 127 | ...Object.keys(keywords.keywordDescriptions).map((k) => keywordArgument(k)), 128 | ].join(" "); 129 | } 130 | 131 | export function renderErrorDetails(error: ActionError): DocumentNode { 132 | return ( 133 |
    134 | {error.mostRelevantElaboration} 135 | {renderDetailsNotice(error)} 136 | {renderElaborationTrail(error)} 137 | {renderExceptionTrail(error)} 138 |
    139 | ); 140 | } 141 | 142 | export async function replyToEventWithErrorDetails( 143 | roomMessageSender: RoomMessageSender, 144 | event: RoomEvent, 145 | error: ActionError 146 | ): Promise> { 147 | return (await sendMatrixEventsFromDeadDocument( 148 | roomMessageSender, 149 | event.room_id, 150 | {renderErrorDetails(error)}, 151 | { replyToEvent: event } 152 | )) as Result; 153 | } 154 | 155 | export function renderActionResultToEvent( 156 | roomMessageSender: RoomMessageSender, 157 | roomReactionSender: RoomReactionSender, 158 | event: RoomEvent, 159 | result: ActionResult 160 | ): void { 161 | if (isError(result)) { 162 | void Task( 163 | replyToEventWithErrorDetails(roomMessageSender, event, result.error) 164 | ); 165 | } 166 | void Task(reactToEventWithResult(roomReactionSender, event, result)); 167 | } 168 | 169 | // Maybe we need something like the MatrixInterfaceAdaptor but for Error types? 170 | 171 | function formattedArgumentHint(error: ArgumentParseError): string { 172 | const argumentsUpToError = error.partialCommand.stream.source.slice( 173 | 0, 174 | error.partialCommand.stream.getPosition() 175 | ); 176 | let commandContext = "Command context:"; 177 | for (const argument of argumentsUpToError) { 178 | commandContext += ` ${TextPresentationRenderer.render(argument)}`; 179 | } 180 | const badArgument = error.partialCommand.stream.peekItem(); 181 | const badArgumentHint = ` ${ 182 | badArgument === undefined 183 | ? "undefined" 184 | : TextPresentationRenderer.render(badArgument) 185 | }\n${Array(commandContext.length + 1).join( 186 | " " 187 | )} ^ expected ${printPresentationSchema(error.parameter.acceptor)} here`; 188 | return commandContext + badArgumentHint; 189 | } 190 | 191 | export async function reactToEventWithResult( 192 | roomReactionSender: RoomReactionSender, 193 | event: RoomEvent, 194 | result: ActionResult 195 | ): Promise> { 196 | // implement this so we can use it in the invitation protection 197 | // then in the invitation protection makes ure we render when the listener fails 198 | // then in the ban propagation protection also do this. 199 | const react = async (emote: string): Promise> => { 200 | return (await roomReactionSender.sendReaction( 201 | event.room_id, 202 | event.event_id, 203 | emote 204 | )) as Result; 205 | }; 206 | if (isOk(result)) { 207 | return await react("✅"); 208 | } else { 209 | return await react("❌"); 210 | } 211 | } 212 | 213 | function renderArgumentParseError(error: ArgumentParseError): DocumentNode { 214 | return ( 215 | 216 | There was a problem when parsing the {error.parameter.name}{" "} 217 | parameter for this command. 218 |
    219 | {renderCommandHelp( 220 | error.partialCommand.description, 221 | error.partialCommand.designator 222 | )} 223 |
    224 | {error.message} 225 |
    226 |
    {formattedArgumentHint(error)}
    227 |
    228 | ); 229 | } 230 | 231 | function renderUnexpectedArgumentError( 232 | error: UnexpectedArgumentError 233 | ): DocumentNode { 234 | return ( 235 | 236 | There was an unexpected argument provided for this command. 237 |
    238 | {renderCommandHelp( 239 | error.partialCommand.description, 240 | error.partialCommand.designator 241 | )} 242 |
    243 | {error.message} 244 |
    245 |
    246 | ); 247 | } 248 | 249 | export async function matrixCommandRenderer< 250 | TAdaptorContext extends MatrixAdaptorContext, 251 | TEventContext extends MatrixEventContext 252 | >( 253 | { clientPlatform, commandRoomID }: TAdaptorContext, 254 | { event }: TEventContext, 255 | _command: Command, 256 | result: Result 257 | ): Promise> { 258 | void Task( 259 | reactToEventWithResult(clientPlatform.toRoomReactionSender(), event, result) 260 | ); 261 | if (isError(result)) { 262 | if (result.error instanceof ArgumentParseError) { 263 | return (await sendMatrixEventsFromDeadDocument( 264 | clientPlatform.toRoomMessageSender(), 265 | commandRoomID, 266 | renderArgumentParseError(result.error), 267 | { replyToEvent: event } 268 | )) as Result; 269 | } else if (result.error instanceof UnexpectedArgumentError) { 270 | return (await sendMatrixEventsFromDeadDocument( 271 | clientPlatform.toRoomMessageSender(), 272 | commandRoomID, 273 | renderUnexpectedArgumentError(result.error), 274 | { replyToEvent: event } 275 | )) as Result; 276 | } else if (result.error instanceof ActionException) { 277 | const commandError = result.error; 278 | log.error( 279 | "command error", 280 | commandError.uuid, 281 | commandError.message, 282 | commandError.exception 283 | ); 284 | return (await sendMatrixEventsFromDeadDocument( 285 | clientPlatform.toRoomMessageSender(), 286 | commandRoomID, 287 | renderCommandException(result.error), 288 | { replyToEvent: event } 289 | )) as Result; 290 | } else { 291 | const noticeResult = await replyNoticeText( 292 | clientPlatform.toRoomMessageSender(), 293 | commandRoomID, 294 | event.event_id, 295 | `An unexpected error occurred while processing the command: ${result.error.message}` 296 | ); 297 | if (isError(noticeResult)) { 298 | return noticeResult.elaborate( 299 | "Could not reply to a command to report an error back to the user" 300 | ); 301 | } 302 | return Ok(undefined); 303 | } 304 | } 305 | return Ok(undefined); 306 | } 307 | 308 | function renderCommandException(error: ActionException): DocumentNode { 309 | return ( 310 | 311 | There was an unexpected error when processing this command: 312 |
    313 | {error.message} 314 |
    315 | Details can be found by providing the reference {error.uuid} 316 | to an administrator. 317 |
    318 | ); 319 | } 320 | 321 | export function renderMentionPill( 322 | mxid: string, 323 | displayName: string 324 | ): DocumentNode { 325 | const url = `https://matrix.to/#/${mxid}`; 326 | return {displayName}; 327 | } 328 | 329 | export function renderRoomPill(room: MatrixRoomReference): DocumentNode { 330 | return {room.toRoomIDOrAlias()}; 331 | } 332 | 333 | function sortCommandsBySourceTable( 334 | table: CommandTable 335 | ): Map { 336 | const commandsBySourceTable = new Map(); 337 | for (const command of table.getAllCommands()) { 338 | const sourceTable = command.sourceTable; 339 | const groupedCommands = 340 | commandsBySourceTable.get(sourceTable) ?? 341 | ((groupedCommands) => ( 342 | commandsBySourceTable.set(sourceTable, groupedCommands), groupedCommands 343 | ))([]); 344 | groupedCommands.push(command); 345 | } 346 | return commandsBySourceTable; 347 | } 348 | 349 | function sortGroupedCommandsByDesignator( 350 | commandsBySourceTable: Map 351 | ): Map { 352 | for (const commands of commandsBySourceTable.values()) { 353 | commands.sort((a, b) => { 354 | const aDesignator = a.designator.join("."); 355 | const bDesignator = b.designator.join("."); 356 | return aDesignator.localeCompare(bDesignator); 357 | }); 358 | } 359 | return commandsBySourceTable; 360 | } 361 | 362 | function renderSourceTableSummary( 363 | sourceTable: CommandTable, 364 | sortedEntries: CommandTableEntry[] 365 | ): DocumentNode { 366 | const tableName = 367 | typeof sourceTable.name === "string" 368 | ? sourceTable.name.charAt(0).toUpperCase() + sourceTable.name.slice(1) 369 | : sourceTable.name.toString(); 370 | return ( 371 | 372 |
    373 | 374 | {tableName} commands: 375 | 376 | {sortedEntries.map((entry) => 377 | renderCommandSummary(entry.currentCommand, entry) 378 | )} 379 |
    380 |
    381 | ); 382 | } 383 | 384 | export function renderTableHelp( 385 | table: CommandTable, 386 | documentationURL: string 387 | ): DocumentNode { 388 | const groupedAndSortedCommands = sortGroupedCommandsByDesignator( 389 | sortCommandsBySourceTable(table) 390 | ); 391 | return ( 392 | 393 | Documentation: {documentationURL} 394 |
    395 | {[...groupedAndSortedCommands.entries()].map( 396 | ([sourceTable, sortedEntries]) => 397 | renderSourceTableSummary(sourceTable, sortedEntries) 398 | )} 399 |
    400 | ); 401 | } 402 | 403 | export function wrapInRoot( 404 | node: DocumentNode | LeafNode | (DocumentNode | LeafNode)[] 405 | ): DocumentNode { 406 | return {node}; 407 | } 408 | -------------------------------------------------------------------------------- /LICENSES/CC-BY-SA-4.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution-ShareAlike 4.0 International 2 | 3 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 4 | 5 | Using Creative Commons Public Licenses 6 | 7 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 8 | 9 | Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. 10 | 11 | Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. 12 | 13 | Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. 14 | 15 | Creative Commons Attribution-ShareAlike 4.0 International Public License 16 | 17 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 18 | 19 | Section 1 – Definitions. 20 | 21 | a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 22 | 23 | b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 24 | 25 | c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. 26 | 27 | d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 28 | 29 | e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 30 | 31 | f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 32 | 33 | g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. 34 | 35 | h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 36 | 37 | i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 38 | 39 | j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. 40 | 41 | k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 42 | 43 | l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 44 | 45 | m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 46 | 47 | Section 2 – Scope. 48 | 49 | a. License grant. 50 | 51 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 52 | 53 | A. reproduce and Share the Licensed Material, in whole or in part; and 54 | 55 | B. produce, reproduce, and Share Adapted Material. 56 | 57 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 58 | 59 | 3. Term. The term of this Public License is specified in Section 6(a). 60 | 61 | 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 62 | 63 | 5. Downstream recipients. 64 | 65 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 66 | 67 | B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. 68 | 69 | C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 70 | 71 | 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 72 | 73 | b. Other rights. 74 | 75 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 76 | 77 | 2. Patent and trademark rights are not licensed under this Public License. 78 | 79 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. 80 | 81 | Section 3 – License Conditions. 82 | 83 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 84 | 85 | a. Attribution. 86 | 87 | 1. If You Share the Licensed Material (including in modified form), You must: 88 | 89 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 90 | 91 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 92 | 93 | ii. a copyright notice; 94 | 95 | iii. a notice that refers to this Public License; 96 | 97 | iv. a notice that refers to the disclaimer of warranties; 98 | 99 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 100 | 101 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 102 | 103 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 104 | 105 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 106 | 107 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 108 | 109 | b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 110 | 111 | 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 112 | 113 | 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 114 | 115 | 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. 116 | 117 | Section 4 – Sui Generis Database Rights. 118 | 119 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 120 | 121 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; 122 | 123 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 124 | 125 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 126 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 127 | 128 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 129 | 130 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. 131 | 132 | b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. 133 | 134 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 135 | 136 | Section 6 – Term and Termination. 137 | 138 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 139 | 140 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 141 | 142 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 143 | 144 | 2. upon express reinstatement by the Licensor. 145 | 146 | c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 147 | 148 | d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 149 | 150 | e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 151 | 152 | Section 7 – Other Terms and Conditions. 153 | 154 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 155 | 156 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 157 | 158 | Section 8 – Interpretation. 159 | 160 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 161 | 162 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 163 | 164 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 165 | 166 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 167 | 168 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 169 | 170 | Creative Commons may be contacted at creativecommons.org. 171 | --------------------------------------------------------------------------------