From f7d59f41b090361745f55c312a1d2284c72f2638 Mon Sep 17 00:00:00 2001 From: m1ngsama Date: Tue, 18 Aug 2026 18:01:30 +0800 Subject: [PATCH] streamline modules with persistent awk --- .github/workflows/ci.yml | 19 ++- CHANGELOG.md | 126 ---------------- Makefile | 64 ++++++++- PERFORMANCE.md | 108 -------------- README.md | 140 ------------------ examples/echo-module/README.md | 29 ---- examples/echo-module/echo-module.awk | 10 ++ examples/echo-module/echo-module.sh | 111 +------------- examples/echo-module/module_json.awk | 141 +++++++++++++++--- modules/8ball-module/8ball-module.awk | 35 +++++ modules/8ball-module/8ball-module.sh | 135 +---------------- modules/8ball-module/README.md | 44 ------ modules/8ball-module/module_json.awk | 141 +++++++++++++++--- modules/README.md | 23 --- modules/choose-module/README.md | 42 ------ modules/choose-module/choose-module.awk | 40 ++++++ modules/choose-module/choose-module.sh | 184 +----------------------- modules/choose-module/module_json.awk | 141 +++++++++++++++--- modules/flip-module/README.md | 41 ------ modules/flip-module/flip-module.awk | 15 ++ modules/flip-module/flip-module.sh | 111 +------------- modules/flip-module/module_json.awk | 141 +++++++++++++++--- modules/quote-module/README.md | 42 ------ modules/quote-module/module_json.awk | 141 +++++++++++++++--- modules/quote-module/quote-module.awk | 29 ++++ modules/quote-module/quote-module.sh | 124 +--------------- modules/roll-module/README.md | 60 -------- modules/roll-module/module_json.awk | 141 +++++++++++++++--- modules/roll-module/roll-module.awk | 70 +++++++++ modules/roll-module/roll-module.sh | 176 +---------------------- protocol/README.md | 161 --------------------- scripts/module_json.awk | 141 +++++++++++++++--- scripts/release_check.sh | 49 ++++++- tests/test_modules_behavior.sh | 50 ++++--- tnt-modules.7 | 125 ++++++++++++++++ 35 files changed, 1378 insertions(+), 1772 deletions(-) delete mode 100644 CHANGELOG.md delete mode 100644 PERFORMANCE.md delete mode 100644 README.md delete mode 100644 examples/echo-module/README.md create mode 100644 examples/echo-module/echo-module.awk create mode 100644 modules/8ball-module/8ball-module.awk delete mode 100644 modules/8ball-module/README.md delete mode 100644 modules/README.md delete mode 100644 modules/choose-module/README.md create mode 100644 modules/choose-module/choose-module.awk delete mode 100644 modules/flip-module/README.md create mode 100644 modules/flip-module/flip-module.awk delete mode 100644 modules/quote-module/README.md create mode 100644 modules/quote-module/quote-module.awk delete mode 100644 modules/roll-module/README.md create mode 100644 modules/roll-module/roll-module.awk delete mode 100644 protocol/README.md create mode 100644 tnt-modules.7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae95de5..8ad6a7c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,13 +27,28 @@ jobs: runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v6 + - name: Install manual-page linter + if: runner.os == 'Linux' + run: | + sudo apt-get update + sudo apt-get install -y mandoc - name: Validate release metadata, manifests, handshakes, and behavior run: make release-check core-compatibility: - name: TNT core compatibility + name: TNT ${{ matrix.tier }} (${{ matrix.tnt_ref }}) timeout-minutes: 15 runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - tier: minimum + tnt_ref: v1.1.0 + - tier: stable + tnt_ref: v1.3.0 + - tier: main + tnt_ref: main steps: - name: Check out modules uses: actions/checkout@v6 @@ -43,7 +58,7 @@ jobs: uses: actions/checkout@v6 with: repository: m1ngsama/TNT - ref: main + ref: ${{ matrix.tnt_ref }} path: TNT - name: Install TNT dependencies run: | diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index b503977..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,126 +0,0 @@ -# Changelog - -## Unreleased - -## 0.3.0 - 2026-08-13 - -### Added - -- Added a reproducible, standard-library Python benchmark for cold process - startup, warm command-event latency, stdout volume, and co-resident idle - resources. It reports p50, p95, and p99 latency plus per-process-group RSS, - CPU, and process counts in human-readable and schema-versioned JSON formats; - `make perf-check` enforces the selected profile's regression redlines. -- Added real slash-command benchmark workloads to every reusable module - manifest and require the expected `message.create` action before event - completion, so the benchmark measures command handlers rather than no-op - paths. -- Added benchmark regression tests, Linux CI budget gates, and equivalent - macOS evidence runs. CI retains platform-specific `module-performance.json` - and `module-load.json` reports even when an enforced Linux check fails or a - macOS measurement crosses the unchanged budget. -- Added a bounded fixed-rate load profile for 1, 4, and 8 module slots at the - 1,000 source-events/minute target. It reports fan-out completion, drops, - throughput, queue depth, deadline misses, per-slot latency, and aggregate - source p50/p95/p99; Linux CI rejects dropped or over-budget command events, - macOS records the identical profile without relaxing its reported budgets, - and a slow-slot regression proves that a healthy peer continues independently. - The driver broadcasts one shared, round-robin command corpus to every slot, - matching TNT event delivery instead of synthesizing simultaneous unrelated - slash commands. -- Added deterministic fault-corpus coverage for slow or unterminated responses, - invalid JSON, process crashes, response floods, stubborn descendants, and - benchmark interruption without allowing unbounded queues or leaked process - groups. -- Added an eight-slot idle-resource profile that includes child processes, - gates per-slot and aggregate RSS plus idle CPU, and runs for ten seconds on - both CI platforms. Added `PERFORMANCE.md` with the Issue #7 target - environment, measurement contract, CI reports, and the explicit TNT-core - isolation boundary. -- Added an explicit `scripts/check_modules.sh --performance` profile. After all - built-in or delegated static checks finish, it invokes the shared benchmark - once for every checked directory to enforce latency, output, bounded load, - and eight-slot idle-resource budgets; the default checker remains fast. -- Added a cross-repository release gate that delegates validation to TNT's - authoritative checker, runs every bundled module under a real TNT server, - exercises all slash commands through SSH, verifies persisted responses, and - confirms graceful module-process cleanup. -- Added release metadata validation and tag/version alignment checks to the - default CI gate. - -### Fixed - -- Updated the echo example and every bundled community module to emit - `event.ok` immediately after any `message.create` action. This explicitly - terminates each event and avoids waiting for TNT's per-event response timeout - after generated messages. -- Replaced grep/sed-based protocol field matching with a shared, self-contained - POSIX awk JSON parser. Escaped quotes and backslashes are now decoded - correctly, and nested metadata fields can no longer impersonate top-level - event fields. The parser validates UTF-8, rejects duplicate keys, preserves - unknown extension fields, and rejects controls only when they occur in a - requested transport string. -- Changed unknown and non-actionable non-handshake inputs to no-op with - `event.ok`, avoiding responses that the current TNT runtime treats as - invalid. Unsupported protocol handshakes still return an error. -- Preserved literal backslashes when sender, dice, and choice text crosses awk - boundaries, made JSON escaping portable across one-true-awk, mawk, and gawk - POSIX mode, and retained the intended Unicode result symbols. -- Capped echo and choose responses at TNT's 1,023-byte decoded-text limit with - UTF-8-aware truncation, so maximum-size valid events cannot produce responses - that TNT rejects. -- Hardened checker, behavior-test, and benchmark process cleanup to terminate - complete process groups, including stubborn descendants, and reject - unsolicited output left behind after a startup handshake. - -### Changed - -- Moved random seed acquisition out of the reusable modules' per-event hot - path, retained a per-process random base with a changing event seed, removed - external trimming from roll/choose, and bypassed choose truncation work for - already-bounded output. This keeps command behavior intact while preserving - latency headroom under the eight-slot load profile. -- Reworked the built-in module checker to parse manifests and handshakes as - strict JSON, validate required field types and exact array membership, reject - duplicate keys and malformed versions, verify handshake name/version against - the manifest, and match TNT's JSONL size boundary. -- Expanded behavior and checker regression coverage across every reusable - module and the echo example, including exact event framing, unsupported - handshakes, unknown events, escaped strings, nested-key spoofing, malformed - manifests, process timeouts, transport boundaries, and checker delegation. -- Clarified the protocol and module documentation that `event.ok` is the - required terminator for every non-handshake event, including no-op events. -- Bumped the bundled module and echo-example versions to `0.2.0` for their - hardened JSON parser, bounded output, and explicit event-completion behavior. - -## 0.2.0 - 2026-06-29 - -### Added - -- Added `modules/roll-module`, the first reusable community module: a - network-free dice roller that replies to chat messages starting with - `/roll` (e.g. `/roll 2d6`, `/roll d20`, `/roll 3d6+2`) and stays silent - otherwise. Validated by the repository checker and TNT core's - `module_check.sh`. -- Added a community "fun pack" of reusable modules under `modules/`: - `flip-module` (`/flip`), `8ball-module` (`/8ball`), `choose-module` - (`/choose a | b | c`), and `quote-module` (`/quote`). Each is a - self-contained, no-dependency `tnt.module.v1` module that responds only to - its own command and stays silent (no-op) on all other messages. -- Added `tests/test_modules_behavior.sh`, the repository's first behavioral - test suite, which drives the four fun-pack modules over JSONL and asserts - response shapes. Wired into `make test`. - -## 0.1.0 - 2026-06-16 - -### Added - -- Added the first public echo module example for `tnt.module.v1`. -- Added `scripts/check_modules.sh` to validate module manifests, entrypoints, - TNT minimum versions, permissions, events, and handshakes. -- Added a test suite for module repository validation. - -### Changed - -- Marked the echo example as requiring TNT 1.1.0 or newer, matching the core - module lifecycle checker and install wizard release. diff --git a/Makefile b/Makefile index d2bee0f..babe75d 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,17 @@ -.PHONY: test check release-check check-modules core-check core-integration perf perf-load perf-resources perf-check +.PHONY: test check release-check check-modules core-check core-integration \ + perf perf-load perf-resources perf-check man-check install install-man \ + install-modules uninstall uninstall-man uninstall-modules PYTHON ?= python3 PERF_ARGS ?= TNT_ROOT ?= ../TNT +PREFIX ?= /usr/local +MANDIR ?= $(PREFIX)/share/man +LIBEXECDIR ?= $(PREFIX)/libexec +MODULEDIR ?= $(LIBEXECDIR)/tnt/modules +INSTALL ?= install +MANPAGE = tnt-modules.7 +MODULES = 8ball-module choose-module flip-module quote-module roll-module test: check-modules @tests/test_check_modules.sh @@ -12,6 +21,59 @@ test: check-modules release-check: @scripts/release_check.sh +man-check: + @set -e; \ + markdown=$$(find . -type f -name '*.md' -not -path './.git/*' -print); \ + [ -z "$$markdown" ] || { printf '%s\n' "$$markdown" >&2; exit 1; }; \ + awk 'length($$0) > 80 { print FNR ":" length($$0); bad = 1 } \ + END { exit bad }' $(MANPAGE); \ + ! grep -n -E '^\.(TS|TE|nf|fi)([[:space:]]|$$)' $(MANPAGE); \ + ! grep -n -E '([[:alnum:]_./-]+\.md|docs/)' $(MANPAGE); \ + if command -v mandoc >/dev/null 2>&1; then \ + mandoc -Tlint $(MANPAGE); \ + test -n "$$(mandoc -Tascii $(MANPAGE))"; \ + elif command -v groff >/dev/null 2>&1; then \ + groff -man -z -ww $(MANPAGE); \ + test -n "$$(groff -man -Tascii $(MANPAGE))"; \ + else \ + echo "man-check: mandoc or groff is required" >&2; \ + exit 1; \ + fi + +install: install-modules install-man + +install-modules: + @set -e; \ + for module in $(MODULES); do \ + dir="$(DESTDIR)$(MODULEDIR)/$$module"; \ + $(INSTALL) -d "$$dir"; \ + $(INSTALL) -m 0644 "modules/$$module/module_json.awk" "$$dir/"; \ + $(INSTALL) -m 0644 "modules/$$module/$$module.awk" "$$dir/"; \ + $(INSTALL) -m 0644 "modules/$$module/tnt-module.json" "$$dir/"; \ + $(INSTALL) -m 0755 "modules/$$module/$$module.sh" "$$dir/"; \ + done + +install-man: $(MANPAGE) + $(INSTALL) -d "$(DESTDIR)$(MANDIR)/man7" + $(INSTALL) -m 0644 $(MANPAGE) \ + "$(DESTDIR)$(MANDIR)/man7/$(MANPAGE)" + +uninstall: uninstall-modules uninstall-man + +uninstall-modules: + @set -e; \ + for module in $(MODULES); do \ + dir="$(DESTDIR)$(MODULEDIR)/$$module"; \ + $(RM) "$$dir/module_json.awk" "$$dir/$$module.awk"; \ + $(RM) "$$dir/tnt-module.json"; \ + $(RM) "$$dir/$$module.sh"; \ + rmdir "$$dir" 2>/dev/null || true; \ + done; \ + rmdir "$(DESTDIR)$(MODULEDIR)" 2>/dev/null || true + +uninstall-man: + $(RM) "$(DESTDIR)$(MANDIR)/man7/$(MANPAGE)" + check-modules: @scripts/sync_module_json.sh --check @scripts/check_modules.sh diff --git a/PERFORMANCE.md b/PERFORMANCE.md deleted file mode 100644 index 4a80911..0000000 --- a/PERFORMANCE.md +++ /dev/null @@ -1,108 +0,0 @@ -# TNT Module Performance - -This is the executable contract for -[Issue #7](https://github.com/m1ngsama/tnt-modules/issues/7). It measures real -external module processes; TNT core scheduling is a separate system boundary. - -The target is eight enabled modules sharing a 1-vCPU, no-swap host with TNT at -1,000 source events per minute. The host may have 128 MiB RAM, but that is not -an allowance for the module set. - -## Budgets - -| Metric | Ideal | Regression redline | -| --- | ---: | ---: | -| Single-module startup p95 | 50 ms | 150 ms | -| Event p95 / p99 | 20 / 50 ms | 50 / 100 ms | -| Single-module idle RSS | 4 MiB | 8 MiB | -| Eight-slot total idle RSS | 24 MiB | 32 MiB | -| Idle CPU | ~0% | 0.2% per module | -| Output per event | 8 KiB | 32 KiB | -| 1/4/8-slot load | 1,000 events/min | any drop or response over 100 ms | - -The memory redlines are deliberately below the original triage estimates. Five -shell modules reused across eight slots measured about 16 MiB total and roughly -2 MiB per slot on the reviewed Apple M4 run. A 32 MiB aggregate redline leaves -100% headroom without making a fivefold regression look acceptable. - -TNT's transport independently limits a JSONL payload to 4,094 bytes and an -event to eight response records, so its effective maximum is 32,760 bytes -including newlines. - -## Commands - -The benchmark uses only Python 3.10+ standard-library modules and local POSIX -tools. It needs no credentials or network access. - -```sh -make perf # startup/event information -make perf-load # 1/4/8-slot fixed-rate load -make perf-resources # eight-slot idle RSS and CPU -make perf-check # enforce selected profiles -``` - -One complete enforced run is: - -```sh -make perf-check PERF_ARGS="--load --idle-resources --idle-seconds 10" -``` - -Add `--json-output /tmp/module-performance.json` only when a report will be -reviewed. `scripts/check_modules.sh --performance [MODULE_DIR ...]` first -validates every selected manifest/handshake, then invokes the same full profile -once. The checker does not maintain a second implementation. - -## Cost policy - -- Push and pull-request CI runs correctness and compatibility only. -- Performance runs only through the manual Linux workflow or a maintainer's - local command; there is no schedule and no duplicate macOS hosted run. -- Successful manual runs upload nothing by default. A failure or explicit - retention request keeps one compact JSON artifact for three days. -- Production TNT is not a continuous benchmark target. - -## Measurement contract - -Each bundled module declares a real command workload in its manifest. A -repository workload must produce a valid `message.create` before `event.ok`, so -a fast no-op cannot masquerade as business-command performance. - -- Startup uses five independent launches by default and ends after a valid - `handshake.ok`. -- Event latency uses a persistent process, at least five untimed warmups and 20 - timed events. It ends only after the complete sequence reaches `event.ok`. -- JSONL, UTF-8, identity, framing, action expectation, record count and output - size remain correctness conditions. -- Fixed-rate load broadcasts one source event to 1, 4 and 8 slots. Each slot - has one in-flight and one pending event; further work is counted as dropped - rather than accumulated. Zero drops and complete fan-out are required. -- Idle measurement starts eight slots, includes helper processes in each - process group, samples RSS/CPU/process count, rejects unsolicited output and - fails if a leader exits. - -The JSON schema records commit/dirty state, OS, Python, CPU, configuration, -budgets, transport limits, sample summaries, assignments, throughput, drops, -deadline misses, resources, failures and overall pass state. Compare only -equivalent hosts and workloads. - -## Reviewed baseline - -On 2026-08-13, clean commit -`ddba30b1c53d36b18b853f79cc8ddf6c6ef2c94d` on Apple M4 / Darwin 24.6 / -Python 3.14.6 passed the complete profile: - -- per-slot idle RSS: about 1,984–2,080 KiB; -- eight-slot aggregate RSS: about 16 MiB; -- sampled idle CPU: 0.0%; -- all 100/400/800 load deliveries completed at 1,000 source events/minute with - no drops; -- eight-slot source fan-out p95/p99 stayed below 31/41 ms. - -These are environment-specific measurements, not permanent promises. - -## Boundary - -This repository proves module-process behavior. TNT core owns supervision, -timeouts, module-to-module isolation and end-to-end SSH integration. A pass -here must not be presented as proof of core scheduler isolation; TNT's own -module runtime and integration tests cover that boundary. diff --git a/README.md b/README.md deleted file mode 100644 index 062cc1e..0000000 --- a/README.md +++ /dev/null @@ -1,140 +0,0 @@ -# TNT Modules - -This repository is a companion community module repository for -[TNT](https://github.com/m1ngsama/TNT), a C SSH terminal chat server. - -TNT modules are external-process components. TNT starts a module process, -sends newline-delimited JSON messages to the module's standard input, and -reads newline-delimited JSON messages from the module's standard output. - -TNT core stays deliberately basic and broadly compatible. Modules are where -personalized workflows, richer visuals, and terminal-specific experience -improvements should live. - -Module compatibility tracks TNT protocol versions. A module declares the TNT -module protocol string it supports in its manifest, currently -`tnt.module.v1`, and TNT core can use that declaration to decide whether the -module is compatible with the running server. - -The current repository release is `0.3.0`. Its modules require TNT 1.1.0 or -newer and use the stable `tnt.module.v1` protocol. - -When deploying TNT with modules, set `TNT_MODULE_PATHS` to a colon-separated -list of module directories. Unset it to return to the plain core server. - -## Layout - -- `modules/`: community modules intended for reuse. -- `protocol/`: module manifest and JSONL protocol notes. -- `examples/`: small modules that demonstrate the protocol shape. - -## Available modules - -Self-contained, no-dependency modules under `modules/`. Each reacts only to its -own slash command and emits no action (only the required `event.ok`) for all -other messages, so several can run at once without interfering: - -| Module | Command | What it does | -| --- | --- | --- | -| `roll-module` | `/roll [N]d[+/-K]` | Rolls dice expressions. | -| `flip-module` | `/flip` | Flips a coin (heads/tails). | -| `8ball-module` | `/8ball [question]` | Replies like a Magic 8-Ball. | -| `choose-module` | `/choose a \| b \| c` | Picks one option at random. | -| `quote-module` | `/quote` | Shares a random public-domain proverb. | - -Enable any subset by listing their directories in `TNT_MODULE_PATHS` -(colon-separated). - -## Module Contract - -A TNT module should: - -1. Include a `tnt-module.json` manifest. -2. Read one JSON object per line from stdin. -3. Emit zero or more action objects for each event, then exactly one - `{"type":"event.ok"}` terminator, with one JSON object per stdout line. -4. Write diagnostics to stderr. -5. Exit non-zero when startup or runtime initialization fails. - -The first module protocol is `tnt.module.v1`. TNT sends events such as -`message.created`, and modules can respond with actions such as -`message.create`. The startup handshake ends with `handshake.ok`; every event -after the handshake ends with `event.ok`, including events that require no -action. - -See `examples/echo-module/` for the smallest useful example. - -## Validation - -Run the repository checks: - -```sh -make test -``` - -The default checker stays fast. To run its optional full performance profile -after every selected module has passed manifest and handshake validation: - -```sh -scripts/check_modules.sh --performance -``` - -That profile invokes the shared benchmark once for all checked directories and -enforces startup/event latency, output volume, bounded 1/4/8-slot load, and the -eight-slot idle RSS/CPU budgets. Explicit module paths, including paths -containing spaces, are passed to the same benchmark rather than measured by a -separate checker implementation. - -Repository validation and performance tooling require Python 3.10 or newer. -The packaged modules themselves remain self-contained and require only a POSIX -shell and standard Unix tools. - -Run the quick startup/event benchmark, or enforce its latency and output -redlines: - -```sh -make perf -make perf-check -``` - -Run the fixed-rate 1/4/8-slot load profile or the eight-slot idle RSS/CPU -profile: - -```sh -make perf-load -make perf-resources -``` - -To enforce every repository-owned budget in one local run and preserve it as -JSON: - -```sh -make perf-check PERF_ARGS="--load --idle-resources \ - --json-output module-performance.json" -``` - -See [PERFORMANCE.md](PERFORMANCE.md) for the target environment, budgets, -measurement method, on-demand workflow, and current coverage gaps. - -When checking modules against a TNT checkout, delegate to TNT's checker: - -```sh -TNT_MODULE_CHECKER=/path/to/TNT/scripts/module_check.sh make test -``` - -The release gate also builds TNT core, starts all five bundled modules in one -server, drives their slash commands through real SSH exec sessions, verifies -the persisted responses, and confirms that graceful shutdown reaps every -module process: - -```sh -make core-check core-integration TNT_ROOT=/path/to/TNT -``` - -`scripts/check_modules.sh --checker /path/to/module_check.sh --performance` -first delegates every static check and then runs the same local full performance -profile. Omitting `--performance` preserves the quick checker-only behavior. - -## License - -This repository uses the same license text as TNT. See `LICENSE`. diff --git a/examples/echo-module/README.md b/examples/echo-module/README.md deleted file mode 100644 index 980c6eb..0000000 --- a/examples/echo-module/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Echo Module - -This example demonstrates a minimal TNT module process. - -It is the smallest compatibility example for TNT 1.1.0 and `tnt.module.v1`. - -It reads JSONL from stdin and emits JSONL to stdout: - -- `handshake` requests for `tnt.module.v1` receive `handshake.ok`. -- `message.created` events with `message.plain_text` receive a - `message.create` response followed by `event.ok`. -- Unsupported or non-actionable events receive only `event.ok` (a no-op). -- A handshake for an unsupported protocol receives an `error` response. - -The startup handshake ends with `handshake.ok`. Every event after it ends with -exactly one `event.ok`; the terminator lets TNT move -to the next event without waiting for its response timeout. - -The shell implementation uses the self-contained `module_json.awk` helper to -read the protocol fields without mistaking nested metadata for top-level data. - -Run it manually: - -```sh -printf '%s\n' \ - '{"type":"handshake","protocol":"tnt.module.v1","server":{"name":"tnt","version":"1.1.0"}}' \ - '{"type":"message.created","message":{"plain_text":"hello"}}' \ - | ./echo-module.sh -``` diff --git a/examples/echo-module/echo-module.awk b/examples/echo-module/echo-module.awk new file mode 100644 index 0000000..4359c4f --- /dev/null +++ b/examples/echo-module/echo-module.awk @@ -0,0 +1,10 @@ +BEGIN { + runtime = 1 +} + +{ + if (!begin_event("echo-module", "0.2.0")) next + text = safe_string("message", "plain_text") + if (text != "") emit_message("echo: " text) + emit_event_ok() +} diff --git a/examples/echo-module/echo-module.sh b/examples/echo-module/echo-module.sh index cfe9ec7..603cac6 100755 --- a/examples/echo-module/echo-module.sh +++ b/examples/echo-module/echo-module.sh @@ -1,109 +1,4 @@ #!/bin/sh - -json_escape() { - printf '%s' "$1" | LC_ALL=C awk ' - BEGIN { - ORS = "" - hex = "0123456789abcdef" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - if (NR > 1) printf "%s", "\\n" - for (i = 1; i <= length($0); i++) { - c = substr($0, i, 1) - if (c == "\\") printf "%s", "\\\\" - else if (c == "\"") printf "%s", "\\\"" - else if (c == "\b") printf "%s", "\\b" - else if (c == "\f") printf "%s", "\\f" - else if (c == "\t") printf "%s", "\\t" - else if (c == "\r") printf "%s", "\\r" - else { - value = byte[c] - if (value < 32 || value == 127) { - printf "\\u00%s%s", substr(hex, int(value / 16) + 1, 1), \ - substr(hex, (value % 16) + 1, 1) - } else { - printf "%s", c - } - } - } - } - ' -} - -# Copy at most LIMIT UTF-8 bytes from stdin without splitting a code point. -# LC_ALL=C makes awk's string offsets byte-based on both macOS and Linux. -utf8_truncate() { - limit=$1 - LC_ALL=C awk -v limit="$limit" ' - BEGIN { - ORS = "" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - out = "" - out_bytes = 0 - pos = 1 - total = length($0) - while (pos <= total) { - first = byte[substr($0, pos, 1)] - if (first <= 127) width = 1 - else if (first >= 194 && first <= 223) width = 2 - else if (first >= 224 && first <= 239) width = 3 - else if (first >= 240 && first <= 244) width = 4 - else exit 1 - - if (pos + width - 1 > total) exit 1 - for (j = 1; j < width; j++) { - continuation = byte[substr($0, pos + j, 1)] - if (continuation < 128 || continuation > 191) exit 1 - } - - second = width > 1 ? byte[substr($0, pos + 1, 1)] : 0 - if ((first == 224 && second < 160) || - (first == 237 && second > 159) || - (first == 240 && second < 144) || - (first == 244 && second > 143)) exit 1 - - if (out_bytes + width > limit) break - out = out substr($0, pos, width) - out_bytes += width - pos += width - } - printf "%s", out - } - ' -} - -json_string_field() { - scope=$1 - key=$2 - line=$3 - printf '%s\n' "$line" | LC_ALL=C awk -v scope="$scope" -v key="$key" \ - -f ./module_json.awk -} - -while IFS= read -r line; do - type=$(json_string_field "" type "$line") - - if [ "$type" = "handshake" ]; then - protocol=$(json_string_field "" protocol "$line") - if [ "$protocol" = "tnt.module.v1" ]; then - printf '{"type":"handshake.ok","protocol":"tnt.module.v1","module":{"name":"echo-module","version":"0.2.0"}}\n' - else - printf '{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"}\n' - fi - elif [ "$type" = "message.created" ]; then - plain_text=$(json_string_field message plain_text "$line") - if [ -n "$plain_text" ]; then - bounded_text=$(printf '%s' "echo: $plain_text" | utf8_truncate 1023) || bounded_text= - if [ -n "$bounded_text" ]; then - escaped_text=$(json_escape "$bounded_text") - printf '{"type":"message.create","plain_text":"%s"}\n' "$escaped_text" - fi - fi - printf '{"type":"event.ok"}\n' - else - printf '{"type":"event.ok"}\n' - fi -done +LC_ALL=C +export LC_ALL +exec awk -f ./module_json.awk -f ./echo-module.awk diff --git a/examples/echo-module/module_json.awk b/examples/echo-module/module_json.awk index 15c973c..afbbc26 100644 --- a/examples/echo-module/module_json.awk +++ b/examples/echo-module/module_json.awk @@ -57,7 +57,8 @@ function utf8(code) { 128 + (int(code / 64) % 64), 128 + (code % 64)) } -function valid_utf8(value, i, total, first, second, width, j, continuation) { +function valid_utf8(value, reject_controls, i, total, first, second, + width, j, continuation) { i = 1 total = length(value) while (i <= total) { @@ -85,6 +86,9 @@ function valid_utf8(value, i, total, first, second, width, j, continuation) { (first == 237 && second > 159) || (first == 240 && second < 144) || (first == 244 && second > 143)) return 0 + if (reject_controls && + ((width == 1 && (first < 32 || first == 127)) || + (first == 194 && second >= 128 && second <= 159))) return 0 i += width } return 1 @@ -272,12 +276,16 @@ function parse_value(path, c, value, value_unsafe, rest) { skip_ws() c = substr(source, pos, 1) if (c == "\"") { - value = parse_string(path == wanted_path) - value_unsafe = string_unsafe - if (!invalid && string_ok && path == wanted_path && !found) { - result = value - found = 1 - unsafe_target = value_unsafe + value = parse_string(runtime || path == wanted_path) + value_unsafe = string_unsafe || !valid_utf8(value, 1) + if (!invalid && string_ok) { + if (runtime) { + if (!value_unsafe) string_value[path] = value + } else if (path == wanted_path && !found) { + result = value + found = 1 + unsafe_target = value_unsafe + } } } else if (c == "{") { parse_object(path) @@ -299,27 +307,124 @@ function parse_value(path, c, value, value_unsafe, rest) { } } +function clear_record( item) { + for (item in seen) delete seen[item] + for (item in string_value) delete string_value[item] +} + +function safe_string(scope_name, field_name, path) { + path = scope_name == "" ? field_name : scope_name SUBSEP field_name + if (!record_valid || !(path in string_value)) return "" + return string_value[path] +} + +function json_escape(value, out, i, c, code, hex) { + out = "" + hex = "0123456789abcdef" + for (i = 1; i <= length(value); i++) { + c = substr(value, i, 1) + code = byte[c] + if (c == "\\") out = out "\\\\" + else if (c == "\"") out = out "\\\"" + else if (code == 8) out = out "\\b" + else if (code == 12) out = out "\\f" + else if (code == 10) out = out "\\n" + else if (code == 13) out = out "\\r" + else if (code == 9) out = out "\\t" + else if (code < 32 || code == 127) { + out = out "\\u00" substr(hex, int(code / 16) + 1, 1) \ + substr(hex, (code % 16) + 1, 1) + } else { + out = out c + } + } + return out +} + +function utf8_truncate(value, limit) { + if (length(value) <= limit) return value + value = substr(value, 1, limit) + while (value != "" && !valid_utf8(value)) { + value = substr(value, 1, length(value) - 1) + } + return value +} + +function emit_message(value) { + value = utf8_truncate(value, 1023) + if (value == "" || !valid_utf8(value, 1)) return + printf "{\"type\":\"message.create\",\"plain_text\":\"%s\"}\n", \ + json_escape(value) +} + +function emit_event_ok() { + print "{\"type\":\"event.ok\"}" + fflush() +} + +function begin_event(name, version, type, protocol) { + type = safe_string("", "type") + if (type == "handshake") { + protocol = safe_string("", "protocol") + if (protocol == "tnt.module.v1") { + printf "{\"type\":\"handshake.ok\",\"protocol\":\"tnt.module.v1\"," \ + "\"module\":{\"name\":\"%s\",\"version\":\"%s\"}}\n", \ + name, version + } else { + print "{\"type\":\"error\",\"code\":\"unsupported_protocol\"," \ + "\"message\":\"requires tnt.module.v1\"}" + } + fflush() + return 0 + } + if (type != "message.created") { + emit_event_ok() + return 0 + } + return 1 +} + +function reseed_random( event_seed) { + seed_counter++ + event_seed = ((seed + seed_counter) % 2147483646) + 1 + srand(event_seed) +} + +function next_random() { + reseed_random() + return rand() +} + { - if (record_seen) { + if (!runtime && record_seen) { invalid = 1 next } - record_seen = 1 + if (!runtime) record_seen = 1 + clear_record() + invalid = 0 + found = 0 + unsafe_target = 0 + result = "" + record_valid = 0 source = $0 source_length = length(source) if (!valid_utf8(source)) { fail() - next + } else { + pos = 1 + wanted_path = scope == "" ? key : scope SUBSEP key + parse_value("") + skip_ws() + if (pos <= source_length) fail() + if (!invalid) record_valid = 1 } - pos = 1 - wanted_path = scope == "" ? key : scope SUBSEP key - parse_value("") - skip_ws() - if (pos <= source_length) fail() } END { - if (invalid || unsafe_target || !record_seen) exit 2 - if (!found) exit 1 - printf "%s", result + if (!runtime) { + if (invalid || unsafe_target || !record_seen) exit 2 + if (!found) exit 1 + printf "%s", result + } } diff --git a/modules/8ball-module/8ball-module.awk b/modules/8ball-module/8ball-module.awk new file mode 100644 index 0000000..25e8f39 --- /dev/null +++ b/modules/8ball-module/8ball-module.awk @@ -0,0 +1,35 @@ +BEGIN { + runtime = 1 + answer[++answer_count] = "It is certain." + answer[++answer_count] = "It is decidedly so." + answer[++answer_count] = "Without a doubt." + answer[++answer_count] = "Yes, definitely." + answer[++answer_count] = "You may rely on it." + answer[++answer_count] = "As I see it, yes." + answer[++answer_count] = "Most likely." + answer[++answer_count] = "Outlook good." + answer[++answer_count] = "Yes." + answer[++answer_count] = "Signs point to yes." + answer[++answer_count] = "Reply hazy, try again." + answer[++answer_count] = "Ask again later." + answer[++answer_count] = "Better not tell you now." + answer[++answer_count] = "Cannot predict now." + answer[++answer_count] = "Concentrate and ask again." + answer[++answer_count] = "Do not count on it." + answer[++answer_count] = "My reply is no." + answer[++answer_count] = "My sources say no." + answer[++answer_count] = "Outlook not so good." + answer[++answer_count] = "Very doubtful." +} + +{ + if (!begin_event("8ball-module", "0.2.0")) next + text = safe_string("message", "plain_text") + if (text == "/8ball" || substr(text, 1, 7) == "/8ball ") { + sender = safe_string("message", "sender") + if (sender == "") sender = "someone" + pick = int(next_random() * answer_count) + 1 + emit_message("🎱 " sender ": " answer[pick]) + } + emit_event_ok() +} diff --git a/modules/8ball-module/8ball-module.sh b/modules/8ball-module/8ball-module.sh index 1cb3604..ad01bda 100755 --- a/modules/8ball-module/8ball-module.sh +++ b/modules/8ball-module/8ball-module.sh @@ -1,129 +1,8 @@ #!/bin/sh -# TNT 8ball-module: a Magic 8-Ball for tnt.module.v1. -# -# Reacts to chat messages that begin with "/8ball" and replies with a random -# classic answer. All other messages are acknowledged with a no-op so the -# module stays quiet during normal chat. - -json_escape() { - printf '%s' "$1" | LC_ALL=C awk ' - BEGIN { - ORS = "" - hex = "0123456789abcdef" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - if (NR > 1) printf "%s", "\\n" - for (i = 1; i <= length($0); i++) { - c = substr($0, i, 1) - if (c == "\\") printf "%s", "\\\\" - else if (c == "\"") printf "%s", "\\\"" - else if (c == "\b") printf "%s", "\\b" - else if (c == "\f") printf "%s", "\\f" - else if (c == "\t") printf "%s", "\\t" - else if (c == "\r") printf "%s", "\\r" - else { - value = byte[c] - if (value < 32 || value == 127) { - printf "\\u00%s%s", substr(hex, int(value / 16) + 1, 1), \ - substr(hex, (value % 16) + 1, 1) - } else { - printf "%s", c - } - } - } - } - ' -} - -json_string_field() { - scope=$1 - key=$2 - line=$3 - printf '%s\n' "$line" | LC_ALL=C awk -v scope="$scope" -v key="$key" \ - -f ./module_json.awk -} - -seed_base= -seed_counter=0 - -next_seed() { - if [ -z "$seed_base" ]; then - seed_base=$(od -An -N4 -tu4 /dev/null) - while [ "${seed_base# }" != "$seed_base" ]; do seed_base=${seed_base# }; done - while [ "${seed_base% }" != "$seed_base" ]; do seed_base=${seed_base% }; done - case "$seed_base" in ''|*[!0-9]*) seed_base=$$ ;; esac - fi - seed_counter=$((seed_counter + 1)) - event_seed=$(((seed_base + seed_counter) % 2147483646 + 1)) -} - -eightball_result() { - sender=$1 - seed=$2 - - # Pass untrusted text as input. awk -v assignments interpret backslash - # escapes, which can corrupt a literal sender and even emit raw controls. - printf '%s\n' "$sender" | LC_ALL=C awk -v seed="$seed" ' - NR == 1 { sender = $0 } - END { - srand(seed) - if (sender == "") sender = "someone" - n = 0 - # 10 affirmative - a[++n] = "It is certain." - a[++n] = "It is decidedly so." - a[++n] = "Without a doubt." - a[++n] = "Yes, definitely." - a[++n] = "You may rely on it." - a[++n] = "As I see it, yes." - a[++n] = "Most likely." - a[++n] = "Outlook good." - a[++n] = "Yes." - a[++n] = "Signs point to yes." - # 5 non-committal - a[++n] = "Reply hazy, try again." - a[++n] = "Ask again later." - a[++n] = "Better not tell you now." - a[++n] = "Cannot predict now." - a[++n] = "Concentrate and ask again." - # 5 negative - a[++n] = "Do not count on it." - a[++n] = "My reply is no." - a[++n] = "My sources say no." - a[++n] = "Outlook not so good." - a[++n] = "Very doubtful." - pick = int(rand() * n) + 1 - printf "🎱 %s: %s\n", sender, a[pick] - } - ' -} - -while IFS= read -r line; do - type=$(json_string_field "" type "$line") - if [ "$type" = "handshake" ]; then - protocol=$(json_string_field "" protocol "$line") - if [ "$protocol" = "tnt.module.v1" ]; then - printf '{"type":"handshake.ok","protocol":"tnt.module.v1","module":{"name":"8ball-module","version":"0.2.0"}}\n' - else - printf '{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"}\n' - fi - elif [ "$type" = "message.created" ]; then - plain_text=$(json_string_field message plain_text "$line") - case "$plain_text" in - "/8ball"|"/8ball "*) - sender=$(json_string_field message sender "$line") - next_seed - result=$(eightball_result "$sender" "$event_seed") - escaped=$(json_escape "$result") - printf '{"type":"message.create","plain_text":"%s"}\n' "$escaped" - printf '{"type":"event.ok"}\n' - ;; - *) - printf '{"type":"event.ok"}\n' - ;; - esac - else - printf '{"type":"event.ok"}\n' - fi -done +LC_ALL=C +export LC_ALL +seed=$(od -An -N4 -tu4 /dev/null) +while [ "${seed# }" != "$seed" ]; do seed=${seed# }; done +while [ "${seed% }" != "$seed" ]; do seed=${seed% }; done +case "$seed" in ''|*[!0-9]*) seed=$$ ;; esac +exec awk -v seed="$seed" -f ./module_json.awk -f ./8ball-module.awk diff --git a/modules/8ball-module/README.md b/modules/8ball-module/README.md deleted file mode 100644 index c384824..0000000 --- a/modules/8ball-module/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# 8-Ball Module - -A network-free TNT community module that answers questions like a Magic 8-Ball. - -It implements `tnt.module.v1`: it reads JSONL events from stdin and writes -JSONL responses to stdout. It only acts on public messages that begin with -`/8ball`; every other message is acknowledged with a no-op. - -For every `message.created` event it emits zero or one `message.create` action, -then exactly one `event.ok` terminator. The startup handshake ends separately -with `handshake.ok`. - -## Syntax - -``` -/8ball random answer (the question text is optional) -``` - -It draws from the classic 20 answers (10 affirmative, 5 non-committal, -5 negative). Example results: - -``` -🎱 alice: It is certain. -🎱 bob: Reply hazy, try again. -🎱 cara: My sources say no. -``` - -## Run it manually - -```sh -printf '%s\n' \ - '{"type":"handshake","protocol":"tnt.module.v1","server":{"name":"tnt","version":"1.1.0"}}' \ - '{"type":"message.created","message":{"sender":"alice","plain_text":"/8ball will it rain?"}}' \ - | ./8ball-module.sh -``` - -## Enable it - -```sh -TNT_MODULE_PATHS=/path/to/tnt-modules/modules/8ball-module tnt -``` - -Randomness is seeded per question from `/dev/urandom` (PID fallback). The -leading 🎱 is decorative; the answer reads fine as plain text. diff --git a/modules/8ball-module/module_json.awk b/modules/8ball-module/module_json.awk index 15c973c..afbbc26 100644 --- a/modules/8ball-module/module_json.awk +++ b/modules/8ball-module/module_json.awk @@ -57,7 +57,8 @@ function utf8(code) { 128 + (int(code / 64) % 64), 128 + (code % 64)) } -function valid_utf8(value, i, total, first, second, width, j, continuation) { +function valid_utf8(value, reject_controls, i, total, first, second, + width, j, continuation) { i = 1 total = length(value) while (i <= total) { @@ -85,6 +86,9 @@ function valid_utf8(value, i, total, first, second, width, j, continuation) { (first == 237 && second > 159) || (first == 240 && second < 144) || (first == 244 && second > 143)) return 0 + if (reject_controls && + ((width == 1 && (first < 32 || first == 127)) || + (first == 194 && second >= 128 && second <= 159))) return 0 i += width } return 1 @@ -272,12 +276,16 @@ function parse_value(path, c, value, value_unsafe, rest) { skip_ws() c = substr(source, pos, 1) if (c == "\"") { - value = parse_string(path == wanted_path) - value_unsafe = string_unsafe - if (!invalid && string_ok && path == wanted_path && !found) { - result = value - found = 1 - unsafe_target = value_unsafe + value = parse_string(runtime || path == wanted_path) + value_unsafe = string_unsafe || !valid_utf8(value, 1) + if (!invalid && string_ok) { + if (runtime) { + if (!value_unsafe) string_value[path] = value + } else if (path == wanted_path && !found) { + result = value + found = 1 + unsafe_target = value_unsafe + } } } else if (c == "{") { parse_object(path) @@ -299,27 +307,124 @@ function parse_value(path, c, value, value_unsafe, rest) { } } +function clear_record( item) { + for (item in seen) delete seen[item] + for (item in string_value) delete string_value[item] +} + +function safe_string(scope_name, field_name, path) { + path = scope_name == "" ? field_name : scope_name SUBSEP field_name + if (!record_valid || !(path in string_value)) return "" + return string_value[path] +} + +function json_escape(value, out, i, c, code, hex) { + out = "" + hex = "0123456789abcdef" + for (i = 1; i <= length(value); i++) { + c = substr(value, i, 1) + code = byte[c] + if (c == "\\") out = out "\\\\" + else if (c == "\"") out = out "\\\"" + else if (code == 8) out = out "\\b" + else if (code == 12) out = out "\\f" + else if (code == 10) out = out "\\n" + else if (code == 13) out = out "\\r" + else if (code == 9) out = out "\\t" + else if (code < 32 || code == 127) { + out = out "\\u00" substr(hex, int(code / 16) + 1, 1) \ + substr(hex, (code % 16) + 1, 1) + } else { + out = out c + } + } + return out +} + +function utf8_truncate(value, limit) { + if (length(value) <= limit) return value + value = substr(value, 1, limit) + while (value != "" && !valid_utf8(value)) { + value = substr(value, 1, length(value) - 1) + } + return value +} + +function emit_message(value) { + value = utf8_truncate(value, 1023) + if (value == "" || !valid_utf8(value, 1)) return + printf "{\"type\":\"message.create\",\"plain_text\":\"%s\"}\n", \ + json_escape(value) +} + +function emit_event_ok() { + print "{\"type\":\"event.ok\"}" + fflush() +} + +function begin_event(name, version, type, protocol) { + type = safe_string("", "type") + if (type == "handshake") { + protocol = safe_string("", "protocol") + if (protocol == "tnt.module.v1") { + printf "{\"type\":\"handshake.ok\",\"protocol\":\"tnt.module.v1\"," \ + "\"module\":{\"name\":\"%s\",\"version\":\"%s\"}}\n", \ + name, version + } else { + print "{\"type\":\"error\",\"code\":\"unsupported_protocol\"," \ + "\"message\":\"requires tnt.module.v1\"}" + } + fflush() + return 0 + } + if (type != "message.created") { + emit_event_ok() + return 0 + } + return 1 +} + +function reseed_random( event_seed) { + seed_counter++ + event_seed = ((seed + seed_counter) % 2147483646) + 1 + srand(event_seed) +} + +function next_random() { + reseed_random() + return rand() +} + { - if (record_seen) { + if (!runtime && record_seen) { invalid = 1 next } - record_seen = 1 + if (!runtime) record_seen = 1 + clear_record() + invalid = 0 + found = 0 + unsafe_target = 0 + result = "" + record_valid = 0 source = $0 source_length = length(source) if (!valid_utf8(source)) { fail() - next + } else { + pos = 1 + wanted_path = scope == "" ? key : scope SUBSEP key + parse_value("") + skip_ws() + if (pos <= source_length) fail() + if (!invalid) record_valid = 1 } - pos = 1 - wanted_path = scope == "" ? key : scope SUBSEP key - parse_value("") - skip_ws() - if (pos <= source_length) fail() } END { - if (invalid || unsafe_target || !record_seen) exit 2 - if (!found) exit 1 - printf "%s", result + if (!runtime) { + if (invalid || unsafe_target || !record_seen) exit 2 + if (!found) exit 1 + printf "%s", result + } } diff --git a/modules/README.md b/modules/README.md deleted file mode 100644 index 9d4c2b5..0000000 --- a/modules/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Community Modules - -Place reusable TNT community modules in this directory. - -Each module should live in its own subdirectory and include: - -- `README.md` -- `tnt-module.json` -- The executable entrypoint declared by the manifest - -Modules should avoid depending on TNT source internals. Communicate through the -documented JSONL module protocol so compatibility can track TNT protocol -versions cleanly. The current community module protocol is `tnt.module.v1`. - -For every event after the startup handshake, emit zero or more action records -and then exactly one `{"type":"event.ok"}` record. Emit `event.ok` immediately -when the module has no action to take; it is the event terminator, not an -optional acknowledgement. - -The bundled shell modules carry a self-contained `module_json.awk` parser. Its -canonical source is `scripts/module_json.awk`; after changing it, run -`scripts/sync_module_json.sh` and verify the copies with -`scripts/sync_module_json.sh --check`. diff --git a/modules/choose-module/README.md b/modules/choose-module/README.md deleted file mode 100644 index 58eba58..0000000 --- a/modules/choose-module/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Choose Module - -A network-free TNT community module that picks one option at random. - -It implements `tnt.module.v1`: it reads JSONL events from stdin and writes -JSONL responses to stdout. It only acts on public messages that begin with -`/choose`; every other message is acknowledged with a no-op. - -For every `message.created` event it emits zero or one `message.create` action, -then exactly one `event.ok` terminator. The startup handshake ends separately -with `handshake.ok`. - -## Syntax - -``` -/choose a | b | c pick one of the pipe-separated options at random -``` - -Options are split on `|` and trimmed. Fewer than two non-empty options gets a -short usage reply. Example result: - -``` -🤔 alice chose: coffee -``` - -## Run it manually - -```sh -printf '%s\n' \ - '{"type":"handshake","protocol":"tnt.module.v1","server":{"name":"tnt","version":"1.1.0"}}' \ - '{"type":"message.created","message":{"sender":"alice","plain_text":"/choose tea | coffee | water"}}' \ - | ./choose-module.sh -``` - -## Enable it - -```sh -TNT_MODULE_PATHS=/path/to/tnt-modules/modules/choose-module tnt -``` - -Randomness is seeded per call from `/dev/urandom` (PID fallback). The leading -🤔 is decorative; the result reads fine as plain text. diff --git a/modules/choose-module/choose-module.awk b/modules/choose-module/choose-module.awk new file mode 100644 index 0000000..31f0f0d --- /dev/null +++ b/modules/choose-module/choose-module.awk @@ -0,0 +1,40 @@ +BEGIN { + runtime = 1 +} + +function trim(value) { + sub(/^[ \t]+/, "", value) + sub(/[ \t]+$/, "", value) + return value +} + +function clear_choices( item) { + for (item in raw_choice) delete raw_choice[item] + for (item in choice) delete choice[item] +} + +{ + if (!begin_event("choose-module", "0.2.0")) next + text = safe_string("message", "plain_text") + if (text == "/choose" || substr(text, 1, 8) == "/choose ") { + rest = trim(substr(text, 8)) + sender = safe_string("message", "sender") + if (sender == "") sender = "someone" + random_value = next_random() + clear_choices() + raw_count = split(rest, raw_choice, "[|]") + choice_count = 0 + for (i = 1; i <= raw_count; i++) { + item = trim(raw_choice[i]) + if (item != "") choice[++choice_count] = item + } + if (choice_count < 2) { + result = "🤔 choose usage: /choose a | b | c" + } else { + pick = int(random_value * choice_count) + 1 + result = "🤔 " sender " chose: " choice[pick] + } + emit_message(result) + } + emit_event_ok() +} diff --git a/modules/choose-module/choose-module.sh b/modules/choose-module/choose-module.sh index 29c1f77..684308b 100755 --- a/modules/choose-module/choose-module.sh +++ b/modules/choose-module/choose-module.sh @@ -1,182 +1,8 @@ #!/bin/sh -# TNT choose-module: a random picker for tnt.module.v1. -# -# Reacts to chat messages that begin with "/choose" and replies with one of the -# pipe-separated options chosen at random. All other messages are acknowledged -# with a no-op so the module stays quiet during normal chat. - LC_ALL=C export LC_ALL - -json_escape() { - printf '%s' "$1" | LC_ALL=C awk ' - BEGIN { - ORS = "" - hex = "0123456789abcdef" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - if (NR > 1) printf "%s", "\\n" - for (i = 1; i <= length($0); i++) { - c = substr($0, i, 1) - if (c == "\\") printf "%s", "\\\\" - else if (c == "\"") printf "%s", "\\\"" - else if (c == "\b") printf "%s", "\\b" - else if (c == "\f") printf "%s", "\\f" - else if (c == "\t") printf "%s", "\\t" - else if (c == "\r") printf "%s", "\\r" - else { - value = byte[c] - if (value < 32 || value == 127) { - printf "\\u00%s%s", substr(hex, int(value / 16) + 1, 1), \ - substr(hex, (value % 16) + 1, 1) - } else { - printf "%s", c - } - } - } - } - ' -} - -# Copy at most LIMIT UTF-8 bytes from stdin without splitting a code point. -# LC_ALL=C makes awk's string offsets byte-based on both macOS and Linux. -utf8_truncate() { - limit=$1 - LC_ALL=C awk -v limit="$limit" ' - BEGIN { - ORS = "" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - out = "" - out_bytes = 0 - pos = 1 - total = length($0) - while (pos <= total) { - first = byte[substr($0, pos, 1)] - if (first <= 127) width = 1 - else if (first >= 194 && first <= 223) width = 2 - else if (first >= 224 && first <= 239) width = 3 - else if (first >= 240 && first <= 244) width = 4 - else exit 1 - - if (pos + width - 1 > total) exit 1 - for (j = 1; j < width; j++) { - continuation = byte[substr($0, pos + j, 1)] - if (continuation < 128 || continuation > 191) exit 1 - } - - second = width > 1 ? byte[substr($0, pos + 1, 1)] : 0 - if ((first == 224 && second < 160) || - (first == 237 && second > 159) || - (first == 240 && second < 144) || - (first == 244 && second > 143)) exit 1 - - if (out_bytes + width > limit) break - out = out substr($0, pos, width) - out_bytes += width - pos += width - } - printf "%s", out - } - ' -} - -json_string_field() { - scope=$1 - key=$2 - line=$3 - printf '%s\n' "$line" | LC_ALL=C awk -v scope="$scope" -v key="$key" \ - -f ./module_json.awk -} - -seed_base= -seed_counter=0 - -next_seed() { - if [ -z "$seed_base" ]; then - seed_base=$(od -An -N4 -tu4 /dev/null) - while [ "${seed_base# }" != "$seed_base" ]; do seed_base=${seed_base# }; done - while [ "${seed_base% }" != "$seed_base" ]; do seed_base=${seed_base% }; done - case "$seed_base" in ''|*[!0-9]*) seed_base=$$ ;; esac - fi - seed_counter=$((seed_counter + 1)) - event_seed=$(((seed_base + seed_counter) % 2147483646 + 1)) -} - -choose_result() { - options=$1 - sender=$2 - seed=$3 - - # Pass untrusted strings as input records. awk -v assignments interpret - # backslash escapes, which would turn a literal "\t" or "\n" into controls. - { - printf '%s\n' "$sender" - printf '%s\n' "$options" - } | LC_ALL=C awk -v seed="$seed" ' - function trim(s) { - gsub(/^[ \t]+/, "", s) - gsub(/[ \t]+$/, "", s) - return s - } - NR == 1 { sender = $0; next } - NR == 2 { options = $0; next } - END { - srand(seed) - if (sender == "") sender = "someone" - n = split(options, raw, "[|]") - m = 0 - for (i = 1; i <= n; i++) { - t = trim(raw[i]) - if (t != "") opt[++m] = t - } - if (m < 2) { - printf "🤔 choose usage: /choose a | b | c\n" - exit 0 - } - pick = int(rand() * m) + 1 - printf "🤔 %s chose: %s\n", sender, opt[pick] - } - ' -} - -while IFS= read -r line; do - type=$(json_string_field "" type "$line") - if [ "$type" = "handshake" ]; then - protocol=$(json_string_field "" protocol "$line") - if [ "$protocol" = "tnt.module.v1" ]; then - printf '{"type":"handshake.ok","protocol":"tnt.module.v1","module":{"name":"choose-module","version":"0.2.0"}}\n' - else - printf '{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"}\n' - fi - elif [ "$type" = "message.created" ]; then - plain_text=$(json_string_field message plain_text "$line") - case "$plain_text" in - "/choose"|"/choose "*) - sender=$(json_string_field message sender "$line") - rest=${plain_text#/choose} - while [ "${rest# }" != "$rest" ]; do rest=${rest# }; done - while [ "${rest% }" != "$rest" ]; do rest=${rest% }; done - next_seed - result=$(choose_result "$rest" "$sender" "$event_seed") - if [ "${#result}" -le 1023 ]; then - bounded_result=$result - else - bounded_result=$(printf '%s' "$result" | utf8_truncate 1023) || bounded_result= - fi - if [ -n "$bounded_result" ]; then - escaped=$(json_escape "$bounded_result") - printf '{"type":"message.create","plain_text":"%s"}\n' "$escaped" - fi - printf '{"type":"event.ok"}\n' - ;; - *) - printf '{"type":"event.ok"}\n' - ;; - esac - else - printf '{"type":"event.ok"}\n' - fi -done +seed=$(od -An -N4 -tu4 /dev/null) +while [ "${seed# }" != "$seed" ]; do seed=${seed# }; done +while [ "${seed% }" != "$seed" ]; do seed=${seed% }; done +case "$seed" in ''|*[!0-9]*) seed=$$ ;; esac +exec awk -v seed="$seed" -f ./module_json.awk -f ./choose-module.awk diff --git a/modules/choose-module/module_json.awk b/modules/choose-module/module_json.awk index 15c973c..afbbc26 100644 --- a/modules/choose-module/module_json.awk +++ b/modules/choose-module/module_json.awk @@ -57,7 +57,8 @@ function utf8(code) { 128 + (int(code / 64) % 64), 128 + (code % 64)) } -function valid_utf8(value, i, total, first, second, width, j, continuation) { +function valid_utf8(value, reject_controls, i, total, first, second, + width, j, continuation) { i = 1 total = length(value) while (i <= total) { @@ -85,6 +86,9 @@ function valid_utf8(value, i, total, first, second, width, j, continuation) { (first == 237 && second > 159) || (first == 240 && second < 144) || (first == 244 && second > 143)) return 0 + if (reject_controls && + ((width == 1 && (first < 32 || first == 127)) || + (first == 194 && second >= 128 && second <= 159))) return 0 i += width } return 1 @@ -272,12 +276,16 @@ function parse_value(path, c, value, value_unsafe, rest) { skip_ws() c = substr(source, pos, 1) if (c == "\"") { - value = parse_string(path == wanted_path) - value_unsafe = string_unsafe - if (!invalid && string_ok && path == wanted_path && !found) { - result = value - found = 1 - unsafe_target = value_unsafe + value = parse_string(runtime || path == wanted_path) + value_unsafe = string_unsafe || !valid_utf8(value, 1) + if (!invalid && string_ok) { + if (runtime) { + if (!value_unsafe) string_value[path] = value + } else if (path == wanted_path && !found) { + result = value + found = 1 + unsafe_target = value_unsafe + } } } else if (c == "{") { parse_object(path) @@ -299,27 +307,124 @@ function parse_value(path, c, value, value_unsafe, rest) { } } +function clear_record( item) { + for (item in seen) delete seen[item] + for (item in string_value) delete string_value[item] +} + +function safe_string(scope_name, field_name, path) { + path = scope_name == "" ? field_name : scope_name SUBSEP field_name + if (!record_valid || !(path in string_value)) return "" + return string_value[path] +} + +function json_escape(value, out, i, c, code, hex) { + out = "" + hex = "0123456789abcdef" + for (i = 1; i <= length(value); i++) { + c = substr(value, i, 1) + code = byte[c] + if (c == "\\") out = out "\\\\" + else if (c == "\"") out = out "\\\"" + else if (code == 8) out = out "\\b" + else if (code == 12) out = out "\\f" + else if (code == 10) out = out "\\n" + else if (code == 13) out = out "\\r" + else if (code == 9) out = out "\\t" + else if (code < 32 || code == 127) { + out = out "\\u00" substr(hex, int(code / 16) + 1, 1) \ + substr(hex, (code % 16) + 1, 1) + } else { + out = out c + } + } + return out +} + +function utf8_truncate(value, limit) { + if (length(value) <= limit) return value + value = substr(value, 1, limit) + while (value != "" && !valid_utf8(value)) { + value = substr(value, 1, length(value) - 1) + } + return value +} + +function emit_message(value) { + value = utf8_truncate(value, 1023) + if (value == "" || !valid_utf8(value, 1)) return + printf "{\"type\":\"message.create\",\"plain_text\":\"%s\"}\n", \ + json_escape(value) +} + +function emit_event_ok() { + print "{\"type\":\"event.ok\"}" + fflush() +} + +function begin_event(name, version, type, protocol) { + type = safe_string("", "type") + if (type == "handshake") { + protocol = safe_string("", "protocol") + if (protocol == "tnt.module.v1") { + printf "{\"type\":\"handshake.ok\",\"protocol\":\"tnt.module.v1\"," \ + "\"module\":{\"name\":\"%s\",\"version\":\"%s\"}}\n", \ + name, version + } else { + print "{\"type\":\"error\",\"code\":\"unsupported_protocol\"," \ + "\"message\":\"requires tnt.module.v1\"}" + } + fflush() + return 0 + } + if (type != "message.created") { + emit_event_ok() + return 0 + } + return 1 +} + +function reseed_random( event_seed) { + seed_counter++ + event_seed = ((seed + seed_counter) % 2147483646) + 1 + srand(event_seed) +} + +function next_random() { + reseed_random() + return rand() +} + { - if (record_seen) { + if (!runtime && record_seen) { invalid = 1 next } - record_seen = 1 + if (!runtime) record_seen = 1 + clear_record() + invalid = 0 + found = 0 + unsafe_target = 0 + result = "" + record_valid = 0 source = $0 source_length = length(source) if (!valid_utf8(source)) { fail() - next + } else { + pos = 1 + wanted_path = scope == "" ? key : scope SUBSEP key + parse_value("") + skip_ws() + if (pos <= source_length) fail() + if (!invalid) record_valid = 1 } - pos = 1 - wanted_path = scope == "" ? key : scope SUBSEP key - parse_value("") - skip_ws() - if (pos <= source_length) fail() } END { - if (invalid || unsafe_target || !record_seen) exit 2 - if (!found) exit 1 - printf "%s", result + if (!runtime) { + if (invalid || unsafe_target || !record_seen) exit 2 + if (!found) exit 1 + printf "%s", result + } } diff --git a/modules/flip-module/README.md b/modules/flip-module/README.md deleted file mode 100644 index ba2ce71..0000000 --- a/modules/flip-module/README.md +++ /dev/null @@ -1,41 +0,0 @@ -# Flip Module - -A tiny, network-free TNT community module that flips a coin in chat. - -It implements `tnt.module.v1`: it reads JSONL events from stdin and writes -JSONL responses to stdout. It only acts on public messages that begin with -`/flip`; every other message is acknowledged with a no-op. - -For every `message.created` event it emits zero or one `message.create` action, -then exactly one `event.ok` terminator. The startup handshake ends separately -with `handshake.ok`. - -## Syntax - -``` -/flip heads or tails (any extra text is ignored) -``` - -Example result: - -``` -🪙 alice flipped → heads -``` - -## Run it manually - -```sh -printf '%s\n' \ - '{"type":"handshake","protocol":"tnt.module.v1","server":{"name":"tnt","version":"1.1.0"}}' \ - '{"type":"message.created","message":{"sender":"alice","plain_text":"/flip"}}' \ - | ./flip-module.sh -``` - -## Enable it - -```sh -TNT_MODULE_PATHS=/path/to/tnt-modules/modules/flip-module tnt -``` - -Randomness is seeded per flip from `/dev/urandom` (PID fallback). The leading -🪙 is decorative; the result reads fine as plain text. diff --git a/modules/flip-module/flip-module.awk b/modules/flip-module/flip-module.awk new file mode 100644 index 0000000..6e12d16 --- /dev/null +++ b/modules/flip-module/flip-module.awk @@ -0,0 +1,15 @@ +BEGIN { + runtime = 1 +} + +{ + if (!begin_event("flip-module", "0.2.0")) next + text = safe_string("message", "plain_text") + if (text == "/flip" || substr(text, 1, 6) == "/flip ") { + sender = safe_string("message", "sender") + if (sender == "") sender = "someone" + face = int(next_random() * 2) == 0 ? "heads" : "tails" + emit_message("🪙 " sender " flipped → " face) + } + emit_event_ok() +} diff --git a/modules/flip-module/flip-module.sh b/modules/flip-module/flip-module.sh index 2aa0a39..01a39cd 100755 --- a/modules/flip-module/flip-module.sh +++ b/modules/flip-module/flip-module.sh @@ -1,105 +1,8 @@ #!/bin/sh -# TNT flip-module: a coin flipper for tnt.module.v1. -# -# Reacts to chat messages that begin with "/flip" and replies with a public -# heads/tails result. All other messages are acknowledged with a no-op so the -# module stays quiet during normal chat. - -json_escape() { - printf '%s' "$1" | LC_ALL=C awk ' - BEGIN { - ORS = "" - hex = "0123456789abcdef" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - if (NR > 1) printf "%s", "\\n" - for (i = 1; i <= length($0); i++) { - c = substr($0, i, 1) - if (c == "\\") printf "%s", "\\\\" - else if (c == "\"") printf "%s", "\\\"" - else if (c == "\b") printf "%s", "\\b" - else if (c == "\f") printf "%s", "\\f" - else if (c == "\t") printf "%s", "\\t" - else if (c == "\r") printf "%s", "\\r" - else { - value = byte[c] - if (value < 32 || value == 127) { - printf "\\u00%s%s", substr(hex, int(value / 16) + 1, 1), \ - substr(hex, (value % 16) + 1, 1) - } else { - printf "%s", c - } - } - } - } - ' -} - -json_string_field() { - scope=$1 - key=$2 - line=$3 - printf '%s\n' "$line" | LC_ALL=C awk -v scope="$scope" -v key="$key" \ - -f ./module_json.awk -} - -seed_base= -seed_counter=0 - -next_seed() { - if [ -z "$seed_base" ]; then - seed_base=$(od -An -N4 -tu4 /dev/null) - while [ "${seed_base# }" != "$seed_base" ]; do seed_base=${seed_base# }; done - while [ "${seed_base% }" != "$seed_base" ]; do seed_base=${seed_base% }; done - case "$seed_base" in ''|*[!0-9]*) seed_base=$$ ;; esac - fi - seed_counter=$((seed_counter + 1)) - event_seed=$(((seed_base + seed_counter) % 2147483646 + 1)) -} - -flip_result() { - sender=$1 - seed=$2 - - # Pass untrusted text as input. awk -v assignments interpret backslash - # escapes, which can corrupt a literal sender and even emit raw controls. - printf '%s\n' "$sender" | LC_ALL=C awk -v seed="$seed" ' - NR == 1 { sender = $0 } - END { - srand(seed) - if (sender == "") sender = "someone" - face = (int(rand() * 2) == 0) ? "heads" : "tails" - printf "🪙 %s flipped → %s\n", sender, face - } - ' -} - -while IFS= read -r line; do - type=$(json_string_field "" type "$line") - if [ "$type" = "handshake" ]; then - protocol=$(json_string_field "" protocol "$line") - if [ "$protocol" = "tnt.module.v1" ]; then - printf '{"type":"handshake.ok","protocol":"tnt.module.v1","module":{"name":"flip-module","version":"0.2.0"}}\n' - else - printf '{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"}\n' - fi - elif [ "$type" = "message.created" ]; then - plain_text=$(json_string_field message plain_text "$line") - case "$plain_text" in - "/flip"|"/flip "*) - sender=$(json_string_field message sender "$line") - next_seed - result=$(flip_result "$sender" "$event_seed") - escaped=$(json_escape "$result") - printf '{"type":"message.create","plain_text":"%s"}\n' "$escaped" - printf '{"type":"event.ok"}\n' - ;; - *) - printf '{"type":"event.ok"}\n' - ;; - esac - else - printf '{"type":"event.ok"}\n' - fi -done +LC_ALL=C +export LC_ALL +seed=$(od -An -N4 -tu4 /dev/null) +while [ "${seed# }" != "$seed" ]; do seed=${seed# }; done +while [ "${seed% }" != "$seed" ]; do seed=${seed% }; done +case "$seed" in ''|*[!0-9]*) seed=$$ ;; esac +exec awk -v seed="$seed" -f ./module_json.awk -f ./flip-module.awk diff --git a/modules/flip-module/module_json.awk b/modules/flip-module/module_json.awk index 15c973c..afbbc26 100644 --- a/modules/flip-module/module_json.awk +++ b/modules/flip-module/module_json.awk @@ -57,7 +57,8 @@ function utf8(code) { 128 + (int(code / 64) % 64), 128 + (code % 64)) } -function valid_utf8(value, i, total, first, second, width, j, continuation) { +function valid_utf8(value, reject_controls, i, total, first, second, + width, j, continuation) { i = 1 total = length(value) while (i <= total) { @@ -85,6 +86,9 @@ function valid_utf8(value, i, total, first, second, width, j, continuation) { (first == 237 && second > 159) || (first == 240 && second < 144) || (first == 244 && second > 143)) return 0 + if (reject_controls && + ((width == 1 && (first < 32 || first == 127)) || + (first == 194 && second >= 128 && second <= 159))) return 0 i += width } return 1 @@ -272,12 +276,16 @@ function parse_value(path, c, value, value_unsafe, rest) { skip_ws() c = substr(source, pos, 1) if (c == "\"") { - value = parse_string(path == wanted_path) - value_unsafe = string_unsafe - if (!invalid && string_ok && path == wanted_path && !found) { - result = value - found = 1 - unsafe_target = value_unsafe + value = parse_string(runtime || path == wanted_path) + value_unsafe = string_unsafe || !valid_utf8(value, 1) + if (!invalid && string_ok) { + if (runtime) { + if (!value_unsafe) string_value[path] = value + } else if (path == wanted_path && !found) { + result = value + found = 1 + unsafe_target = value_unsafe + } } } else if (c == "{") { parse_object(path) @@ -299,27 +307,124 @@ function parse_value(path, c, value, value_unsafe, rest) { } } +function clear_record( item) { + for (item in seen) delete seen[item] + for (item in string_value) delete string_value[item] +} + +function safe_string(scope_name, field_name, path) { + path = scope_name == "" ? field_name : scope_name SUBSEP field_name + if (!record_valid || !(path in string_value)) return "" + return string_value[path] +} + +function json_escape(value, out, i, c, code, hex) { + out = "" + hex = "0123456789abcdef" + for (i = 1; i <= length(value); i++) { + c = substr(value, i, 1) + code = byte[c] + if (c == "\\") out = out "\\\\" + else if (c == "\"") out = out "\\\"" + else if (code == 8) out = out "\\b" + else if (code == 12) out = out "\\f" + else if (code == 10) out = out "\\n" + else if (code == 13) out = out "\\r" + else if (code == 9) out = out "\\t" + else if (code < 32 || code == 127) { + out = out "\\u00" substr(hex, int(code / 16) + 1, 1) \ + substr(hex, (code % 16) + 1, 1) + } else { + out = out c + } + } + return out +} + +function utf8_truncate(value, limit) { + if (length(value) <= limit) return value + value = substr(value, 1, limit) + while (value != "" && !valid_utf8(value)) { + value = substr(value, 1, length(value) - 1) + } + return value +} + +function emit_message(value) { + value = utf8_truncate(value, 1023) + if (value == "" || !valid_utf8(value, 1)) return + printf "{\"type\":\"message.create\",\"plain_text\":\"%s\"}\n", \ + json_escape(value) +} + +function emit_event_ok() { + print "{\"type\":\"event.ok\"}" + fflush() +} + +function begin_event(name, version, type, protocol) { + type = safe_string("", "type") + if (type == "handshake") { + protocol = safe_string("", "protocol") + if (protocol == "tnt.module.v1") { + printf "{\"type\":\"handshake.ok\",\"protocol\":\"tnt.module.v1\"," \ + "\"module\":{\"name\":\"%s\",\"version\":\"%s\"}}\n", \ + name, version + } else { + print "{\"type\":\"error\",\"code\":\"unsupported_protocol\"," \ + "\"message\":\"requires tnt.module.v1\"}" + } + fflush() + return 0 + } + if (type != "message.created") { + emit_event_ok() + return 0 + } + return 1 +} + +function reseed_random( event_seed) { + seed_counter++ + event_seed = ((seed + seed_counter) % 2147483646) + 1 + srand(event_seed) +} + +function next_random() { + reseed_random() + return rand() +} + { - if (record_seen) { + if (!runtime && record_seen) { invalid = 1 next } - record_seen = 1 + if (!runtime) record_seen = 1 + clear_record() + invalid = 0 + found = 0 + unsafe_target = 0 + result = "" + record_valid = 0 source = $0 source_length = length(source) if (!valid_utf8(source)) { fail() - next + } else { + pos = 1 + wanted_path = scope == "" ? key : scope SUBSEP key + parse_value("") + skip_ws() + if (pos <= source_length) fail() + if (!invalid) record_valid = 1 } - pos = 1 - wanted_path = scope == "" ? key : scope SUBSEP key - parse_value("") - skip_ws() - if (pos <= source_length) fail() } END { - if (invalid || unsafe_target || !record_seen) exit 2 - if (!found) exit 1 - printf "%s", result + if (!runtime) { + if (invalid || unsafe_target || !record_seen) exit 2 + if (!found) exit 1 + printf "%s", result + } } diff --git a/modules/quote-module/README.md b/modules/quote-module/README.md deleted file mode 100644 index 09f804d..0000000 --- a/modules/quote-module/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Quote Module - -A network-free TNT community module that shares a random proverb in chat. - -It implements `tnt.module.v1`: it reads JSONL events from stdin and writes -JSONL responses to stdout. It only acts on public messages that begin with -`/quote`; every other message is acknowledged with a no-op. - -For every `message.created` event it emits zero or one `message.create` action, -then exactly one `event.ok` terminator. The startup handshake ends separately -with `handshake.ok`. - -## Syntax - -``` -/quote a random proverb (any extra text is ignored) -``` - -The built-in list is intentionally common, public-domain proverbs **without -attribution**, to avoid misquoting anyone. Example result: - -``` -❝ Slow and steady wins the race. ❞ -``` - -## Run it manually - -```sh -printf '%s\n' \ - '{"type":"handshake","protocol":"tnt.module.v1","server":{"name":"tnt","version":"1.1.0"}}' \ - '{"type":"message.created","message":{"sender":"alice","plain_text":"/quote"}}' \ - | ./quote-module.sh -``` - -## Enable it - -```sh -TNT_MODULE_PATHS=/path/to/tnt-modules/modules/quote-module tnt -``` - -Randomness is seeded per call from `/dev/urandom` (PID fallback). The -decorative ❝ ❞ ornaments read fine as plain text. diff --git a/modules/quote-module/module_json.awk b/modules/quote-module/module_json.awk index 15c973c..afbbc26 100644 --- a/modules/quote-module/module_json.awk +++ b/modules/quote-module/module_json.awk @@ -57,7 +57,8 @@ function utf8(code) { 128 + (int(code / 64) % 64), 128 + (code % 64)) } -function valid_utf8(value, i, total, first, second, width, j, continuation) { +function valid_utf8(value, reject_controls, i, total, first, second, + width, j, continuation) { i = 1 total = length(value) while (i <= total) { @@ -85,6 +86,9 @@ function valid_utf8(value, i, total, first, second, width, j, continuation) { (first == 237 && second > 159) || (first == 240 && second < 144) || (first == 244 && second > 143)) return 0 + if (reject_controls && + ((width == 1 && (first < 32 || first == 127)) || + (first == 194 && second >= 128 && second <= 159))) return 0 i += width } return 1 @@ -272,12 +276,16 @@ function parse_value(path, c, value, value_unsafe, rest) { skip_ws() c = substr(source, pos, 1) if (c == "\"") { - value = parse_string(path == wanted_path) - value_unsafe = string_unsafe - if (!invalid && string_ok && path == wanted_path && !found) { - result = value - found = 1 - unsafe_target = value_unsafe + value = parse_string(runtime || path == wanted_path) + value_unsafe = string_unsafe || !valid_utf8(value, 1) + if (!invalid && string_ok) { + if (runtime) { + if (!value_unsafe) string_value[path] = value + } else if (path == wanted_path && !found) { + result = value + found = 1 + unsafe_target = value_unsafe + } } } else if (c == "{") { parse_object(path) @@ -299,27 +307,124 @@ function parse_value(path, c, value, value_unsafe, rest) { } } +function clear_record( item) { + for (item in seen) delete seen[item] + for (item in string_value) delete string_value[item] +} + +function safe_string(scope_name, field_name, path) { + path = scope_name == "" ? field_name : scope_name SUBSEP field_name + if (!record_valid || !(path in string_value)) return "" + return string_value[path] +} + +function json_escape(value, out, i, c, code, hex) { + out = "" + hex = "0123456789abcdef" + for (i = 1; i <= length(value); i++) { + c = substr(value, i, 1) + code = byte[c] + if (c == "\\") out = out "\\\\" + else if (c == "\"") out = out "\\\"" + else if (code == 8) out = out "\\b" + else if (code == 12) out = out "\\f" + else if (code == 10) out = out "\\n" + else if (code == 13) out = out "\\r" + else if (code == 9) out = out "\\t" + else if (code < 32 || code == 127) { + out = out "\\u00" substr(hex, int(code / 16) + 1, 1) \ + substr(hex, (code % 16) + 1, 1) + } else { + out = out c + } + } + return out +} + +function utf8_truncate(value, limit) { + if (length(value) <= limit) return value + value = substr(value, 1, limit) + while (value != "" && !valid_utf8(value)) { + value = substr(value, 1, length(value) - 1) + } + return value +} + +function emit_message(value) { + value = utf8_truncate(value, 1023) + if (value == "" || !valid_utf8(value, 1)) return + printf "{\"type\":\"message.create\",\"plain_text\":\"%s\"}\n", \ + json_escape(value) +} + +function emit_event_ok() { + print "{\"type\":\"event.ok\"}" + fflush() +} + +function begin_event(name, version, type, protocol) { + type = safe_string("", "type") + if (type == "handshake") { + protocol = safe_string("", "protocol") + if (protocol == "tnt.module.v1") { + printf "{\"type\":\"handshake.ok\",\"protocol\":\"tnt.module.v1\"," \ + "\"module\":{\"name\":\"%s\",\"version\":\"%s\"}}\n", \ + name, version + } else { + print "{\"type\":\"error\",\"code\":\"unsupported_protocol\"," \ + "\"message\":\"requires tnt.module.v1\"}" + } + fflush() + return 0 + } + if (type != "message.created") { + emit_event_ok() + return 0 + } + return 1 +} + +function reseed_random( event_seed) { + seed_counter++ + event_seed = ((seed + seed_counter) % 2147483646) + 1 + srand(event_seed) +} + +function next_random() { + reseed_random() + return rand() +} + { - if (record_seen) { + if (!runtime && record_seen) { invalid = 1 next } - record_seen = 1 + if (!runtime) record_seen = 1 + clear_record() + invalid = 0 + found = 0 + unsafe_target = 0 + result = "" + record_valid = 0 source = $0 source_length = length(source) if (!valid_utf8(source)) { fail() - next + } else { + pos = 1 + wanted_path = scope == "" ? key : scope SUBSEP key + parse_value("") + skip_ws() + if (pos <= source_length) fail() + if (!invalid) record_valid = 1 } - pos = 1 - wanted_path = scope == "" ? key : scope SUBSEP key - parse_value("") - skip_ws() - if (pos <= source_length) fail() } END { - if (invalid || unsafe_target || !record_seen) exit 2 - if (!found) exit 1 - printf "%s", result + if (!runtime) { + if (invalid || unsafe_target || !record_seen) exit 2 + if (!found) exit 1 + printf "%s", result + } } diff --git a/modules/quote-module/quote-module.awk b/modules/quote-module/quote-module.awk new file mode 100644 index 0000000..930e221 --- /dev/null +++ b/modules/quote-module/quote-module.awk @@ -0,0 +1,29 @@ +BEGIN { + runtime = 1 + quote[++quote_count] = "Well begun is half done." + quote[++quote_count] = \ + "A journey of a thousand miles begins with a single step." + quote[++quote_count] = "Fortune favors the bold." + quote[++quote_count] = "Still waters run deep." + quote[++quote_count] = "Where there is a will, there is a way." + quote[++quote_count] = "Actions speak louder than words." + quote[++quote_count] = "The early bird catches the worm." + quote[++quote_count] = "Necessity is the mother of invention." + quote[++quote_count] = "Better late than never." + quote[++quote_count] = "Practice makes perfect." + quote[++quote_count] = "A picture is worth a thousand words." + quote[++quote_count] = "Slow and steady wins the race." + quote[++quote_count] = "Knowledge is power." + quote[++quote_count] = "Hope for the best, prepare for the worst." + quote[++quote_count] = "Measure twice, cut once." +} + +{ + if (!begin_event("quote-module", "0.2.0")) next + text = safe_string("message", "plain_text") + if (text == "/quote" || substr(text, 1, 7) == "/quote ") { + pick = int(next_random() * quote_count) + 1 + emit_message("❝ " quote[pick] " ❞") + } + emit_event_ok() +} diff --git a/modules/quote-module/quote-module.sh b/modules/quote-module/quote-module.sh index 2923876..df4e32e 100755 --- a/modules/quote-module/quote-module.sh +++ b/modules/quote-module/quote-module.sh @@ -1,118 +1,8 @@ #!/bin/sh -# TNT quote-module: a random proverb sharer for tnt.module.v1. -# -# Reacts to chat messages that begin with "/quote" and replies with a random -# proverb. All other messages are acknowledged with a no-op so the module stays -# quiet during normal chat. -# -# The built-in list is intentionally common, public-domain proverbs without -# attribution, to avoid misquoting anyone. - -json_escape() { - printf '%s' "$1" | LC_ALL=C awk ' - BEGIN { - ORS = "" - hex = "0123456789abcdef" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - if (NR > 1) printf "%s", "\\n" - for (i = 1; i <= length($0); i++) { - c = substr($0, i, 1) - if (c == "\\") printf "%s", "\\\\" - else if (c == "\"") printf "%s", "\\\"" - else if (c == "\b") printf "%s", "\\b" - else if (c == "\f") printf "%s", "\\f" - else if (c == "\t") printf "%s", "\\t" - else if (c == "\r") printf "%s", "\\r" - else { - value = byte[c] - if (value < 32 || value == 127) { - printf "\\u00%s%s", substr(hex, int(value / 16) + 1, 1), \ - substr(hex, (value % 16) + 1, 1) - } else { - printf "%s", c - } - } - } - } - ' -} - -json_string_field() { - scope=$1 - key=$2 - line=$3 - printf '%s\n' "$line" | LC_ALL=C awk -v scope="$scope" -v key="$key" \ - -f ./module_json.awk -} - -seed_base= -seed_counter=0 - -next_seed() { - if [ -z "$seed_base" ]; then - seed_base=$(od -An -N4 -tu4 /dev/null) - while [ "${seed_base# }" != "$seed_base" ]; do seed_base=${seed_base# }; done - while [ "${seed_base% }" != "$seed_base" ]; do seed_base=${seed_base% }; done - case "$seed_base" in ''|*[!0-9]*) seed_base=$$ ;; esac - fi - seed_counter=$((seed_counter + 1)) - event_seed=$(((seed_base + seed_counter) % 2147483646 + 1)) -} - -quote_result() { - seed=$1 - - awk -v seed="$seed" ' - BEGIN { - srand(seed) - n = 0 - q[++n] = "Well begun is half done." - q[++n] = "A journey of a thousand miles begins with a single step." - q[++n] = "Fortune favors the bold." - q[++n] = "Still waters run deep." - q[++n] = "Where there is a will, there is a way." - q[++n] = "Actions speak louder than words." - q[++n] = "The early bird catches the worm." - q[++n] = "Necessity is the mother of invention." - q[++n] = "Better late than never." - q[++n] = "Practice makes perfect." - q[++n] = "A picture is worth a thousand words." - q[++n] = "Slow and steady wins the race." - q[++n] = "Knowledge is power." - q[++n] = "Hope for the best, prepare for the worst." - q[++n] = "Measure twice, cut once." - pick = int(rand() * n) + 1 - printf "❝ %s ❞\n", q[pick] - } - ' -} - -while IFS= read -r line; do - type=$(json_string_field "" type "$line") - if [ "$type" = "handshake" ]; then - protocol=$(json_string_field "" protocol "$line") - if [ "$protocol" = "tnt.module.v1" ]; then - printf '{"type":"handshake.ok","protocol":"tnt.module.v1","module":{"name":"quote-module","version":"0.2.0"}}\n' - else - printf '{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"}\n' - fi - elif [ "$type" = "message.created" ]; then - plain_text=$(json_string_field message plain_text "$line") - case "$plain_text" in - "/quote"|"/quote "*) - next_seed - result=$(quote_result "$event_seed") - escaped=$(json_escape "$result") - printf '{"type":"message.create","plain_text":"%s"}\n' "$escaped" - printf '{"type":"event.ok"}\n' - ;; - *) - printf '{"type":"event.ok"}\n' - ;; - esac - else - printf '{"type":"event.ok"}\n' - fi -done +LC_ALL=C +export LC_ALL +seed=$(od -An -N4 -tu4 /dev/null) +while [ "${seed# }" != "$seed" ]; do seed=${seed# }; done +while [ "${seed% }" != "$seed" ]; do seed=${seed% }; done +case "$seed" in ''|*[!0-9]*) seed=$$ ;; esac +exec awk -v seed="$seed" -f ./module_json.awk -f ./quote-module.awk diff --git a/modules/roll-module/README.md b/modules/roll-module/README.md deleted file mode 100644 index 704117b..0000000 --- a/modules/roll-module/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# Roll Module - -A small, network-free TNT community module that rolls dice in chat. - -It implements `tnt.module.v1`: it reads JSONL events from stdin and writes -JSONL responses to stdout. It only acts on public messages that begin with -`/roll`; every other message is acknowledged with a no-op so the module stays -quiet during normal conversation. - -For every `message.created` event it emits zero or one `message.create` action, -then exactly one `event.ok` terminator. The startup handshake ends separately -with `handshake.ok`. - -## Syntax - -The dice spec is case-insensitive (`d` or `D`): - -``` -/roll one 6-sided die (1d6) -/roll d20 one 20-sided die -/roll 3d6 three 6-sided dice, summed -/roll 2d6+3 with a flat +/- modifier -``` - -Bounds: 1–20 dice, 2–1000 sides, modifier within ±10000. Anything outside the -syntax or bounds gets a short usage reply. - -Example results: - -``` -🎲 alice rolled d20 → 14 -🎲 alice rolled 3d6 → 4 + 2 + 6 = 12 -🎲 alice rolled 2d6+3 → 5 + 1 (+3) = 9 -``` - -## Run it manually - -```sh -printf '%s\n' \ - '{"type":"handshake","protocol":"tnt.module.v1","server":{"name":"tnt","version":"1.1.0"}}' \ - '{"type":"message.created","message":{"sender":"alice","plain_text":"/roll 2d6"}}' \ - | ./roll-module.sh -``` - -## Enable it - -Point TNT at this module directory (colon-separated for multiple modules): - -```sh -TNT_MODULE_PATHS=/path/to/tnt-modules/modules/roll-module tnt -``` - -## Implementation notes - -The result text is always plain UTF-8 (the leading 🎲 is decorative and the -line reads fine without it), satisfying the protocol's plain-text requirement. -Randomness is seeded per roll from `/dev/urandom` (falling back to the PID), -so repeated rolls within the same second still differ. JSON output is escaped; -the bundled `module_json.awk` helper strictly parses the protocol fields while -keeping this module self-contained. diff --git a/modules/roll-module/module_json.awk b/modules/roll-module/module_json.awk index 15c973c..afbbc26 100644 --- a/modules/roll-module/module_json.awk +++ b/modules/roll-module/module_json.awk @@ -57,7 +57,8 @@ function utf8(code) { 128 + (int(code / 64) % 64), 128 + (code % 64)) } -function valid_utf8(value, i, total, first, second, width, j, continuation) { +function valid_utf8(value, reject_controls, i, total, first, second, + width, j, continuation) { i = 1 total = length(value) while (i <= total) { @@ -85,6 +86,9 @@ function valid_utf8(value, i, total, first, second, width, j, continuation) { (first == 237 && second > 159) || (first == 240 && second < 144) || (first == 244 && second > 143)) return 0 + if (reject_controls && + ((width == 1 && (first < 32 || first == 127)) || + (first == 194 && second >= 128 && second <= 159))) return 0 i += width } return 1 @@ -272,12 +276,16 @@ function parse_value(path, c, value, value_unsafe, rest) { skip_ws() c = substr(source, pos, 1) if (c == "\"") { - value = parse_string(path == wanted_path) - value_unsafe = string_unsafe - if (!invalid && string_ok && path == wanted_path && !found) { - result = value - found = 1 - unsafe_target = value_unsafe + value = parse_string(runtime || path == wanted_path) + value_unsafe = string_unsafe || !valid_utf8(value, 1) + if (!invalid && string_ok) { + if (runtime) { + if (!value_unsafe) string_value[path] = value + } else if (path == wanted_path && !found) { + result = value + found = 1 + unsafe_target = value_unsafe + } } } else if (c == "{") { parse_object(path) @@ -299,27 +307,124 @@ function parse_value(path, c, value, value_unsafe, rest) { } } +function clear_record( item) { + for (item in seen) delete seen[item] + for (item in string_value) delete string_value[item] +} + +function safe_string(scope_name, field_name, path) { + path = scope_name == "" ? field_name : scope_name SUBSEP field_name + if (!record_valid || !(path in string_value)) return "" + return string_value[path] +} + +function json_escape(value, out, i, c, code, hex) { + out = "" + hex = "0123456789abcdef" + for (i = 1; i <= length(value); i++) { + c = substr(value, i, 1) + code = byte[c] + if (c == "\\") out = out "\\\\" + else if (c == "\"") out = out "\\\"" + else if (code == 8) out = out "\\b" + else if (code == 12) out = out "\\f" + else if (code == 10) out = out "\\n" + else if (code == 13) out = out "\\r" + else if (code == 9) out = out "\\t" + else if (code < 32 || code == 127) { + out = out "\\u00" substr(hex, int(code / 16) + 1, 1) \ + substr(hex, (code % 16) + 1, 1) + } else { + out = out c + } + } + return out +} + +function utf8_truncate(value, limit) { + if (length(value) <= limit) return value + value = substr(value, 1, limit) + while (value != "" && !valid_utf8(value)) { + value = substr(value, 1, length(value) - 1) + } + return value +} + +function emit_message(value) { + value = utf8_truncate(value, 1023) + if (value == "" || !valid_utf8(value, 1)) return + printf "{\"type\":\"message.create\",\"plain_text\":\"%s\"}\n", \ + json_escape(value) +} + +function emit_event_ok() { + print "{\"type\":\"event.ok\"}" + fflush() +} + +function begin_event(name, version, type, protocol) { + type = safe_string("", "type") + if (type == "handshake") { + protocol = safe_string("", "protocol") + if (protocol == "tnt.module.v1") { + printf "{\"type\":\"handshake.ok\",\"protocol\":\"tnt.module.v1\"," \ + "\"module\":{\"name\":\"%s\",\"version\":\"%s\"}}\n", \ + name, version + } else { + print "{\"type\":\"error\",\"code\":\"unsupported_protocol\"," \ + "\"message\":\"requires tnt.module.v1\"}" + } + fflush() + return 0 + } + if (type != "message.created") { + emit_event_ok() + return 0 + } + return 1 +} + +function reseed_random( event_seed) { + seed_counter++ + event_seed = ((seed + seed_counter) % 2147483646) + 1 + srand(event_seed) +} + +function next_random() { + reseed_random() + return rand() +} + { - if (record_seen) { + if (!runtime && record_seen) { invalid = 1 next } - record_seen = 1 + if (!runtime) record_seen = 1 + clear_record() + invalid = 0 + found = 0 + unsafe_target = 0 + result = "" + record_valid = 0 source = $0 source_length = length(source) if (!valid_utf8(source)) { fail() - next + } else { + pos = 1 + wanted_path = scope == "" ? key : scope SUBSEP key + parse_value("") + skip_ws() + if (pos <= source_length) fail() + if (!invalid) record_valid = 1 } - pos = 1 - wanted_path = scope == "" ? key : scope SUBSEP key - parse_value("") - skip_ws() - if (pos <= source_length) fail() } END { - if (invalid || unsafe_target || !record_seen) exit 2 - if (!found) exit 1 - printf "%s", result + if (!runtime) { + if (invalid || unsafe_target || !record_seen) exit 2 + if (!found) exit 1 + printf "%s", result + } } diff --git a/modules/roll-module/roll-module.awk b/modules/roll-module/roll-module.awk new file mode 100644 index 0000000..5ebb338 --- /dev/null +++ b/modules/roll-module/roll-module.awk @@ -0,0 +1,70 @@ +BEGIN { + runtime = 1 +} + +function roll_result(spec, sender, dpos, ncount, rest, mod, mpos, i, c, + sides, n, s, total, rolls, label, result, modifier) { + if (spec == "") spec = "1d6" + gsub(/D/, "d", spec) + if (spec !~ /^[0-9]*d[0-9]+([+-][0-9]+)?$/) return "" + + dpos = index(spec, "d") + ncount = substr(spec, 1, dpos - 1) + rest = substr(spec, dpos + 1) + mod = 0 + mpos = 0 + for (i = 1; i <= length(rest); i++) { + c = substr(rest, i, 1) + if (c == "+" || c == "-") { + mpos = i + break + } + } + if (mpos > 0) { + sides = substr(rest, 1, mpos - 1) + mod = substr(rest, mpos) + 0 + } else { + sides = rest + } + + n = ncount == "" ? 1 : ncount + 0 + s = sides + 0 + if (n < 1 || n > 20 || s < 2 || s > 1000 || + mod < -10000 || mod > 10000) return "" + + reseed_random() + total = 0 + rolls = "" + for (i = 0; i < n; i++) { + result = int(rand() * s) + 1 + total += result + rolls = rolls (i == 0 ? "" : " + ") result + } + label = (ncount == "" ? "" : n) "d" s + if (mod != 0) label = label (mod > 0 ? "+" mod : mod) + result = total + mod + if (n == 1 && mod == 0) { + return "🎲 " sender " rolled " label " → " total + } + modifier = mod > 0 ? " (+" mod ")" : (mod < 0 ? " (" mod ")" : "") + return "🎲 " sender " rolled " label " → " rolls modifier " = " result +} + +{ + if (!begin_event("roll-module", "0.2.0")) next + text = safe_string("message", "plain_text") + if (text == "/roll" || substr(text, 1, 6) == "/roll ") { + rest = substr(text, 6) + sub(/^ +/, "", rest) + sub(/ +$/, "", rest) + sender = safe_string("message", "sender") + if (sender == "") sender = "someone" + result = roll_result(rest, sender) + if (result == "") { + result = "🎲 roll usage: /roll [N]d[+/-K] e.g. " \ + "/roll 2d6, /roll d20, /roll 3d6+2" + } + emit_message(result) + } + emit_event_ok() +} diff --git a/modules/roll-module/roll-module.sh b/modules/roll-module/roll-module.sh index 0bbecc1..1343991 100755 --- a/modules/roll-module/roll-module.sh +++ b/modules/roll-module/roll-module.sh @@ -1,170 +1,8 @@ #!/bin/sh -# TNT roll-module: a dice roller for tnt.module.v1. -# -# Reacts to chat messages that begin with "/roll" and replies with a public -# dice result. All other messages are acknowledged with a no-op so the module -# stays quiet and is never flagged for protocol errors during normal chat. -# -# Supported syntax (case-insensitive d): -# /roll -> 1d6 -# /roll d20 -> one 20-sided die -# /roll 3d6 -> three 6-sided dice, summed -# /roll 2d6+3 -> with a flat modifier (+/-) -# Bounds: 1..20 dice, 2..1000 sides, modifier within +/-10000. - -json_escape() { - printf '%s' "$1" | LC_ALL=C awk ' - BEGIN { - ORS = "" - hex = "0123456789abcdef" - for (i = 1; i <= 255; i++) byte[sprintf("%c", i)] = i - } - { - if (NR > 1) printf "%s", "\\n" - for (i = 1; i <= length($0); i++) { - c = substr($0, i, 1) - if (c == "\\") printf "%s", "\\\\" - else if (c == "\"") printf "%s", "\\\"" - else if (c == "\b") printf "%s", "\\b" - else if (c == "\f") printf "%s", "\\f" - else if (c == "\t") printf "%s", "\\t" - else if (c == "\r") printf "%s", "\\r" - else { - value = byte[c] - if (value < 32 || value == 127) { - printf "\\u00%s%s", substr(hex, int(value / 16) + 1, 1), \ - substr(hex, (value % 16) + 1, 1) - } else { - printf "%s", c - } - } - } - } - ' -} - -json_string_field() { - scope=$1 - key=$2 - line=$3 - printf '%s\n' "$line" | LC_ALL=C awk -v scope="$scope" -v key="$key" \ - -f ./module_json.awk -} - -seed_base= -seed_counter=0 - -next_seed() { - if [ -z "$seed_base" ]; then - seed_base=$(od -An -N4 -tu4 /dev/null) - while [ "${seed_base# }" != "$seed_base" ]; do seed_base=${seed_base# }; done - while [ "${seed_base% }" != "$seed_base" ]; do seed_base=${seed_base% }; done - case "$seed_base" in ''|*[!0-9]*) seed_base=$$ ;; esac - fi - seed_counter=$((seed_counter + 1)) - event_seed=$(((seed_base + seed_counter) % 2147483646 + 1)) -} - -# Compute the plain-text dice result for a spec like "2d6+3". -# Prints exactly the user-visible line to emit. -roll_result() { - spec=$1 - sender=$2 - seed=$3 - - # Pass untrusted strings as input records. awk -v assignments interpret - # backslash escapes, which can corrupt a literal sender or dice spec. - { - printf '%s\n' "$sender" - printf '%s\n' "$spec" - } | LC_ALL=C awk -v seed="$seed" ' - function usage() { - printf "🎲 roll usage: /roll [N]d[+/-K] e.g. /roll 2d6, /roll d20, /roll 3d6+2\n" - exit 0 - } - NR == 1 { sender = $0; next } - NR == 2 { spec = $0; next } - END { - srand(seed) - if (sender == "") sender = "someone" - if (spec == "") spec = "1d6" - gsub(/D/, "d", spec) - - if (spec !~ /^[0-9]*d[0-9]+([+-][0-9]+)?$/) usage() - - dpos = index(spec, "d") - ncount = substr(spec, 1, dpos - 1) - rest = substr(spec, dpos + 1) - - mod = 0 - mpos = 0 - for (i = 1; i <= length(rest); i++) { - c = substr(rest, i, 1) - if (c == "+" || c == "-") { mpos = i; break } - } - if (mpos > 0) { - sides = substr(rest, 1, mpos - 1) - mod = substr(rest, mpos) + 0 - } else { - sides = rest - } - - n = (ncount == "") ? 1 : ncount + 0 - s = sides + 0 - if (n < 1 || n > 20) usage() - if (s < 2 || s > 1000) usage() - if (mod > 10000 || mod < -10000) usage() - - total = 0 - out = "" - for (i = 0; i < n; i++) { - r = int(rand() * s) + 1 - total += r - out = out (i == 0 ? "" : " + ") r - } - label = ((ncount == "") ? "" : n) "d" s - if (mod != 0) label = label (mod > 0 ? "+" mod : mod) - res = total + mod - - if (n == 1 && mod == 0) { - printf "🎲 %s rolled %s → %d\n", sender, label, total - } else { - modtxt = (mod > 0 ? " (+" mod ")" : (mod < 0 ? " (" mod ")" : "")) - printf "🎲 %s rolled %s → %s%s = %d\n", sender, label, out, modtxt, res - } - } - ' -} - -while IFS= read -r line; do - type=$(json_string_field "" type "$line") - if [ "$type" = "handshake" ]; then - protocol=$(json_string_field "" protocol "$line") - if [ "$protocol" = "tnt.module.v1" ]; then - printf '{"type":"handshake.ok","protocol":"tnt.module.v1","module":{"name":"roll-module","version":"0.2.0"}}\n' - else - printf '{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"}\n' - fi - elif [ "$type" = "message.created" ]; then - plain_text=$(json_string_field message plain_text "$line") - case "$plain_text" in - "/roll"|"/roll "*) - sender=$(json_string_field message sender "$line") - rest=${plain_text#/roll} - # trim leading spaces from the dice spec - while [ "${rest# }" != "$rest" ]; do rest=${rest# }; done - while [ "${rest% }" != "$rest" ]; do rest=${rest% }; done - next_seed - result=$(roll_result "$rest" "$sender" "$event_seed") - escaped=$(json_escape "$result") - printf '{"type":"message.create","plain_text":"%s"}\n' "$escaped" - printf '{"type":"event.ok"}\n' - ;; - *) - printf '{"type":"event.ok"}\n' - ;; - esac - else - printf '{"type":"event.ok"}\n' - fi -done +LC_ALL=C +export LC_ALL +seed=$(od -An -N4 -tu4 /dev/null) +while [ "${seed# }" != "$seed" ]; do seed=${seed# }; done +while [ "${seed% }" != "$seed" ]; do seed=${seed% }; done +case "$seed" in ''|*[!0-9]*) seed=$$ ;; esac +exec awk -v seed="$seed" -f ./module_json.awk -f ./roll-module.awk diff --git a/protocol/README.md b/protocol/README.md deleted file mode 100644 index c79281b..0000000 --- a/protocol/README.md +++ /dev/null @@ -1,161 +0,0 @@ -# TNT Module Protocol - -This document defines the compatibility contract for TNT community modules. -The first implementation target is external-process modules that exchange -JSON Lines with TNT over stdin/stdout. - -## Compatibility - -- Protocol version: `tnt.module.v1` -- Transport: UTF-8 JSON Lines -- Framing: one complete JSON object per line -- Direction: TNT sends events to module stdin; modules write responses to - stdout -- Event completion: every non-handshake event ends with exactly one `event.ok` - response -- Error stream: modules should write diagnostics to stderr -- License: protocol examples and official community modules should use TNT's - license unless a module states stricter terms - -TNT may add optional fields to existing messages. Modules must ignore unknown -fields. TNT must ignore unknown response fields unless the response type -explicitly requires them. - -## Manifest - -Each module declares metadata in `tnt-module.json`. - -```json -{ - "protocol": "tnt.module.v1", - "name": "echo-module", - "version": "0.2.0", - "tnt_min_version": "1.1.0", - "description": "Echoes chat messages back to TNT.", - "entrypoint": "./echo-module.sh", - "permissions": ["message:read", "message:create"], - "events": ["message.created"] -} -``` - -Required fields: - -- `protocol`: protocol compatibility string. Use `tnt.module.v1`. -- `name`: stable module identifier, lowercase ASCII, `a-z`, `0-9`, and `-`. - TNT 1.1.0 caps module names at 56 bytes so generated `module:` - senders fit the core message username limit. -- `version`: module version in `MAJOR.MINOR.PATCH` form (for example, - `0.2.0`). -- `entrypoint`: executable path relative to the manifest directory. Current - TNT rejects absolute paths, `..`, whitespace, control characters, and shell - metacharacters in entrypoints. -- `permissions`: explicit capabilities requested by the module. -- `events`: event names the module wants to receive. - -Optional fields: - -- `description`: human-readable module summary. -- `tnt_min_version`: minimum TNT version expected by the module. TNT 1.1.0's - module checker and install wizard use this to reject modules that require a - newer core. -- Additional descriptive metadata may be added by module repositories, but - modules should not depend on TNT core reading unknown metadata fields. - -Current TNT `tnt.module.v1` runtime support is intentionally narrow: modules -that receive `message.created` events must request `message:read`, and modules -that emit `message.create` responses must request `message:create`. - -## Transport - -TNT and modules communicate with JSON Lines over stdio: - -- TNT writes one JSON object per line to module stdin. -- The module writes one JSON object per line to stdout. -- The module writes logs and diagnostics to stderr. -- Messages must be UTF-8. -- Each line must contain exactly one complete JSON object. -- Keep each JSON payload at or below 4,094 bytes so the payload and newline fit - completely in TNT's 4,096-byte line buffer. -- Current TNT runtimes accept at most eight response records for one event. -- A `message.create` `plain_text` value must decode to 1–1,023 UTF-8 bytes and - must not contain C0 or DEL control characters. - -## Handshake - -After startup, TNT sends a handshake request: - -```json -{"type":"handshake","protocol":"tnt.module.v1","server":{"name":"tnt","version":"1.1.0"}} -``` - -The module responds: - -```json -{"type":"handshake.ok","protocol":"tnt.module.v1","module":{"name":"echo-module","version":"0.2.0"}} -``` - -If the module cannot support the requested protocol version, it responds with -an error: - -```json -{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"} -``` - -## Events - -TNT sends events to the module: - -```json -{ - "type": "message.created", - "message": { - "id": "local-00000001", - "timestamp": "2026-06-04T12:00:00Z", - "sender": "alice", - "kind": "text", - "plain_text": "hello", - "metadata": {} - } -} -``` - -For every event after the handshake, the module emits zero or more action -records followed by exactly one `event.ok` terminator. For a chat response, the -complete response sequence is: - -```json -{"type":"message.create","plain_text":"echo: hello"} -{"type":"event.ok"} -``` - -When no action is needed, the complete response is just: - -```json -{"type":"event.ok"} -``` - -`event.ok` is a framing terminator, not an optional acknowledgement. Omitting it -forces TNT to wait for the per-event response timeout before dispatch can -continue; emitting more than one can terminate a later event accidentally. The -startup handshake is the sole exception: it ends with `handshake.ok`, not -`event.ok`. - -TNT 1.1.0 and newer disable a module that floods one event with too many -responses or repeatedly emits invalid response records. Modules should keep -generated messages sparse. - -## Errors - -Modules can report protocol negotiation failures during the startup handshake -with: - -```json -{"type":"error","code":"unsupported_protocol","message":"requires tnt.module.v1"} -``` - -Use stable, lowercase `code` values. Current TNT runtimes accept only -`message.create` actions and the final `event.ok` while processing an event, so -event-specific validation failures should produce a user-visible -`message.create` when useful, then `event.ok`; otherwise they should produce -only `event.ok`. Write implementation diagnostics to stderr. Every -module-created message must include a plain-text fallback through `plain_text`. diff --git a/scripts/module_json.awk b/scripts/module_json.awk index 15c973c..afbbc26 100644 --- a/scripts/module_json.awk +++ b/scripts/module_json.awk @@ -57,7 +57,8 @@ function utf8(code) { 128 + (int(code / 64) % 64), 128 + (code % 64)) } -function valid_utf8(value, i, total, first, second, width, j, continuation) { +function valid_utf8(value, reject_controls, i, total, first, second, + width, j, continuation) { i = 1 total = length(value) while (i <= total) { @@ -85,6 +86,9 @@ function valid_utf8(value, i, total, first, second, width, j, continuation) { (first == 237 && second > 159) || (first == 240 && second < 144) || (first == 244 && second > 143)) return 0 + if (reject_controls && + ((width == 1 && (first < 32 || first == 127)) || + (first == 194 && second >= 128 && second <= 159))) return 0 i += width } return 1 @@ -272,12 +276,16 @@ function parse_value(path, c, value, value_unsafe, rest) { skip_ws() c = substr(source, pos, 1) if (c == "\"") { - value = parse_string(path == wanted_path) - value_unsafe = string_unsafe - if (!invalid && string_ok && path == wanted_path && !found) { - result = value - found = 1 - unsafe_target = value_unsafe + value = parse_string(runtime || path == wanted_path) + value_unsafe = string_unsafe || !valid_utf8(value, 1) + if (!invalid && string_ok) { + if (runtime) { + if (!value_unsafe) string_value[path] = value + } else if (path == wanted_path && !found) { + result = value + found = 1 + unsafe_target = value_unsafe + } } } else if (c == "{") { parse_object(path) @@ -299,27 +307,124 @@ function parse_value(path, c, value, value_unsafe, rest) { } } +function clear_record( item) { + for (item in seen) delete seen[item] + for (item in string_value) delete string_value[item] +} + +function safe_string(scope_name, field_name, path) { + path = scope_name == "" ? field_name : scope_name SUBSEP field_name + if (!record_valid || !(path in string_value)) return "" + return string_value[path] +} + +function json_escape(value, out, i, c, code, hex) { + out = "" + hex = "0123456789abcdef" + for (i = 1; i <= length(value); i++) { + c = substr(value, i, 1) + code = byte[c] + if (c == "\\") out = out "\\\\" + else if (c == "\"") out = out "\\\"" + else if (code == 8) out = out "\\b" + else if (code == 12) out = out "\\f" + else if (code == 10) out = out "\\n" + else if (code == 13) out = out "\\r" + else if (code == 9) out = out "\\t" + else if (code < 32 || code == 127) { + out = out "\\u00" substr(hex, int(code / 16) + 1, 1) \ + substr(hex, (code % 16) + 1, 1) + } else { + out = out c + } + } + return out +} + +function utf8_truncate(value, limit) { + if (length(value) <= limit) return value + value = substr(value, 1, limit) + while (value != "" && !valid_utf8(value)) { + value = substr(value, 1, length(value) - 1) + } + return value +} + +function emit_message(value) { + value = utf8_truncate(value, 1023) + if (value == "" || !valid_utf8(value, 1)) return + printf "{\"type\":\"message.create\",\"plain_text\":\"%s\"}\n", \ + json_escape(value) +} + +function emit_event_ok() { + print "{\"type\":\"event.ok\"}" + fflush() +} + +function begin_event(name, version, type, protocol) { + type = safe_string("", "type") + if (type == "handshake") { + protocol = safe_string("", "protocol") + if (protocol == "tnt.module.v1") { + printf "{\"type\":\"handshake.ok\",\"protocol\":\"tnt.module.v1\"," \ + "\"module\":{\"name\":\"%s\",\"version\":\"%s\"}}\n", \ + name, version + } else { + print "{\"type\":\"error\",\"code\":\"unsupported_protocol\"," \ + "\"message\":\"requires tnt.module.v1\"}" + } + fflush() + return 0 + } + if (type != "message.created") { + emit_event_ok() + return 0 + } + return 1 +} + +function reseed_random( event_seed) { + seed_counter++ + event_seed = ((seed + seed_counter) % 2147483646) + 1 + srand(event_seed) +} + +function next_random() { + reseed_random() + return rand() +} + { - if (record_seen) { + if (!runtime && record_seen) { invalid = 1 next } - record_seen = 1 + if (!runtime) record_seen = 1 + clear_record() + invalid = 0 + found = 0 + unsafe_target = 0 + result = "" + record_valid = 0 source = $0 source_length = length(source) if (!valid_utf8(source)) { fail() - next + } else { + pos = 1 + wanted_path = scope == "" ? key : scope SUBSEP key + parse_value("") + skip_ws() + if (pos <= source_length) fail() + if (!invalid) record_valid = 1 } - pos = 1 - wanted_path = scope == "" ? key : scope SUBSEP key - parse_value("") - skip_ws() - if (pos <= source_length) fail() } END { - if (invalid || unsafe_target || !record_seen) exit 2 - if (!found) exit 1 - printf "%s", result + if (!runtime) { + if (invalid || unsafe_target || !record_seen) exit 2 + if (!found) exit 1 + printf "%s", result + } } diff --git a/scripts/release_check.sh b/scripts/release_check.sh index 6d94a66..df5d747 100755 --- a/scripts/release_check.sh +++ b/scripts/release_check.sh @@ -16,6 +16,7 @@ version=$(tr -d '\r\n' < VERSION) python3 - "$version" <<'PY' || exit 1 import re import sys +from pathlib import Path version = sys.argv[1] if re.fullmatch( @@ -23,12 +24,16 @@ if re.fullmatch( ) is None: print(f"release-check: invalid semantic version: {version}", file=sys.stderr) raise SystemExit(1) -PY -grep -Fq "current repository release is \`$version\`" README.md || - fail "README release does not match $version" -grep -Eq "^## $version - [0-9]{4}-[0-9]{2}-[0-9]{2}$" CHANGELOG.md || - fail "CHANGELOG has no dated $version release section" +manual_header = Path("tnt-modules.7").read_text(encoding="utf-8").splitlines()[0] +manual_pattern = ( + r'\.TH TNT-MODULES 7 "[0-9]{4}-[0-9]{2}-[0-9]{2}" ' + rf'"tnt-modules {re.escape(version)}"' +) +if re.fullmatch(manual_pattern, manual_header) is None: + print(f"release-check: manual release does not match {version}", file=sys.stderr) + raise SystemExit(1) +PY if [ "$#" -gt 1 ]; then fail "usage: scripts/release_check.sh [vX.Y.Z]" @@ -41,5 +46,37 @@ if [ -n "$release_ref" ] && [ "$release_ref" != "v$version" ]; then fail "tag $release_ref does not match VERSION $version" fi -make test +make man-check test + +stage=$(mktemp -d "${TMPDIR:-/tmp}/tnt-modules-release.XXXXXX") +cleanup() { + rm -rf "$stage" +} +trap cleanup EXIT INT TERM + +make DESTDIR="$stage" PREFIX=/usr install +[ -f "$stage/usr/share/man/man7/tnt-modules.7" ] || + fail "staged install is missing tnt-modules.7" +for module in 8ball-module choose-module flip-module quote-module \ + roll-module; do + dir="$stage/usr/libexec/tnt/modules/$module" + [ -x "$dir/$module.sh" ] || + fail "staged install is missing executable $module.sh" + [ -f "$dir/module_json.awk" ] || + fail "staged install is missing $module/module_json.awk" + [ -f "$dir/$module.awk" ] || + fail "staged install is missing $module/$module.awk" + [ -f "$dir/tnt-module.json" ] || + fail "staged install is missing $module/tnt-module.json" +done + +make DESTDIR="$stage" PREFIX=/usr uninstall +[ ! -e "$stage/usr/share/man/man7/tnt-modules.7" ] || + fail "uninstall left tnt-modules.7" +for module in 8ball-module choose-module flip-module quote-module \ + roll-module; do + [ ! -e "$stage/usr/libexec/tnt/modules/$module" ] || + fail "uninstall left the $module directory" +done + echo "release-check: tnt-modules $version is ready" diff --git a/tests/test_modules_behavior.sh b/tests/test_modules_behavior.sh index 346bdd6..fef2128 100755 --- a/tests/test_modules_behavior.sh +++ b/tests/test_modules_behavior.sh @@ -695,18 +695,26 @@ $(nl -ba "$literal_file")" assert_json_escape_semantics() { escape_label=$1 - escape_dir=$2 - escape_entry=$3 + escape_parser=$2 escape_file="$STATE_DIR/$escape_label-json-escape.out" + escape_program="$STATE_DIR/json-escape.awk" + cat >"$escape_program" <<'AWK' +BEGIN { + runtime = 1 + value = "quote=\" slash=\\ tab=" sprintf("%c", 9) \ + " backspace=" sprintf("%c", 8) \ + " formfeed=" sprintf("%c", 12) \ + " carriage=" sprintf("%c", 13) \ + " newline=" sprintf("%c", 10) \ + " control=" sprintf("%c", 1) \ + " delete=" sprintf("%c", 127) " utf8=🙂" + printf "%s", json_escape(value) + exit +} +AWK - if ( - cd "$ROOT/$escape_dir" - ENTRYPOINT=$escape_entry /bin/sh -s <<'SH' -. "./$ENTRYPOINT" "$escape_file" 2>"$escape_file.err"; then + if LC_ALL=C awk -f "$ROOT/$escape_parser" \ + -f "$escape_program" "$escape_file" 2>"$escape_file.err"; then : else fail_case "$escape_label: JSON escaping is portable" \ @@ -895,6 +903,8 @@ assert_parser_result escaped-control 2 '' \ '{"message":{"plain_text":"unsafe\u0001text"}}' message plain_text assert_parser_result escaped-newline 2 '' \ '{"message":{"plain_text":"unsafe\ntext"}}' message plain_text +assert_parser_result escaped-c1 2 '' \ + '{"message":{"plain_text":"unsafe\u0085text"}}' message plain_text assert_parser_result unrelated-escaped-control 0 '/flip' \ '{"metadata":{"note":"line\nwith\ttabs\u0001"},"message":{"plain_text":"/flip"}}' message plain_text @@ -921,12 +931,15 @@ else "expected status 2 with no output, got $parser_invalid_utf8_status" fi -assert_json_escape_semantics roll modules/roll-module roll-module.sh -assert_json_escape_semantics flip modules/flip-module flip-module.sh -assert_json_escape_semantics 8ball modules/8ball-module 8ball-module.sh -assert_json_escape_semantics choose modules/choose-module choose-module.sh -assert_json_escape_semantics quote modules/quote-module quote-module.sh -assert_json_escape_semantics echo examples/echo-module echo-module.sh +parser_raw_c1=$(printf '{"message":{"plain_text":"unsafe\302\205text"}}') +assert_parser_result raw-c1 2 '' "$parser_raw_c1" message plain_text + +assert_json_escape_semantics roll modules/roll-module/module_json.awk +assert_json_escape_semantics flip modules/flip-module/module_json.awk +assert_json_escape_semantics 8ball modules/8ball-module/module_json.awk +assert_json_escape_semantics choose modules/choose-module/module_json.awk +assert_json_escape_semantics quote modules/quote-module/module_json.awk +assert_json_escape_semantics echo examples/echo-module/module_json.awk # --- roll-module --- assert_handshakes roll modules/roll-module roll-module.sh roll-module @@ -1100,6 +1113,11 @@ assert_noop_event echo examples/echo-module echo-module.sh \ '{"type":"message.created","message":{"sender":"frank","plain_text":"unsafe\u0001text"}}' escaped-control assert_noop_event echo examples/echo-module echo-module.sh \ '{"type":"message.created","message":{"sender":"frank","plain_text":"unsafe\ntext"}}' escaped-newline +assert_noop_event echo examples/echo-module echo-module.sh \ + '{"type":"message.created","message":{"sender":"frank","plain_text":"unsafe\u0085text"}}' escaped-c1 +echo_raw_c1=$(printf '{"type":"message.created","message":{"sender":"frank","plain_text":"unsafe\302\205text"}}') +assert_noop_event echo examples/echo-module echo-module.sh \ + "$echo_raw_c1" raw-c1 echo_bad_event_file="$STATE_DIR/echo-missing-plain-text.out" module_out "$echo_bad_event_file" examples/echo-module echo-module.sh \ diff --git a/tnt-modules.7 b/tnt-modules.7 new file mode 100644 index 0000000..67456e2 --- /dev/null +++ b/tnt-modules.7 @@ -0,0 +1,125 @@ +.TH TNT-MODULES 7 "2026-08-18" "tnt-modules 0.3.0" +.SH NAME +tnt\-modules \- bundled chat commands for TNT +.SH SYNOPSIS +.EX +\fBTNT_MODULE_PATHS=\fP\fImodule-dir\fP\ +[\fB:\fP\fImodule-dir\fP]...\ \fBtnt\fP +.EE +.SH DESCRIPTION +.B tnt\-modules +supplies five optional external-process modules for +.BR tnt (8). +TNT starts each enabled module as a separate child process. +The bundled modules receive public chat messages. +A matching module may publish a public reply under its module name. +Several modules can be enabled together. +Other commands and normal conversation produce no bundled reply. +.SS Bundled commands +Command names are case-sensitive. +Each command must begin the message. +It must end the message or be followed by an ASCII space. +.TP +.BI "/roll [" count "]d" sides "[+/\-" modifier "]" +Roll dice and publish the individual rolls and total. +With no dice expression, roll one six-sided die. +The letter +.B d +is case-insensitive. +.I count +must be 1\(en20, +.I sides +must be 2\(en1000, and the absolute value of +.I modifier +must not exceed 10000. +An invalid expression produces a short usage reply. +.TP +.B /flip +Publish either heads or tails. +Trailing text is ignored. +.TP +.BI "/8ball [" question "]" +Publish one of the 20 classic Magic 8-Ball answers. +The question is optional. +.TP +.BI "/choose " option " | " option " [| " option ]... +Publish one randomly selected pipe-separated option. +Leading and trailing spaces and tabs are removed from each option. +At least two nonempty options are required; +otherwise the module produces a short usage reply. +.TP +.B /quote +Publish a random proverb from the module's built-in list. +Trailing text is ignored. +.SH SECURITY +Module processes run as the TNT service account. +They inherit its user, group, filesystem, and network privileges. +They are not an operating-system sandbox. +Manifest permissions describe protocol capabilities; +they do not restrict system calls or resource access. +.PP +The bundled modules perform no network operations. +Review any replacement or additional module before enabling it, +keep its directory from being writable by untrusted users, +and run TNT under a dedicated least-privileged account. +Use an operating-system sandbox or container for stronger isolation. +.PP +TNT can disable a module that stalls or violates the protocol. +That supervision does not contain filesystem or network side effects. +.SH ENVIRONMENT +.TP +.B TNT_MODULE_PATHS +A colon-separated list of module directories read when TNT starts. +Each directory must contain +.I tnt\-module.json +and the executable entrypoint named by that manifest. +An empty or unset value disables external modules. +TNT enables at most eight valid modules. +Restart TNT after changing the value. +.IP +Relative directories are resolved from TNT's working directory. +Use absolute directories in service configuration. +For the default +.B make install +layout, +enable the dice and coin modules with: +.EX +TNT_MODULE_PATHS=/usr/local/libexec/tnt/modules/roll\-module:\e +/usr/local/libexec/tnt/modules/flip\-module \e + tnt +.EE +.SH FILES +.TP +.I /usr/local/libexec/tnt/modules/ +Default installation root for the five module directories. +Changing +.B PREFIX +or +.B MODULEDIR +when running +.B make install +changes this path. +.TP +.I modules/ +Contains the bundled +.BR 8ball\-module , +.BR choose\-module , +.BR flip\-module , +.BR quote\-module , +and +.B roll\-module +directories in the source distribution. +Pass an individual child directory, not this parent directory, in +.BR TNT_MODULE_PATHS . +Each child contains its manifest, executable entrypoint, JSON parser, and +module program. +.SH VERSIONS +The bundled manifests require TNT 1.1.0 or later and use the +.B tnt.module.v1 +protocol. +TNT checks the manifest protocol and startup handshake. +It enables only modules that pass both checks. +.SH SEE ALSO +.BR tntctl (1), +.BR tnt\-module\-protocol (7), +.BR tnt (8)