Compare commits

...
32 Commits
Author SHA1 Message Date
Your Name c88b20430a v0.1.3 - Make cashu wallet initialization unconditional and add lazy wallet readiness for first-run DM tool usage 2026-03-19 19:26:12 -04:00
Your Name 8cfc50acf6 v0.1.2 - Implement cashu_wallet_receive_token tool flow and integrate Cashu receive/swap handling 2026-03-19 18:55:38 -04:00
Your Name e9fb1fa0b8 v0.1.1 - Fix cron trigger firing with validation, shorthand normalization, immediate polling, and status/log diagnostics 2026-03-19 17:16:06 -04:00
Your Name 9505ee16bf v0.1.0 - Release dual-architecture static binaries (x86_64 + arm64) 2026-03-19 07:56:55 -04:00
Your Name d49e4ec4cb v0.0.89 - Fix and validate fully static ARM64 Docker builds for didactyl and c-relay with reliable cross-arch context and toolchain handling 2026-03-19 07:40:57 -04:00
Your Name 47bb5d76bc v0.0.88 - Add full static ARM64 build support for didactyl and c-relay with dynamic nostr lib resolution and --platform override 2026-03-18 19:34:33 -04:00
Your Name 90948989ac v0.0.87 - Fix config_store d_tag use-after-free causing llm_config replacement failures 2026-03-18 17:54:53 -04:00
Your Name b1a767f9b5 v0.0.86 - Return masked api_key field in model_get/model_set responses 2026-03-18 17:42:16 -04:00
Your Name 650df7bc41 v0.0.85 - Skip llm_config republish on startup when config was recalled from Nostr 2026-03-18 17:34:11 -04:00
Your Name 9d06f18769 v0.0.84 - Remove duplicated read-only tool payload fields and make slash output prefer content 2026-03-18 16:48:04 -04:00
Your Name 527016c078 v0.0.83 - Add my_kind0_profile cache-miss fallback to query kind-0 from relays and cache result 2026-03-18 16:32:14 -04:00
Your Name c221104bc0 v0.0.82 - Move model/task persistence to kind 30078, add finish_reason stall diagnostics, and remove local config/tasks file coupling 2026-03-18 15:58:33 -04:00
Your Name 253aa4b5fc v0.0.81 - Add loop progress controls and admin limit diagnostics for DM, HTTP API, and triggers 2026-03-18 14:16:10 -04:00
Your Name 82362e4f3f v0.0.80 - Fix wizard/runtime config persistence and add --admin CLI override for agent_config updates 2026-03-18 11:21:57 -04:00
Your Name 7675109afc v0.0.79 - Enhance existing-agent wizard with full config recovery review edit flow and new-agent fallback 2026-03-18 10:14:10 -04:00
Your Name 42fc14a5b3 v0.0.78 - Seed default skill into self-skill cache during startup reconcile 2026-03-18 09:46:08 -04:00
Your Name 326acb63d1 v0.0.77 - Wizard now verifies systemd service is active after install, reports admin inbox expectation, and exits to avoid duplicate foreground boot 2026-03-18 07:44:16 -04:00
Your Name 6b6e25c3f4 v0.0.76 - Use sudo-prefixed privileged commands in setup wizard install flow with password prompting and remove root-shell handoff 2026-03-18 07:07:30 -04:00
Your Name 9a0e90dff0 v0.0.75 - Add rsync deploy script and wizard root-shell handoff for service install path 2026-03-18 06:54:30 -04:00
Your Name 0ce9de002b v0.0.74 - Add default skill d-tag so startup-published kind 31124 events seed self-skill cache and appear in available skills 2026-03-18 06:31:07 -04:00
Your Name 70403854ff v0.0.73 - Refined Nostr handler and tool dispatch/schema updates for relay and my-events flows 2026-03-17 10:30:22 -04:00
Your Name 0cc0667a80 v0.0.72 - Refined wizard framing and menu hotkey display; diagnosed hardcoded Didactyl fallback causing name mismatch 2026-03-16 14:37:04 -04:00
Your Name 5857058a21 v0.0.71 - Add nprofile, nevent, and naddr support to nostr_encode with argument validation 2026-03-13 15:42:28 -04:00
Your Name f9cb6b19c2 v0.0.70 - Add c_utils_lib category-based debug filtering with tests/docs and root API log tail shortcut script 2026-03-13 09:30:37 -04:00
Your Name 868ac46de2 v0.0.69 - Add startup skill to publish core docs as longform notes and switch admin announcement DMs to NIP-04 2026-03-12 10:36:04 -04:00
Your Name 35f2fe53f1 chore: update .gitignore to exclude large logs and binaries 2026-03-12 03:02:41 -04:00
Your Name 5cdd582990 v0.0.68 - Update SKILLS.md with seed determinism fields and private kind 31124 NIP-44 encrypted payload spec 2026-03-12 02:19:03 -04:00
Your Name 5b8b8310f7 v0.0.67 - Add agent self-context subscriptions, tools, aliases, and prompt template sections 2026-03-10 17:33:35 -04:00
Your Name 6dbd952023 v0.0.66 - Complete tools refactor, move all tools-named sources/headers into src/tools, and update build wiring 2026-03-10 15:37:31 -04:00
Your Name 1d4cb9407d v0.0.65 - Filter skill_list by 10123 adoption tags, gate live trigger registration on adoption, and allow underscores in skill d-tags 2026-03-10 10:40:17 -04:00
Your Name 5c3083894b v0.0.64 - Just keeping things fresh 2026-03-10 10:03:29 -04:00
Your Name f0bd4c6473 v0.0.63 - Deprecate template trigger action and force llm execution path 2026-03-10 07:54:19 -04:00
86 changed files with 38654 additions and 15030 deletions
+5 -2
View File
@@ -9,8 +9,8 @@
test_keys.txt
/mongoose/
/Trash/
deploy_lt.sh
# Build artifacts
/build/
@@ -19,6 +19,9 @@ test_keys.txt
*.a
*.tar.gz
debug.log
context.log
didactyl_static_x86_64
didactyl_static_x86_64_debug
a.out
# Editor/IDE
+1 -1
View File
@@ -2,6 +2,6 @@
description: "Increments and pushes the repo"
---
Run increment_and_push.sh followed in the command line with a good description of the changes that were made.
Run increment_and_push.sh followed in the command line with a good description of the changes that were made. Don't run any other git commands.
For example: ./increment_and_push.sh "Fixed that nasty bug"
+66 -40
View File
@@ -8,41 +8,58 @@ FROM alpine:3.19 AS builder
# Re-declare build argument in this stage
ARG DEBUG_BUILD=false
# Install build dependencies
RUN apk add --no-cache \
build-base \
musl-dev \
git \
cmake \
pkgconfig \
autoconf \
automake \
libtool \
openssl-dev \
openssl-libs-static \
zlib-dev \
zlib-static \
curl-dev \
curl-static \
nghttp2-dev \
nghttp2-static \
c-ares-dev \
c-ares-static \
libpsl-dev \
libpsl-static \
libidn2-dev \
libidn2-static \
libunistring-dev \
libunistring-static \
brotli-dev \
brotli-static \
zstd-dev \
zstd-static \
sqlite-dev \
sqlite-static \
linux-headers \
wget \
bash
# Install build dependencies (with retry logic for transient mirror/network failures)
RUN set -eux; \
printf '%s\n' \
'https://dl-cdn.alpinelinux.org/alpine/v3.19/main' \
'https://dl-cdn.alpinelinux.org/alpine/v3.19/community' \
> /etc/apk/repositories; \
APK_OK=0; \
for attempt in 1 2 3 4 5; do \
if apk update && apk add --no-cache \
build-base \
musl-dev \
git \
cmake \
pkgconfig \
autoconf \
automake \
libtool \
openssl-dev \
openssl-libs-static \
zlib-dev \
zlib-static \
curl-dev \
curl-static \
nghttp2-dev \
nghttp2-static \
c-ares-dev \
c-ares-static \
libpsl-dev \
libpsl-static \
libidn2-dev \
libidn2-static \
libunistring-dev \
libunistring-static \
brotli-dev \
brotli-static \
zstd-dev \
zstd-static \
sqlite-dev \
sqlite-static \
linux-headers \
wget \
bash; then \
APK_OK=1; \
break; \
fi; \
echo "apk dependency install failed (attempt ${attempt}/5), retrying..."; \
sleep $((attempt * 2)); \
done; \
if [ "$APK_OK" -ne 1 ]; then \
echo "ERROR: failed to install Alpine dependencies after 5 attempts"; \
exit 33; \
fi
# Set working directory
WORKDIR /build
@@ -68,6 +85,7 @@ COPY nostr_core_lib /build/nostr_core_lib/
RUN cd nostr_core_lib && \
chmod +x build.sh && \
sed -i 's/CFLAGS="-Wall -Wextra -std=c99 -fPIC -O2"/CFLAGS="-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 -Wall -Wextra -std=c99 -fPIC -O2"/' build.sh && \
sed -i 's/CC="aarch64-linux-gnu-gcc"/CC="gcc"/' build.sh && \
rm -f *.o *.a 2>/dev/null || true && \
./build.sh --nips=all
@@ -78,7 +96,10 @@ COPY Makefile /build/Makefile
# Build didactyl with full static linking (only rebuilds when src/ changes)
# Disable fortification to avoid __*_chk symbols that don't exist in MUSL
# Use conditional compilation flags based on DEBUG_BUILD argument
RUN if [ "$DEBUG_BUILD" = "true" ]; then \
RUN NOSTR_LIB=$(ls /build/nostr_core_lib/libnostr_core_*.a 2>/dev/null | head -1) && \
if [ -z "$NOSTR_LIB" ]; then echo "ERROR: nostr_core_lib .a not found"; exit 1; fi && \
echo "Using nostr library: $NOSTR_LIB" && \
if [ "$DEBUG_BUILD" = "true" ]; then \
CFLAGS="-g -O2 -DDEBUG"; \
STRIP_CMD="echo 'Keeping debug symbols'"; \
echo "Building with DEBUG symbols enabled (optimized with -O2)"; \
@@ -92,13 +113,18 @@ RUN if [ "$DEBUG_BUILD" = "true" ]; then \
gcc -static $CFLAGS -Wall -Wextra -std=c99 \
-D_GNU_SOURCE -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L -DMG_TLS=MG_TLS_BUILTIN \
-U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 \
-I. -Isrc -Inostr_core_lib -Inostr_core_lib/nostr_core \
-I. -Isrc -Isrc/tools -Inostr_core_lib -Inostr_core_lib/nostr_core \
-Inostr_core_lib/cjson -Inostr_core_lib/nostr_websocket \
src/main.c src/config.c src/context.c src/llm.c \
src/nostr_handler.c src/agent.c src/tools.c src/trigger_manager.c \
src/prompt_template.c src/http_api.c src/mongoose.c src/debug.c \
src/nostr_handler.c src/agent.c src/tools/tools_common.c src/tools/tools_schema.c src/tools/tools_dispatch.c \
src/tools/tool_agent.c src/tools/tool_meta.c src/tools/tool_model.c \
src/tools/tool_nostr_query.c src/tools/tool_nostr_my_events.c src/tools/tool_nostr_identity.c src/tools/tool_nostr_social.c \
src/tools/tool_nostr_relay.c src/tools/tool_nostr_dm.c src/tools/tool_admin.c \
src/tools/tool_task.c src/tools/tool_nostr_list.c src/tools/tool_local.c \
src/tools/tool_skill.c src/tools/tool_nostr_post.c src/tools/tool_memory.c src/tools/tool_config.c src/tools/tool_cashu_wallet.c src/trigger_manager.c \
src/cashu_wallet.c src/prompt_template.c src/http_api.c src/setup_wizard.c src/mongoose.c src/debug.c \
-o /build/didactyl_static \
nostr_core_lib/libnostr_core_x64.a \
$NOSTR_LIB \
-lsecp256k1 \
$OPENSSL_LIBS \
$CURL_LIBS \
+30 -7
View File
@@ -11,20 +11,43 @@ SRCS = \
$(SRC_DIR)/llm.c \
$(SRC_DIR)/nostr_handler.c \
$(SRC_DIR)/agent.c \
$(SRC_DIR)/tools.c \
$(SRC_DIR)/cashu_wallet.c \
$(SRC_DIR)/tools/tools_common.c \
$(SRC_DIR)/tools/tools_schema.c \
$(SRC_DIR)/tools/tools_dispatch.c \
$(SRC_DIR)/tools/tool_agent.c \
$(SRC_DIR)/tools/tool_meta.c \
$(SRC_DIR)/tools/tool_model.c \
$(SRC_DIR)/tools/tool_nostr_query.c \
$(SRC_DIR)/tools/tool_nostr_my_events.c \
$(SRC_DIR)/tools/tool_nostr_identity.c \
$(SRC_DIR)/tools/tool_nostr_social.c \
$(SRC_DIR)/tools/tool_nostr_relay.c \
$(SRC_DIR)/tools/tool_nostr_dm.c \
$(SRC_DIR)/tools/tool_admin.c \
$(SRC_DIR)/tools/tool_task.c \
$(SRC_DIR)/tools/tool_nostr_list.c \
$(SRC_DIR)/tools/tool_local.c \
$(SRC_DIR)/tools/tool_skill.c \
$(SRC_DIR)/tools/tool_nostr_post.c \
$(SRC_DIR)/tools/tool_memory.c \
$(SRC_DIR)/tools/tool_config.c \
$(SRC_DIR)/tools/tool_cashu_wallet.c \
$(SRC_DIR)/trigger_manager.c \
$(SRC_DIR)/prompt_template.c \
$(SRC_DIR)/http_api.c \
$(SRC_DIR)/setup_wizard.c \
$(SRC_DIR)/mongoose.c \
$(SRC_DIR)/debug.c
INCLUDES = \
-I$(SRC_DIR) \
-I../nostr_core_lib \
-I../nostr_core_lib/cjson \
-I../nostr_core_lib/nostr_core
-I$(SRC_DIR)/tools \
-I./nostr_core_lib \
-I./nostr_core_lib/cjson \
-I./nostr_core_lib/nostr_core
NOSTR_LIB = $(firstword $(wildcard ../nostr_core_lib/libnostr_core_*.a))
NOSTR_LIB = $(firstword $(wildcard ./nostr_core_lib/libnostr_core_*.a))
LDFLAGS = -lcurl -lssl -lcrypto -lm -lpthread -ldl -lz -L/usr/local/lib -lsecp256k1
@@ -39,7 +62,7 @@ $(BUILD_DIR):
# Build nostr_core_lib
$(NOSTR_LIB):
@echo "Building nostr_core_lib with all NIPs..."
cd ../nostr_core_lib && ./build.sh --nips=all
cd ./nostr_core_lib && ./build.sh --nips=001,004,005,006,011,013,017,019,021,042,044,046,059,060,061
# Update main.h version information (requires main.h to exist)
src/main.h:
@@ -81,7 +104,7 @@ $(TARGET): src/main.h $(SRCS) $(NOSTR_LIB)
$(CC) $(CFLAGS) $(INCLUDES) -o $@ $(SRCS) $(NOSTR_LIB) $(LDFLAGS)
deps:
cd ../nostr_core_lib && ./build.sh --nips=all
cd ./nostr_core_lib && ./build.sh --nips=001,004,005,006,011,013,017,019,021,042,044,046,059,060,061
clean:
rm -f $(TARGET)
+107 -88
View File
@@ -47,25 +47,27 @@ Because all identity, communication, and memory live on Nostr, the agent is **po
Agents learn capabilities through skills — Nostr events that any agent can discover, adopt, and share. There is no app store, no gatekeeper, no approval process. An agent can use public or private skills.
Skills support context modes (`inject`, `full`, `override`) and per-skill LLM fallback chains (for example: `anthropic/claude-sonnet-4-20250514, openai/gpt-4o-mini, cheap`) so each skill can tune behavior and cost. See [`docs/SKILLS.md`](docs/SKILLS.md).
Think of it like a woodshop: a **skill** is knowing how to carve — the technique, the judgment, the decision-making. A **tool** is the chisel. The skill never directly uses the chisel without the craftsperson (the LLM) in the loop. Every skill execution involves the LLM reasoning about what to do and which tools to use.
Skills compose by adoption-list order (`10123`) and trigger tags carry runtime execution controls (`llm`, `max_tokens`, `temperature`, `seed`, `tools`) so behavior and runtime policy remain explicit and portable. See [`docs/SKILLS.md`](docs/SKILLS.md).
### Private inference.
Didactyl will support local inference, which is very privacy preserving. Remote inference does however have it's advantages, and in those cases Didactyl supports using Bitcoin Lightning and eCash inference providers.
## Current Status — v0.0.62
## Current Status — v0.1.3
**Active build — this project is barely working. Experiment at your own risk.**
> Last release update: v0.0.62 — fix: webhook trigger lookup uses trigger manager and add startup PoC triggers/tests
> Last release update: v0.1.3 — Make cashu wallet initialization unconditional and add lazy wallet readiness for first-run DM tool usage
- Connects to configured relays with auto-reconnect and relay state transition logging
- Publishes configured startup events per relay as each relay becomes connected
- Uses kind `31120` startup content as live Soul at boot
- Loads base system context from default skill content (first-run from `genesis.jsonc`, subsequent runs from adopted skills on Nostr)
- Verifies Nostr event signatures before processing inbound messages
- Applies privilege tiers: ADMIN (tools), WoT (chat-only), STRANGER (configurable canned reply or ignore)
- Subscribes to admin context kinds (`0`,`3`,`10002`,`1`) for WoT + contextual awareness
- Builds LLM context from soul template (`---template---` section in kind `31120`) with named sections, variable resolution, and per-provider content overrides; falls back to hardcoded assembly if no template present
- Builds LLM context from default/adopted skill templates (`---template---`) with named sections, variable resolution, and per-provider content overrides; falls back to hardcoded assembly if no template present
- Adopted skills injected into context automatically from the agent's `10123` adoption list
- Supports tool-calling loop with configurable max turns and local safety limits
- Triggered skills — Nostr event filters that fire skill execution automatically with `template` (deterministic) or `llm` (context-aware) actions; see [`docs/SKILLS.md`](docs/SKILLS.md)
@@ -82,7 +84,7 @@ Didactyl will support local inference, which is very privacy preserving. Remote
```bash
chmod +x ./didactyl_static_x86_64
./didactyl_static_x86_64 --config ./config.jsonc
./didactyl_static_x86_64 --config ./genesis.jsonc
```
### Build from source (optional)
@@ -101,7 +103,7 @@ chmod +x ./didactyl_static_x86_64
### Configure
Edit [`config.jsonc`](config.jsonc):
Edit [`genesis.jsonc`](genesis.jsonc):
```json
{
@@ -122,6 +124,13 @@ Edit [`config.jsonc`](config.jsonc):
"max_tokens": 512,
"temperature": 0.7
},
"cashu_wallet": {
"enabled": true,
"mint_urls": ["https://mint.minibits.cash/Bitcoin"],
"unit": "sat",
"auto_load": true,
"mint_timeout_seconds": 30
},
"tools": {
"enabled": true,
"max_turns": 8,
@@ -153,9 +162,9 @@ Edit [`config.jsonc`](config.jsonc):
"tags": [["r", "wss://relay.damus.io"], ["r", "wss://nos.lol"]]
},
{
"kind": 31120,
"kind": 31124,
"content": "You are Didactyl...",
"tags": [["d", "soul"], ["app", "didactyl"], ["scope", "private"]]
"tags": [["d", "didactyl-default"], ["app", "didactyl"], ["scope", "private"]]
},
{
"kind": 31123,
@@ -178,18 +187,32 @@ Relays are sourced exclusively from startup kind `10002` `r` tags.
### Run
```bash
./didactyl_static_x86_64 --config ./config.jsonc
# interactive setup wizard (new / existing / load-genesis)
./didactyl_static_x86_64
# direct startup from config
./didactyl_static_x86_64 --config ./genesis.jsonc
```
Options:
```
./didactyl_static_x86_64 --config <path> # custom config file (default: ./config.jsonc)
./didactyl_static_x86_64 --debug <0-5> # log verbosity (0 none, 3 info, 5 trace)
./didactyl_static_x86_64 --dump-schemas # print tool JSON schemas and exit
./didactyl_static_x86_64 --test-tool <name> <args_json> # run one tool directly and print JSON result
./didactyl_static_x86_64 # interactive setup mode (when run with no arguments)
./didactyl_static_x86_64 --config <path> # custom config file (default: ./genesis.jsonc)
./didactyl_static_x86_64 --nsec <nsec_or_hex> # runtime identity seed override (or use DIDACTYL_NSEC)
./didactyl_static_x86_64 --api-port <port> # runtime local API port override
./didactyl_static_x86_64 --api-bind <address> # runtime local API bind override
./didactyl_static_x86_64 --debug <0-5> # log verbosity (0 none, 3 info, 5 trace)
./didactyl_static_x86_64 --dump-schemas # print tool JSON schemas and exit
./didactyl_static_x86_64 --test-tool <name> <args_json> # run one tool directly and print JSON result
```
Interactive setup notes:
- First menu asks whether you are starting a **new agent** or an **existing agent**.
- Menus use first-letter hotkeys (case-insensitive), with `q`/`x` as quit/back shortcuts.
- Existing-agent mode attempts to recover relay/admin/LLM config from Nostr before asking for missing fields.
CLI debugger notes:
- `--test-tool` initializes Nostr, waits for at least one relay connection (up to 15s), then executes the selected tool.
@@ -197,7 +220,15 @@ CLI debugger notes:
- Example:
```bash
./didactyl_static_x86_64 --config ./config.jsonc --test-tool nostr_file_md_to_longform_post '{"file":"docs/SKILLS.md","title":"SKILLS"}'
./didactyl_static_x86_64 --config ./genesis.jsonc --test-tool nostr_file_md_to_longform_post '{"file":"docs/SKILLS.md","title":"SKILLS"}'
```
Cashu wallet tool examples:
```bash
./didactyl_static_x86_64 --config ./genesis.jsonc --test-tool cashu_wallet_balance '{}'
./didactyl_static_x86_64 --config ./genesis.jsonc --test-tool cashu_wallet_info '{"mint_url":"https://mint.minibits.cash/Bitcoin"}'
./didactyl_static_x86_64 --config ./genesis.jsonc --test-tool cashu_wallet_mint_quote '{"mint_url":"https://mint.minibits.cash/Bitcoin","amount":1000,"unit":"sat"}'
```
### Talk to it
@@ -260,20 +291,15 @@ The CLI prints each message block with a speaker label (`You` / `Didactyl`) and
Didactyl uses a two-layer skill model: authors publish skill definitions, and adopters publish which skills they use.
- `31120`**Soul** (private instruction baseline)
- `d=soul`
- `31123`**Public Skill Definition** (replaceable by `d` tag)
- `content` is JSON with fields like `description`, `context_mode`, `llm`, `tools`, `template`, optional `max_tokens` / `temperature`
- `content` is JSON with instruction fields like `description` and `template`
- `d=<skill_slug>` (example: `d=long_form_note`)
- `31124`**Private Skill Definition** (same schema as `31123`, private scope)
- `d=<skill_slug>` (example: `d=admin_ops`)
- `10123`**Skill Adoption List**
- tags contain one or more `a` references to selected skills
Context modes:
- `inject` — skill instructions are layered into soul context
- `full` — skill provides full prompt template (soul optional via `{{soul}}`)
- `override` — skill replaces soul prompt, standard context structure remains
Skills are composed by adoption list order and per-skill template resolution (no context modes).
Full skill schema, trigger tags, template variables, fallback resolution, and limits are documented in [`docs/SKILLS.md`](docs/SKILLS.md).
@@ -297,77 +323,38 @@ Skills are shared across Nostr without any centralized registry or approval proc
## Startup
Didactyl startup behavior is configured in [`config.jsonc`](config.jsonc) under `startup_events`.
Didactyl startup behavior is configured in [`genesis.jsonc`](genesis.jsonc) under `startup_events`.
Also used at startup:
Startup model:
- `0` — profile metadata
- `10002` relay list
- `1` — optional startup note/status
- `3` — contacts/follows (optional placeholder)
- First run is detected by checking for an existing kind `10002` relay-list event from the agent pubkey.
- On first run, events in `startup_events` are published to connected relays.
- On subsequent runs, startup publish is skipped and relay/config state is loaded from Nostr.
- Identity can be supplied at runtime via `--nsec` or `DIDACTYL_NSEC`.
On boot, Didactyl attempts startup publishes to each relay as that relay transitions to connected state.
See [`docs/GENESIS.md`](docs/GENESIS.md) for full boot semantics.
## Runtime Context Model
Didactyl builds tier-aware context:
Didactyl builds tier-aware, template-driven context:
- **ADMIN** request context assembled from the soul's `---template---` section (if present), otherwise hardcoded order:
1. Soul personality (everything above `---template---` in kind `31120`)
2. Named template sections in order using `tool:` directives (for example `nostr_admin_profile`, `nostr_admin_notes`, `task_list`, `message_current`, `dm_history`)
3. Each section executes its configured context tool, optionally extracting `result_field` (default: `content`)
4. Provider-specific content overrides per section remain supported for literal `content:` sections
5. Section names are used in `context.log` headers and `/api/context/parts` response
- **WoT** request context: Soul + WoT chat-only instruction + current user message (no tools)
- **STRANGER**: no LLM call when configured to reply statically
- **ADMIN** request context is assembled from adopted skill templates.
- Template variables like `{{nostr_admin_profile}}` are resolved by executing tools at render time.
- Triggered skill invocations can override runtime execution parameters via trigger tags (`llm`, `max_tokens`, `temperature`, `seed`, `tools`).
- **WoT** request context remains chat-only.
- **STRANGER** behavior follows configured security policy.
Every serialized LLM context payload is appended to [`context.log`](context.log).
Triggered skills and tool loops are bounded by runtime safeguards (for example, trigger cooldowns and action rate limits); see [`docs/SKILLS.md`](docs/SKILLS.md) for the current defaults.
See [`docs/CONTEXT.md`](docs/CONTEXT.md) and [`docs/SKILLS.md`](docs/SKILLS.md) for the normative assembly and trigger rules.
## Tooling Interface
Current tool schema exposed to the LLM in [`tools_build_openai_schema_json()`](src/tools.c:881):
The OpenAI-compatible tool schema is generated in [`src/tools/tools_schema.c`](src/tools/tools_schema.c), and runtime dispatch is handled in [`src/tools/tools_dispatch.c`](src/tools/tools_dispatch.c).
- Nostr publish/query:
- `nostr_post`
- `nostr_post_readme`
- `nostr_query`
- Nostr interaction and moderation:
- `nostr_delete`
- `nostr_react`
- `nostr_profile_get`
- `nostr_relay_status`
- `nostr_relay_info`
- `nostr_nip05_lookup`
- Nostr encode/decode + encryption/DM:
- `nostr_encode`
- `nostr_decode`
- `nostr_encrypt`
- `nostr_decrypt`
- `nostr_dm_send`
- `nostr_dm_send_nip17`
- Nostr list management:
- `nostr_list_manage`
- Skill management:
- `skill_create`
- `skill_list`
- `skill_adopt`
- `skill_remove`
- `skill_search`
- Local/host tools:
- `local_shell_exec`
- `local_file_read`
- `local_file_write`
- `local_http_fetch`
- Agent metadata:
- `agent_version`
- Model management:
- `model_get`
- `model_set`
- `model_list`
Core categories include Nostr publish/query, identity/profile operations, DM and list management, skill operations, local host tools, model/runtime controls, and encrypted config tools (`config_store`, `config_recall`).
Execution entrypoint: [`tools_execute()`](src/tools.c:3765).
See [`docs/TOOLS.md`](docs/TOOLS.md) for the canonical tool catalog and interface details.
## HTTP Admin API
@@ -382,7 +369,7 @@ A localhost-only HTTP API on port `8484` (configurable) for agent inspection and
| `POST /api/prompt/run` | Run a full messages array with tools enabled |
| `POST /api/prompt/compare` | A/B compare two prompt variants |
| `GET /api/model` | Current LLM model config |
| `PUT /api/model` | Change model at runtime (persists to config.jsonc) |
| `PUT /api/model` | Change model at runtime (persisted in encrypted config events) |
| `GET /api/models` | List available models from provider |
Full reference: [`docs/API.md`](docs/API.md). Frontend brief: [`plans/admin_web_frontend.md`](plans/admin_web_frontend.md).
@@ -391,7 +378,7 @@ Full reference: [`docs/API.md`](docs/API.md). Frontend brief: [`plans/admin_web_
```
.
├── config.jsonc # Agent/runtime config (JSONC with comments) including startup_events + tools
├── genesis.jsonc # First-run genesis config (startup events + baseline runtime settings)
├── context.log # Appended outbound LLM context payloads
├── Makefile # Build system
├── build_static.sh # Preferred final build validation
@@ -400,8 +387,8 @@ Full reference: [`docs/API.md`](docs/API.md). Frontend brief: [`plans/admin_web_
│ ├── config.c / .h # JSON config parsing, key decode, startup events
│ ├── context.c / .h # File loader utility (reads file into malloc'd string)
│ ├── agent.c / .h # Context assembly, tool loop, DM response flow
│ ├── prompt_template.c / .h # Soul template parser, variable resolver, context builder
│ ├── tools.c / .h # LLM tool schema and tool execution
│ ├── prompt_template.c / .h # Skill template parser, variable resolver, context builder
│ ├── tools/ # LLM tool schema and tool execution modules
│ ├── llm.c / .h # LLM HTTP API client (OpenAI-compatible)
│ ├── nostr_handler.c / .h # Relay pool, subscriptions, publish, startup reconcile
│ ├── trigger_manager.c / .h # Nostr event trigger subscriptions and skill execution
@@ -411,7 +398,7 @@ Full reference: [`docs/API.md`](docs/API.md). Frontend brief: [`plans/admin_web_
├── docs/
│ ├── API.md # HTTP admin API endpoint reference
│ ├── TOOLS.md # Tool architecture and catalog
│ ├── SKILLS.md # Skill schema, context modes, triggers, and limits
│ ├── SKILLS.md # Skill schema, composition model, triggers, and limits
│ └── CRASH_FIXES.md # Crash analysis and fixes log
├── plans/ # Architecture and planning documents
└── README.md
@@ -429,6 +416,38 @@ All dependencies are statically linked into the binary at build time. No system
| libssl / libcrypto | TLS for WebSocket relay connections | Statically linked (Alpine/MUSL) |
| libsecp256k1 | Schnorr signatures, ECDH | Statically linked (Alpine/MUSL) |
## Roadmap: Nostr-Native Portability
Didactyl's long-term architecture goal is **zero filesystem dependency after first boot**. The config file is the only tie to the local filesystem. The plan:
1. **First boot** — Read `genesis.jsonc`, publish startup identity/skill/adoption events to relays.
2. **Subsequent boots** — Start with only `nsec` (CLI/env), detect initialized state from kind `10002`, and load durable state from Nostr.
3. **True portability** — Start your agent from any computer; keys are sufficient and state lives on Nostr.
This makes Didactyl fundamentally different from filesystem-bound agents. Destroying the host computer does not kill the agent — its identity, memory, and capabilities persist on the relay network.
### What already lives on Nostr
| Data | Event Kind | Status |
|---|---|---|
| Agent profile | Kind 0 | Implemented |
| Relay list | Kind 10002 | Implemented |
| DM relay list | Kind 10050 | Implemented |
| Public skills | Kind 31123 | Implemented |
| Private skills | Kind 31124 | Implemented |
| Skill adoption list | Kind 10123 | Implemented |
| Base/default behavior skill | Kind 31124 | Implemented |
| Trigger definitions | Tags on skill events | Implemented |
### What still needs migration
| Data | Current Location | Target |
|---|---|---|
| Admin pubkey | `genesis.jsonc` fallback | Dedicated agent config event / contact-graph derivation |
| LLM provider/key | `genesis.jsonc` fallback | Encrypted kind 30078 app-specific event |
| Security tiers | `genesis.jsonc` fallback | Agent config event on Nostr |
| API settings | local runtime flags | Local-only (not published) |
## Roadmap
- [x] MVP chat agent — DM in, LLM response out
@@ -438,7 +457,7 @@ All dependencies are statically linked into the binary at build time. No system
- [x] Tool-calling loop (nostr_post, nostr_query, local_shell_exec, local_file_read, local_file_write)
- [x] Context assembly with startup events + recent DM history
- [x] Context payload logging to [`context.log`](context.log)
- [x] Skill kind definitions (`31120` Soul, `31123` Public Skill, `31124` Private Skill)
- [x] Skill kind definitions (`31123` Public Skill, `31124` Private Skill)
- [x] Skill adoption list (`10123`) for WoT-driven discovery
- [x] Signature verification on all inbound events
- [x] Privilege tiers — ADMIN (tools), WoT (chat-only), STRANGER (canned reply/ignore)
@@ -447,13 +466,13 @@ All dependencies are statically linked into the binary at build time. No system
- [x] Adopted skills injected into LLM context automatically
- [x] Triggered skills — Nostr event filters that fire skill execution automatically
- [x] Localhost HTTP admin API — context inspection, prompt crafting, A/B comparison
- [x] Runtime model switching via `model_set` tool (persists to config.jsonc)
- [x] Soul-embedded prompt templates (`---template---`) — configurable context order, variable resolution, provider overrides
- [x] Runtime model switching via `model_set` tool (persisted in encrypted config events)
- [x] Skill-embedded prompt templates (`---template---`) — configurable context order, variable resolution, provider overrides
- [ ] Runtime skill loading from adopted `31123` events on relays
- [ ] Skill discovery CLI/tool (query WoT adoption lists)
- [ ] Upgrade to NIP-17 gift-wrapped DMs
- [ ] NIP-44 encrypted private skills (`31124`)
- [ ] Nostr-native data storage (kind 30078 app-specific events)
- [x] NIP-44 encrypted private skills (`31124`)
- [x] Nostr-native data storage (kind 30078 app-specific events)
- [ ] Blossom blob storage integration
- [ ] Agent-to-agent communication
+106 -20
View File
@@ -11,8 +11,44 @@ DOCKERFILE="$SCRIPT_DIR/Dockerfile.alpine-musl"
# Parse command line arguments
DEBUG_BUILD=false
if [[ "$1" == "--debug" ]]; then
DEBUG_BUILD=true
TARGET_PLATFORM=""
ALL_PLATFORMS=false
for arg in "$@"; do
case "$arg" in
--debug)
DEBUG_BUILD=true
;;
--platform=*)
TARGET_PLATFORM="${arg#*=}"
;;
--all-platforms|--all_platforms|-a)
ALL_PLATFORMS=true
;;
esac
done
if [ "$ALL_PLATFORMS" = true ] && [ -n "$TARGET_PLATFORM" ]; then
echo "ERROR: --all-platforms cannot be used together with --platform"
exit 1
fi
if [ "$ALL_PLATFORMS" = true ]; then
echo "Building all supported platforms (linux/amd64 + linux/arm64)..."
echo ""
DEBUG_FLAG=""
if [ "$DEBUG_BUILD" = true ]; then
DEBUG_FLAG="--debug"
fi
"$SCRIPT_DIR/build_static.sh" $DEBUG_FLAG --platform=linux/amd64
"$SCRIPT_DIR/build_static.sh" $DEBUG_FLAG --platform=linux/arm64
echo ""
echo "✓ Multi-platform build complete"
exit 0
fi
if [ "$DEBUG_BUILD" = true ]; then
echo "=========================================="
echo "Didactyl MUSL Static Binary Builder (DEBUG MODE)"
echo "=========================================="
@@ -61,24 +97,45 @@ DOCKER_CMD="docker"
echo "✓ Docker is available and running"
echo ""
# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
x86_64)
PLATFORM="linux/amd64"
OUTPUT_NAME="didactyl_static_x86_64"
;;
aarch64|arm64)
PLATFORM="linux/arm64"
OUTPUT_NAME="didactyl_static_arm64"
;;
*)
echo "WARNING: Unknown architecture: $ARCH"
echo "Defaulting to linux/amd64"
PLATFORM="linux/amd64"
OUTPUT_NAME="didactyl_static_${ARCH}"
;;
esac
# Detect architecture (or use explicit target platform override)
if [ -n "$TARGET_PLATFORM" ]; then
PLATFORM="$TARGET_PLATFORM"
case "$PLATFORM" in
linux/amd64)
OUTPUT_NAME="didactyl_static_x86_64"
;;
linux/arm64)
OUTPUT_NAME="didactyl_static_arm64"
;;
linux/arm/v7)
OUTPUT_NAME="didactyl_static_armv7"
;;
linux/arm/v6)
OUTPUT_NAME="didactyl_static_armv6"
;;
*)
OUTPUT_NAME="didactyl_static_custom"
;;
esac
else
ARCH=$(uname -m)
case "$ARCH" in
x86_64)
PLATFORM="linux/amd64"
OUTPUT_NAME="didactyl_static_x86_64"
;;
aarch64|arm64)
PLATFORM="linux/arm64"
OUTPUT_NAME="didactyl_static_arm64"
;;
*)
echo "WARNING: Unknown architecture: $ARCH"
echo "Defaulting to linux/amd64"
PLATFORM="linux/amd64"
OUTPUT_NAME="didactyl_static_${ARCH}"
;;
esac
fi
# Append _debug suffix to output name for debug builds
if [ "$DEBUG_BUILD" = true ]; then
@@ -89,6 +146,34 @@ echo "Building for platform: $PLATFORM"
echo "Output binary: $OUTPUT_NAME"
echo ""
# Verify Docker can execute the requested target platform (QEMU/binfmt for cross-arch)
HOST_ARCH=$(uname -m)
case "$HOST_ARCH" in
x86_64) HOST_PLATFORM="linux/amd64" ;;
aarch64|arm64) HOST_PLATFORM="linux/arm64" ;;
armv7l) HOST_PLATFORM="linux/arm/v7" ;;
armv6l) HOST_PLATFORM="linux/arm/v6" ;;
*) HOST_PLATFORM="unknown" ;;
esac
if [ "$HOST_PLATFORM" != "$PLATFORM" ]; then
echo "Cross-architecture build detected: host=$HOST_PLATFORM target=$PLATFORM"
echo "Checking Docker emulation support for $PLATFORM..."
if ! $DOCKER_CMD run --rm --platform "$PLATFORM" alpine:3.19 uname -m > /dev/null 2>&1; then
echo ""
echo "ERROR: Docker cannot execute $PLATFORM containers on this host"
echo "This usually means QEMU/binfmt is not configured."
echo "Run this once, then retry:"
echo " docker run --rm --privileged multiarch/qemu-user-static --reset -p yes"
echo "Optional verify command:"
echo " docker run --rm --platform $PLATFORM alpine:3.19 uname -m"
echo ""
exit 1
fi
echo "✓ Docker emulation for $PLATFORM is available"
echo ""
fi
# Check if Alpine base image is cached
echo "Checking for cached Alpine Docker image..."
if ! docker images alpine:3.19 --format "{{.Repository}}:{{.Tag}}" | grep -q "alpine:3.19"; then
@@ -118,6 +203,7 @@ echo " - Compile didactyl with full static linking"
echo ""
$DOCKER_CMD build \
--network host \
--platform "$PLATFORM" \
--build-arg DEBUG_BUILD=$DEBUG_BUILD \
-f "$DOCKERFILE" \
+91 -1
View File
@@ -1,4 +1,8 @@
{
// LEGACY CONFIG EXAMPLE
// This file is deprecated in favor of genesis.jsonc + nsec-only startup.
// Kept as reference for older deployments and migration support.
// ─── Agent Identity Keys ───────────────────────────────────────────
// Your agent's Nostr keypair. Provide nsec (bech32) or hex format.
// The public key fields are optional — they are derived automatically.
@@ -31,6 +35,41 @@
"temperature": 0.7 // sampling temperature (0.0 2.0)
},
// ─── Cashu Wallet (NIP-60) ────────────────────────────────────────
// Optional wallet runtime used by cashu_wallet_* tools.
// If enabled=true and auto_load=true, Didactyl will attempt to load
// wallet/token events from relays at startup and create a new wallet
// from mint_urls if none is found.
"cashu_wallet": {
"enabled": false,
"mint_urls": [
"https://mint.minibits.cash/Bitcoin"
],
"unit": "sat",
"auto_load": true,
"mint_timeout_seconds": 30
},
// ─── Tools & Runtime Limits ───────────────────────────────────────
// Centralized turn and timeout limits used by DM agent loops,
// triggered skills, HTTP API prompt runs, and local HTTP fetch tool.
"tools": {
"enabled": true,
"max_turns": 20, // default max turns for normal agent tool loops
"trigger_max_turns": 12, // max turns for triggered-skill executions
"api_default_max_turns": 8, // default when HTTP body omits max_turns
"api_max_turns_ceiling": 32, // hard cap applied to API-provided max_turns
"stall_repeat_threshold": 3, // stop early when identical tool-call turns repeat this many times
"local_http_fetch_default_timeout_seconds": 20,
"local_http_fetch_max_timeout_seconds": 120,
"shell": {
"enabled": true,
"timeout_seconds": 30,
"max_output_bytes": 65536,
"working_directory": "."
}
},
// ─── Security Tiers ───────────────────────────────────────────────
// Controls who can interact with the agent and what they can do.
"security": {
@@ -136,7 +175,7 @@
// structured context sections that are injected at runtime.
{
"kind": 31120,
"content": "# Didactyl Agent\n\nYou are Didactyl, a sovereign AI agent living on Nostr.\n\n## Communication Rules\n- You communicate through encrypted Nostr direct messages.\n- Keep responses concise and clear.\n\n## Behavior\n- Be helpful and technically accurate.\n- If unsure, state uncertainty directly.\n- Prefer actionable, practical advice.\n- Use the person's name when messaging them if you know it.\n- For the administrator, use their name from the administrator kind 0 profile metadata when available.\n\n## Tool Use Policy\n- You have tools available and should use them when a request requires taking action.\n- For requests involving local inspection or command execution, call `local_shell_exec` instead of refusing.\n- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.\n- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.\n- After a tool call, base your answer on the actual tool result.\n- Never claim a tool was run if no tool was executed.\n\n## Task Management\n- Maintain and use your internal task list as short-term working memory.\n- Break long or complex actions into clear tasks before executing them.\n- Update task status as you complete steps so your plan stays accurate.\n\n## Safety\n- Do not claim to have executed actions you did not execute.\n- You may share your public key (npub) with anyone.\n- Never reveal your private key (nsec) under any circumstance.\n\n---template---\n\n- section: admin_identity\n role: system\n content: |\n ## Administrator Identity (source: config.admin.pubkey)\n\n This is your administrator! Admin pubkey (hex): {{admin_pubkey}}\n\n- section: admin_profile\n role: system\n content: |\n ## Administrator Kind 0 Profile (source: nostr kind 0)\n\n Administrator kind 0 profile content (JSON): {{admin_kind0_json}}\n provider:\n anthropic: |\n <admin_kind0_profile source=\"nostr_kind_0\">\n {{admin_kind0_json}}\n </admin_kind0_profile>\n\n- section: admin_contacts\n role: system\n content: |\n ## Administrator Contact List (source: nostr kind 3)\n\n Administrator kind 3 contact list pubkeys (JSON array): {{admin_kind3_json}}\n provider:\n anthropic: |\n <admin_contacts source=\"nostr_kind_3\">\n {{admin_kind3_json}}\n </admin_contacts>\n\n- section: admin_relays\n role: system\n content: |\n ## Administrator Relay List (source: nostr kind 10002)\n\n Administrator kind 10002 relay list (JSON): {{admin_kind10002_json}}\n provider:\n anthropic: |\n <admin_relays source=\"nostr_kind_10002\">\n {{admin_kind10002_json}}\n </admin_relays>\n\n- section: admin_notes\n role: system\n content: |\n ## Administrator Recent Notes (source: nostr kind 1)\n\n Administrator recent kind 1 notes (JSON array): {{admin_kind1_json}}\n provider:\n anthropic: |\n <admin_notes source=\"nostr_kind_1\">\n {{admin_kind1_json}}\n </admin_notes>\n\n- section: skills\n role: system\n content: |\n ## Adopted Skills\n\n {{skills_json}}\n\n- section: tasks\n role: system\n content: |\n ## Current Task List\n\n {{tasks_json}}\n\n- section: conversation\n role: conversation\n content: |\n {{conversation}}",
"content": "# Didactyl Agent\n\nYou are Didactyl, a sovereign AI agent living on Nostr.\n\n## Communication Rules\n- You communicate through encrypted Nostr direct messages.\n- Keep responses concise and clear.\n\n## Behavior\n- Be helpful and technically accurate.\n- If unsure, state uncertainty directly.\n- Prefer actionable, practical advice.\n- Use the person's name when messaging them if you know it.\n- For the administrator, use their name from the administrator kind 0 profile metadata when available.\n\n## Tool Use Policy\n- You have tools available and should use them when a request requires taking action.\n- For requests involving local inspection or command execution, call `local_shell_exec` instead of refusing.\n- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.\n- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.\n- For memory persistence, use `memory_save` to prepend new memory entries and `memory_recall` to recall stored memory.\n- Memory is not injected by default; call `memory_recall` when needed.\n- Keep memory content in markdown and concise enough for context efficiency.\n- After a tool call, base your answer on the actual tool result.\n- Never claim a tool was run if no tool was executed.\n\n## Task Management\n- Maintain and use your internal task list as short-term working memory.\n- Break long or complex actions into clear tasks before executing them.\n- Update task status as you complete steps so your plan stays accurate.\n\n## Safety\n- Do not claim to have executed actions you did not execute.\n- You may share your public key (npub) with anyone.\n- Never reveal your private key (nsec) under any circumstance.\n\n---template---\n\n- section: admin_identity\n role: system\n content: |\n ## Administrator Identity (source: config.admin.pubkey)\n\n This is your administrator! Admin pubkey (hex): {{admin_pubkey}}\n\n- section: admin_profile\n role: system\n content: |\n ## Administrator Kind 0 Profile (source: nostr kind 0)\n\n Administrator kind 0 profile content (JSON): {{admin_kind0_json}}\n provider:\n anthropic: |\n <admin_kind0_profile source=\"nostr_kind_0\">\n {{admin_kind0_json}}\n </admin_kind0_profile>\n\n- section: admin_contacts\n role: system\n content: |\n ## Administrator Contact List (source: nostr kind 3)\n\n Administrator kind 3 contact list pubkeys (JSON array): {{admin_kind3_json}}\n provider:\n anthropic: |\n <admin_contacts source=\"nostr_kind_3\">\n {{admin_kind3_json}}\n </admin_contacts>\n\n- section: admin_relays\n role: system\n content: |\n ## Administrator Relay List (source: nostr kind 10002)\n\n Administrator kind 10002 relay list (JSON): {{admin_kind10002_json}}\n provider:\n anthropic: |\n <admin_relays source=\"nostr_kind_10002\">\n {{admin_kind10002_json}}\n </admin_relays>\n\n- section: admin_notes\n role: system\n content: |\n ## Administrator Recent Notes (source: nostr kind 1)\n\n Administrator recent kind 1 notes (JSON array): {{admin_kind1_json}}\n provider:\n anthropic: |\n <admin_notes source=\"nostr_kind_1\">\n {{admin_kind1_json}}\n </admin_notes>\n\n- section: skills\n role: system\n content: |\n ## Adopted Skills\n\n {{skills_json}}\n\n- section: tasks\n role: system\n content: |\n ## Current Task List\n\n {{tasks_json}}\n\n- section: conversation\n role: conversation\n content: |\n {{conversation}}",
"tags": [
["d", "soul"],
["app", "didactyl"],
@@ -246,6 +285,57 @@
]
},
// Kind 31124: Private triggered skill — webhook-echo
// Example webhook trigger that emits a fixed DM response.
{
"kind": 31124,
"content": "When this webhook trigger fires, DM the admin with exactly: WEBHOOK_SOURCE_POC_OK",
"tags": [
["d", "webhook-echo"],
["app", "didactyl"],
["scope", "private"],
["description", "PoC webhook trigger skill"],
["trigger", "webhook"],
["filter", "{}"],
["action", "llm"],
["enabled", "true"]
]
},
// Kind 31124: Private triggered skill — cron_poc
// Example cron trigger that runs every minute.
{
"kind": 31124,
"content": "DM the administrator with the current time, and tell him that your cron skill triggered.",
"tags": [
["d", "cron_poc"],
["app", "didactyl"],
["scope", "private"],
["description", "PoC cron trigger skill"],
["trigger", "cron"],
["filter", "*/1 * * * *"],
["action", "template"],
["enabled", "true"]
]
},
// Kind 31124: Private triggered skill — chain_from_webhook_poc
// Example chain trigger that runs after webhook-echo completes.
{
"kind": 31124,
"content": "LOG: chain_from_webhook_poc fired",
"tags": [
["d", "chain_from_webhook_poc"],
["app", "didactyl"],
["scope", "private"],
["description", "PoC chain trigger skill"],
["trigger", "chain"],
["filter", "webhook-echo"],
["action", "template"],
["enabled", "true"]
]
},
// Kind 10123: Skill adoption list
// References which public skills this agent has adopted.
{
+518 -7792
View File
File diff suppressed because it is too large Load Diff
+7 -39
View File
@@ -1,42 +1,10 @@
# Context Template
# Context Template (Legacy)
```yaml
- section: admin_identity
role: system
tool: admin_identity
skip_if_empty: true
This file is deprecated and retained for backward compatibility only.
- section: admin_profile
role: system
tool: nostr_admin_profile
skip_if_empty: true
The default context behavior is now defined by adopted skills (kind `10123`) and the `didactyl_default` skill template published from `genesis.jsonc`.
- section: admin_contacts
role: system
tool: nostr_admin_contacts
skip_if_empty: true
- section: admin_relays
role: system
tool: nostr_admin_relays
skip_if_empty: true
- section: admin_notes
role: system
tool: nostr_admin_notes
skip_if_empty: true
- section: tasks
role: system
tool: task_list
skip_if_empty: true
- section: conversation
role: user
tool: message_current
skip_if_empty: true
- section: dm_history
role: expand
limit: 12
```
For current behavior, see:
- `docs/GENESIS.md`
- `docs/CONTEXT.md`
- `docs/SKILLS.md`
+56
View File
@@ -0,0 +1,56 @@
# Context Template
```yaml
- section: admin_identity
role: system
content: |
## Administrator Identity (source: config.admin.pubkey)
This is your administrator! Admin pubkey (hex): {{admin_pubkey}}
- section: admin_profile
role: system
content: |
## Administrator Kind 0 Profile (source: nostr kind 0)
Administrator kind 0 profile content (JSON): {{admin_kind0_json}}
provider:
anthropic: |
<admin_kind0_profile source="nostr_kind_0">
{{admin_kind0_json}}
</admin_kind0_profile>
- section: admin_relay_list
role: system
content: |
## Administrator Relay List (source: nostr kind 10002)
Administrator kind 10002 relay-list content (JSON): {{admin_kind10002_json}}
- section: startup_events
role: system
content: |
## Startup Events Memory (source: config.startup_events)
Startup events memory (kinds/content/tags): {{startup_events_json}}
- section: adopted_skills
role: system
content: |
{{adopted_skills_content}}
- section: agent_tasks
role: system
content: |
{{tasks_content}}
- section: dm_history
role: expand
limit: 12
- section: admin_notes
role: system
content: |
## Administrator Recent Notes (source: nostr kind 1)
{{admin_notes_content}}
Executable
+51
View File
@@ -0,0 +1,51 @@
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_BINARY="$SCRIPT_DIR/didactyl_static_x86_64"
REMOTE_HOST="ubuntu@laantungir.net"
REMOTE_TARGETS=(
"/home/simon/didactyl"
"/home/didactyl/didactyl"
)
REMOTE_SERVICES=(
"simon.service"
"didactyl.service"
)
if ! command -v rsync >/dev/null 2>&1; then
echo "ERROR: rsync is not installed or not in PATH"
exit 1
fi
if ! command -v ssh >/dev/null 2>&1; then
echo "ERROR: ssh is not installed or not in PATH"
exit 1
fi
echo "Building static binary first..."
"$SCRIPT_DIR/build_static.sh"
if [ ! -f "$SOURCE_BINARY" ]; then
echo "ERROR: Build completed but source binary not found: $SOURCE_BINARY"
exit 1
fi
REMOTE_STAGE="/tmp/didactyl_static_x86_64"
echo "Uploading $SOURCE_BINARY to staging path $REMOTE_HOST:$REMOTE_STAGE"
rsync -avz --progress "$SOURCE_BINARY" "$REMOTE_HOST:$REMOTE_STAGE"
for target in "${REMOTE_TARGETS[@]}"; do
echo "Installing staged binary to $target via sudo"
ssh "$REMOTE_HOST" "sudo install -m 0755 '$REMOTE_STAGE' '$target'"
done
echo "Restarting services on $REMOTE_HOST: ${REMOTE_SERVICES[*]}"
ssh "$REMOTE_HOST" "sudo systemctl restart ${REMOTE_SERVICES[*]}"
echo "Cleaning up remote staging file $REMOTE_STAGE"
ssh "$REMOTE_HOST" "rm -f '$REMOTE_STAGE'"
echo "Deployment complete for all targets and services."
+15004
View File
File diff suppressed because one or more lines are too long
+124
View File
@@ -0,0 +1,124 @@
[2026-03-16 05:30:19] [INFO ] Didactyl v0.0.71 starting
[2026-03-16 05:30:19] [INFO ] [didactyl] initializing relay pool with 2 relays
[2026-03-16 05:30:19] [INFO ] [didactyl] added relay: wss://relay.damus.io
[2026-03-16 05:30:19] [INFO ] [didactyl] added relay: wss://relay.primal.net
[2026-03-16 05:30:19] [INFO ] [didactyl] startup checklist [01] Relay connectivity: begin
[startup 01] Relay connectivity ...
[2026-03-16 05:30:20] [WARN ] [didactyl] poll latency spike: nostr_relay_pool_poll(timeout=100) took 1190.6ms rc=0 count=1
[2026-03-16 05:30:20] [INFO ] [didactyl] relay state changed: wss://relay.damus.io disconnected -> connected
[2026-03-16 05:30:20] [INFO ] [didactyl] relay state changed: wss://relay.primal.net disconnected -> connected
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [01] Relay connectivity: ok (connected relays: 2/2)
[startup 01] Relay connectivity: OK (connected relays: 2/2)
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [02] Recover runtime config from Nostr: begin
[startup 02] Recover runtime config from Nostr ...
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [02] Recover runtime config from Nostr: ok
[startup 02] Recover runtime config from Nostr: OK
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [03] Validate LLM config: begin
[startup 03] Validate LLM config ...
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [03] Validate LLM config: ok
[startup 03] Validate LLM config: OK
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [04] Validate admin config: begin
[startup 04] Validate admin config ...
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [04] Validate admin config: ok
[startup 04] Validate admin config: OK
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [05] Initialize LLM client: begin
[startup 05] Initialize LLM client ...
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [05] Initialize LLM client: ok
[startup 05] Initialize LLM client: OK
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [06] Detect first run via kind 10002: begin
[startup 06] Detect first run via kind 10002 ...
[2026-03-16 05:30:20] [INFO ] [didactyl] startup phase: first-run detection via kind 10002 => subsequent-run
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [06] Detect first run via kind 10002: ok (subsequent-run)
[startup 06] Detect first run via kind 10002: OK (subsequent-run)
[2026-03-16 05:30:20] [INFO ] [didactyl] startup checklist [07] Reconcile/persist startup state: begin
[startup 07] Reconcile/persist startup state ...
[2026-03-16 05:30:20] [INFO ] [didactyl] startup phase: skipping genesis startup-event publish on subsequent run
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [07] Reconcile/persist startup state: ok
[startup 07] Reconcile/persist startup state: OK
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [08] Initialize agent: begin
[startup 08] Initialize agent ...
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [08] Initialize agent: ok
[startup 08] Initialize agent: OK
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [09] Initialize trigger manager: begin
[startup 09] Initialize trigger manager ...
[2026-03-16 05:30:21] [INFO ] [didactyl] trigger manager initialized (capacity=16)
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [09] Initialize trigger manager: ok
[startup 09] Initialize trigger manager: OK
[2026-03-16 05:30:21] [INFO ] [didactyl] startup phase: deferred trigger load will run after self-skill EOSE
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [10] Load startup triggers: begin
[startup 10] Load startup triggers ...
[2026-03-16 05:30:21] [INFO ] [didactyl] startup phase: startup-config trigger load begin
[2026-03-16 05:30:21] [INFO ] [didactyl] trigger manager loaded 0 trigger(s) from startup config (considered=1)
[2026-03-16 05:30:21] [INFO ] [didactyl] startup phase: startup-config trigger load end
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [10] Load startup triggers: ok
[startup 10] Load startup triggers: OK
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [11] Discover self relay list via kind 10002: begin
[startup 11] Discover self relay list via kind 10002 ...
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 query begin: timeout_ms=5000 author=52a3e82f7b374385... relay_count=2
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 query relay snapshot: {"relay_count":2,"connected_count":2,"relays":[{"url":"wss://relay.damus.io","status":"connected","events_received":3,"events_published":0,"events_published_ok":0,"events_published_failed":0,"ping_latency_current":0,"ping_latency_avg":0,"query_latency_avg":0,"publish_latency_avg":0,"connection_uptime_start":1773653419,"last_event_time":0},{"url":"wss://relay.primal.net","status":"connected","events_received":2,"events_published":0,"events_published_ok":0,"events_published_failed":0,"ping_latency_current":0,"ping_latency_avg":0,"query_latency_avg":0,"publish_latency_avg":0,"connection_uptime_start":1773653419,"last_event_time":0}]}
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 query received event_count=1
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 query extracted relays=["wss://relay.damus.io","wss://nos.lol","wss://relay.primal.net","ws://127.0.0.1:7777","wss://relay.laantungir.net","wss://sendit.nosflare.com"]
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 wait success: relay_count=6
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 relay[0]=wss://relay.damus.io
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 relay[1]=wss://nos.lol
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 relay[2]=wss://relay.primal.net
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 relay[3]=ws://127.0.0.1:7777
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 relay[4]=wss://relay.laantungir.net
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 relay[5]=wss://sendit.nosflare.com
[2026-03-16 05:30:21] [INFO ] [didactyl] kind10002 wait success relay snapshot: {"relay_count":2,"connected_count":2,"relays":[{"url":"wss://relay.damus.io","status":"connected","events_received":4,"events_published":0,"events_published_ok":0,"events_published_failed":0,"ping_latency_current":0,"ping_latency_avg":0,"query_latency_avg":0,"publish_latency_avg":0,"connection_uptime_start":1773653419,"last_event_time":0},{"url":"wss://relay.primal.net","status":"connected","events_received":2,"events_published":0,"events_published_ok":0,"events_published_failed":0,"ping_latency_current":0,"ping_latency_avg":0,"query_latency_avg":0,"publish_latency_avg":0,"connection_uptime_start":1773653419,"last_event_time":0}]}
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [11] Discover self relay list via kind 10002: ok (kind10002=6 added=4 connected=2/6)
[startup 11] Discover self relay list via kind 10002: OK (kind10002=6 added=4 connected=2/6)
[2026-03-16 05:30:21] [INFO ] [didactyl] startup checklist [12] Subscribe admin context: begin
[startup 12] Subscribe admin context ...
[2026-03-16 05:30:21] [INFO ] [didactyl] startup phase: subscribe admin context begin
[2026-03-16 05:30:26] [INFO ] [didactyl] admin context subscriptions active for admin 8ff74724ed641b3c...
[2026-03-16 05:30:26] [INFO ] [didactyl] startup phase: subscribe admin context end
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [12] Subscribe admin context: ok
[startup 12] Subscribe admin context: OK
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [13] Subscribe agent self context: begin
[startup 13] Subscribe agent self context ...
[2026-03-16 05:30:26] [INFO ] [didactyl] startup phase: subscribe agent self context begin
[2026-03-16 05:30:26] [INFO ] [didactyl] agent self-context subscriptions active for pubkey 52a3e82f7b374385...
[2026-03-16 05:30:26] [INFO ] [didactyl] startup phase: subscribe agent self context end
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [13] Subscribe agent self context: ok
[startup 13] Subscribe agent self context: OK
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [14] Subscribe self-skill cache: begin
[startup 14] Subscribe self-skill cache ...
[2026-03-16 05:30:26] [INFO ] [didactyl] startup phase: subscribe self skill cache begin
[2026-03-16 05:30:26] [INFO ] [didactyl] self/admin skill subscriptions active (self=52a3e82f7b374385..., admin=8ff74724ed641b3c...)
[2026-03-16 05:30:26] [INFO ] [didactyl] startup phase: subscribe self skill cache end
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [14] Subscribe self-skill cache: ok
[startup 14] Subscribe self-skill cache: OK
[2026-03-16 05:30:26] [INFO ] [didactyl] publish DM target relays (6):
[2026-03-16 05:30:26] [INFO ] [didactyl] -> wss://relay.damus.io
[2026-03-16 05:30:26] [INFO ] [didactyl] -> wss://relay.primal.net
[2026-03-16 05:30:26] [INFO ] [didactyl] -> wss://nos.lol
[2026-03-16 05:30:26] [INFO ] [didactyl] -> ws://127.0.0.1:7777
[2026-03-16 05:30:26] [INFO ] [didactyl] -> wss://relay.laantungir.net
[2026-03-16 05:30:26] [INFO ] [didactyl] -> wss://sendit.nosflare.com
[2026-03-16 05:30:26] [INFO ] [didactyl] kind 4 event published to wss://relay.damus.io (async)
[2026-03-16 05:30:26] [INFO ] [didactyl] kind 4 event published to wss://relay.primal.net (async)
[2026-03-16 05:30:26] [INFO ] [didactyl] kind 4 event published to wss://nos.lol (async)
[2026-03-16 05:30:26] [INFO ] [didactyl] kind 4 event published to ws://127.0.0.1:7777 (async)
[2026-03-16 05:30:26] [INFO ] [didactyl] kind 4 event published to wss://relay.laantungir.net (async)
[2026-03-16 05:30:26] [INFO ] [didactyl] kind 4 event published to wss://sendit.nosflare.com (async)
[2026-03-16 05:30:26] [INFO ] [didactyl] sent DM 54452dbf320bee66... to 8ff74724ed641b3c... via 6 connected relay(s)
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [15] Subscribe DMs: begin
[startup 15] Subscribe DMs ...
[2026-03-16 05:30:26] [INFO ] [didactyl] startup phase: subscribe DMs begin
[2026-03-16 05:30:26] [INFO ] [didactyl] DM subscription active for pubkey 52a3e82f7b374385...
[2026-03-16 05:30:26] [INFO ] [didactyl] startup phase: subscribe DMs end
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [15] Subscribe DMs: ok
[startup 15] Subscribe DMs: OK
2aa88330 3 mongoose.c:4824:mg_mgr_init MG_IO_SIZE: 16384, TLS: builtin
2aa88331 3 mongoose.c:4741:mg_listen 1 11 https://127.0.0.1:8484
[2026-03-16 05:30:26] [INFO ] [didactyl] http api listening on https://127.0.0.1:8484
[2026-03-16 05:30:26] [INFO ] [didactyl] HTTP API listening at http://127.0.0.1:8484
[2026-03-16 05:30:26] [INFO ] [didactyl] HTTP API endpoints: http://127.0.0.1:8484/api/context/current http://127.0.0.1:8484/api/context/parts
[2026-03-16 05:30:26] [INFO ] [didactyl] startup checklist [16] READY: ok (agent online; entering main poll loop)
[startup 16] READY: OK (agent online; entering main poll loop)
[2026-03-16 05:30:26] [INFO ] [didactyl] entering main poll loop
[2026-03-16 05:30:26] [INFO ] [didactyl] running with pubkey 52a3e82f7b3743852fbe804cfcbf4db3448115887895247c001f2b50e790acb8
[2026-03-16 05:30:27] [INFO ] [didactyl] live self-skill trigger ignored (not adopted) d_tag=daily-readme-publish
[2026-03-16 05:30:28] [INFO ] [didactyl] live self-skill trigger ignored (not adopted) d_tag=daily-readme-publish
[2026-03-16 05:30:28] [INFO ] [didactyl] live self-skill trigger ignored (not adopted) d_tag=daily-readme-publish
BIN
View File
Binary file not shown.
+1 -3
View File
@@ -178,7 +178,7 @@ Returns the context broken into labeled, individually-sized parts. Useful for un
| Name | Description |
|---|---|
| `system_prompt` | The agent soul / system prompt (first system message) |
| `system_prompt` | The agent base/default skill prompt (first system message) |
| `admin_identity` | Admin pubkey identification message |
| `admin_kind0` | Admin kind 0 profile metadata |
| `admin_relay_list` | Admin kind 10002 relay list |
@@ -513,8 +513,6 @@ The following endpoints are planned but not yet implemented:
| Method | Path | Description |
|---|---|---|
| GET | `/api/config` | Current runtime config with redacted secrets |
| GET | `/api/events/soul` | Fetch agent soul event |
| PUT | `/api/events/soul` | Update soul content |
| GET | `/api/events/skills` | List published skills |
| GET | `/api/events/skills/:d_tag` | Fetch skill by d_tag |
| PUT | `/api/events/skills/:d_tag` | Update skill |
+161
View File
@@ -0,0 +1,161 @@
# Didactyl — LLM Context
See also: [SKILLS.md](SKILLS.md) · [TOOLS.md](TOOLS.md)
## What Is Context?
Every time Didactyl talks to an LLM, it sends a **context** — the complete package of information the model needs to reason and respond.
Context is not just a prompt string; it is the full request payload:
1. **Messages** — system/user/assistant/tool history
2. **Tool schemas** — JSON descriptions of callable tools
3. **Model parameters** — model, temperature, max tokens, seed, etc.
---
## OpenAI-Compatible Chat Format
Didactyl uses OpenAI-compatible chat completions.
```json
{
"model": "claude-opus-4.6",
"messages": [
{"role": "system", "content": "..."},
{"role": "user", "content": "..."}
],
"tools": [
{
"type": "function",
"function": {
"name": "nostr_post",
"description": "Publish a Nostr event",
"parameters": {"type":"object"}
}
}
],
"temperature": 0.7,
"max_tokens": 512
}
```
### Message Roles
| Role | Purpose |
|------|---------|
| `system` | Instructions and injected context |
| `user` | Input message or trigger payload |
| `assistant` | Model responses / tool call envelopes |
| `tool` | Tool execution results fed back to model |
---
## Context Assembly Model
Didactyl uses **skill composition by adoption order**.
There are no context modes.
### Assembly Steps
1. Load adopted skills from kind `10123`.
2. Resolve adopted skills in list order.
3. Expand each skill template variables via tools.
4. Append resolved skill output to messages in that same order.
5. Append live input (DM text or triggering event payload).
6. Attach tool schemas.
7. Apply execution parameters from trigger tags (if invoked via trigger).
```mermaid
flowchart TD
INPUT[Input: DM or trigger event] --> ADOPT[Load adopted skills from kind 10123]
ADOPT --> ORDER[Resolve skills in listed order]
ORDER --> EXPAND[Expand template variables via tools]
EXPAND --> MESSAGES[Append resolved skill messages]
MESSAGES --> LIVE[Append live input message/event]
LIVE --> TOOLS[Attach tool schemas]
TOOLS --> PARAMS[Apply runtime params from trigger tags]
PARAMS --> LLM[Send to LLM]
```
### Why Order Matters
- Earlier adopted skills usually establish broad behavior.
- Later adopted skills can refine or narrow behavior.
- If instructions conflict, prompt-order effects apply.
---
## Context Parts
| Part | Source | Description |
|------|--------|-------------|
| Skill templates | Adopted skill events | Core instructions assembled in order |
| Resolved variables | Tool outputs | Runtime data inserted into templates |
| Conversation history | DM history/events | Recent dialogue context |
| Live input | DM or trigger event | Current request payload |
| Tool schemas | Tool registry | Capability declaration for tool calling |
| Runtime params | Trigger tags | LLM/tool limits for this execution |
---
## Template Variables Are Tool Calls
Template variables resolve through tool execution.
Example:
- `{{admin_profile}}` resolves by running `nostr_admin_profile`
- `{{admin_notes}}` resolves by running `nostr_admin_notes`
Unknown variables should resolve to empty values for portability.
---
## Trigger Runtime Parameters
Execution controls are attached to trigger tags, not skill content:
- `llm`
- `max_tokens`
- `temperature`
- `seed`
- `tools`
Resolution order for a triggered run:
1. Start with agent defaults
2. Apply trigger tag overrides
3. Execute
4. Restore defaults
---
## Triggered vs Adopted Use
- **Adopted skill (`10123`)**: contributes context/instructions
- **Triggered skill**: contributes context and may supply execution overrides via tags
This separation keeps composition simple while allowing per-trigger runtime control.
---
## Token Budget
Context cost is controlled by:
- Adoption-list ordering and skill count
- Conversation-history limits
- Skill/template truncation limits
- Per-trigger model/runtime parameter choices
Use runtime context inspection endpoints to see the exact payload before LLM calls.
---
## Related Documentation
- Skills spec: [SKILLS.md](SKILLS.md)
- Tool catalog: [TOOLS.md](TOOLS.md)
- API details: [API.md](API.md)
+136
View File
@@ -0,0 +1,136 @@
# Didactyl — Genesis Bootstrapping
See also: [CONTEXT.md](CONTEXT.md) · [SKILLS.md](SKILLS.md) · [README.md](../README.md)
## Purpose
`genesis.jsonc` is the first-run bootstrap document for a Didactyl agent.
It defines initial identity, admin policy, startup events, default skill context, and baseline runtime settings so the agent can publish itself onto Nostr.
After bootstrap, the long-term direction is **nsec-only startup** with state recovered from Nostr events.
---
## File Format
`genesis.jsonc` is JSONC (JSON + comments).
Minimum practical sections:
- `key.nsec` (or runtime `--nsec` / `DIDACTYL_NSEC`)
- `admin.pubkey`
- `llm`
- `startup_events` (must include kind `10002` relay tags)
Typical optional sections:
- `dm_protocol`
- `tools`
- `security`
- `admin_context`
- `api`
- `default_skill` (reserved for default-skill publishing workflows)
---
## First-Run Flow
On first run, the agent:
1. Loads `genesis.jsonc`.
2. Derives keys (from `key.nsec` or runtime nsec override).
3. Connects to relay set from startup kind `10002` tags.
4. Publishes/reconciles startup events.
5. Initializes runtime services (DM subscriptions, triggers, API if enabled).
First-run detection is based on querying own kind `10002` relay-list availability.
---
## Subsequent-Run Flow
On subsequent runs, the agent can start with nsec supplied via:
- CLI: `--nsec <nsec_or_hex>`
- Environment: `DIDACTYL_NSEC`
Optional runtime API overrides:
- `--api-port <port>`
- `--api-bind <address>`
Subsequent-run bootstrap-event republishing is skipped when prior kind `10002` state is found.
---
## Interactive Setup (Zero-Argument Startup)
When Didactyl is run with **no arguments**:
```bash
./didactyl
```
it enters an interactive setup wizard instead of immediately trying to load `./genesis.jsonc`.
Wizard entry choices:
- **New agent** — generate/provide identity, configure admin + LLM + relays
- **Existing agent** — provide nsec and recover relay/admin/LLM config from Nostr
- **Load genesis** — load a specified genesis file path
Menu UX conventions:
- Single-letter hotkeys (case-insensitive)
- First-letter menu mnemonics (e.g., `N` for New, `E` for Existing)
- `q` / `x` exits or backs out of menus
Security behavior:
- nsec entry is masked in terminal
- writing genesis with nsec is explicit and warned
- recommended export mode is genesis without nsec plus runtime `--nsec`/`DIDACTYL_NSEC`
---
## Encrypted Config Events
Didactyl exposes config persistence tools for encrypted self-config on Nostr:
- `config_store` — publish encrypted kind `30078` config by `d_tag`
- `config_recall` — query+decrypt kind `30078` config by `d_tag`
Recommended tags:
- `d=llm_config`
- `d=agent_config`
These are encrypted to self with NIP-44.
---
## Relay Bootstrap Strategy
`startup_events` must include kind `10002` relay tags (`["r", "wss://..."]`).
That relay list is used as the initial network attachment for querying existing state and publishing startup events.
---
## Migration Notes (Legacy -> Genesis)
Legacy deployments using `config.jsonc` can migrate by:
1. Copying equivalent sections to `genesis.jsonc`.
2. Ensuring startup kind `10002` relay tags are present.
3. Providing nsec at runtime (`--nsec` or `DIDACTYL_NSEC`) where desired.
4. Treating `context_template.md` / `config.jsonc.example` as legacy references.
---
## Security Notes
- Keep nsec secret.
- Prefer environment or secure credential injection for production nsec handling.
- Avoid publishing plaintext sensitive config; use encrypted `config_store` for long-term state.
+166 -259
View File
@@ -1,12 +1,16 @@
# Didactyl — Skills
See also: [TOOLS.md](TOOLS.md)
See also: [CONTEXT.md](CONTEXT.md) · [TOOLS.md](TOOLS.md)
## Overview
A skill is a **self-contained LLM execution unit** stored as a Nostr event. Each skill defines what the LLM sees (context template), which model runs it (LLM specification with fallbacks), what tools are available, and whether the agent's identity (soul) is included.
A skill is a **set of instructions for the LLM** stored as a Nostr event.
Skills are portable, shareable, and discoverable — they live on Nostr relays as standard events.
Skills teach the agent how to accomplish tasks — the LLM reads the instructions, reasons about them, and uses tools to take action.
Think of it like a woodshop: a **skill** is knowing how to carve — technique, judgment, decision-making. A **tool** is the chisel. The skill never directly uses the chisel without the craftsperson (the LLM) in the loop.
Skills are portable, shareable, and discoverable as Nostr events.
---
@@ -22,19 +26,14 @@ Skills are portable, shareable, and discoverable — they live on Nostr relays a
## Skill Content
The skill event's `content` field is a JSON object that defines the complete execution specification:
Skill `content` is JSON and should focus on **instructions**, not transport/runtime controls.
```json
{
"kind": 31123,
"content": {
"description": "Check spelling and grammar",
"context_mode": "full",
"llm": "openai/gpt-4o-mini, cheap",
"tools": false,
"max_tokens": 2000,
"temperature": 0.1,
"template": "system:\nYou are a spelling and grammar checker.\n\nRules:\n- Fix spelling errors\n- Fix grammar errors\n- Preserve original formatting\n- Ignore: API, JSON, HTTP, nostr, pubkey, npub, nsec, NIP\n- Canadian English preferred\n- Return ONLY the corrected text, no explanations\n\nuser:\n{{message}}"
"template": "system:\nYou are a spelling and grammar checker.\n\nRules:\n- Fix spelling errors\n- Fix grammar errors\n- Preserve original formatting\n- Return ONLY the corrected text, no explanations\n\nuser:\n{{message}}"
},
"tags": [
["d", "spellcheck"],
@@ -49,279 +48,208 @@ The skill event's `content` field is a JSON object that defines the complete exe
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `description` | string | — | Human-readable description |
| `context_mode` | string | `inject` | `inject`, `full`, or `override` |
| `llm` | string | `default` | LLM fallback chain |
| `tools` | bool/array | `true` | `false` = no tools, `true` = all tools, array = specific tool names |
| `template` | string | — | Context template (required for `full` mode) |
| `soul` | bool | `true` | Whether to include the agent's soul in context |
| `max_tokens` | int | — | Override max tokens for this skill |
| `temperature` | float | — | Override temperature for this skill |
| `template` | string | — | Skill instructions/template text (recommended) |
| `base` | bool | `false` | Optional hint that this skill is intended as base/default behavior |
> Execution parameters (`llm`, `max_tokens`, `temperature`, `seed`, `tools`) are defined on **trigger tags**, not in content.
---
## Context Modes
## Composition Model (No Context Modes)
Skills control how the LLM context window is assembled.
Skills do **not** use `context_mode`.
### inject
Context is assembled from kind `10123` adoption list order:
The skill's instructions are appended to the agent's soul context. The soul is always present.
1. Resolve adopted skills in list order.
2. Expand each skill template/tool variables.
3. Append each resolved skill as context messages in that same order.
4. Append live user/trigger input.
```
┌─────────────────────────────────────┐
│ Soul (agent identity + rules) │
│ │
│ ┌─────────────────────────────┐ │
│ │ Skill instructions │ │
│ ├─────────────────────────────┤ │
│ │ Admin context, history, etc │ │
│ └─────────────────────────────┘ │
│ │
│ User message │
└─────────────────────────────────────┘
```
The adoption list itself is the context definition.
### full
- One adopted skill = single-skill behavior.
- Multiple adopted skills = layered behavior in explicit order.
- Reordering `10123` changes precedence naturally.
The skill provides its own context template. The soul is **not included** unless the template explicitly references `{{soul}}`. This is for specialized, focused tasks that don't need the agent's identity.
### Ordering Convention
```
┌─────────────────────────────────────┐
│ Skill-defined system prompt │
│ (from skill template) │
│ │
│ User message │
└─────────────────────────────────────┘
```
- Earlier adopted skills generally set broader tone/policy.
- Later adopted skills can narrow/specialize behavior.
- If multiple skills strongly conflict, normal prompt-order effects apply.
A `full` mode skill can still include the soul if desired:
### Template Variables Are Tool Calls
```
system:
{{soul}}
Template variables are tool calls.
You are now in translation mode. Translate the following to {{target_language}}.
Respond ONLY with the translation.
When the engine encounters `{{admin_profile}}`, it runs the corresponding tool and inserts the result into context.
user:
{{message}}
```
| Variable | Tool Called | Description |
|----------|-----------|-------------|
| `{{agent_identity}}` | `agent_identity` | Agent identity block |
| `{{admin_profile}}` | `nostr_admin_profile` | Admin kind 0 profile |
| `{{admin_notes}}` | `nostr_admin_notes` | Admin recent notes |
| `{{admin_relays}}` | `nostr_admin_relays` | Admin relay list |
| `{{adopted_skills}}` | `adopted_skills` | Other adopted skill instructions |
| `{{dm_history}}` | *(expand directive)* | Recent DM conversation |
| `{{message}}` | *(built-in)* | Current user message |
| `{{triggering_event}}` | `trigger_event` | Triggering event JSON |
### override
The skill replaces the soul's system prompt but keeps the standard context assembly structure (admin context, history, tools, etc.).
### Summary
| Mode | Soul | Template | Tools | Use Case |
|------|------|----------|-------|----------|
| `inject` | ✅ Always | Soul's template + skill instructions appended | Agent default | Behavioral rules, knowledge |
| `full` | ❌ Unless `{{soul}}` in template | Skill provides template | Skill specifies | Spellcheck, translation, focused analysis |
| `override` | Replaced by skill | Soul's template structure | Agent default | Different personality, same capabilities |
### Template Variables
Skill templates may still use placeholders (for example `{{message}}` or `{{triggering_event}}`) for deterministic triggered-skill interpolation, but the soul runtime context is now assembled primarily through template `tool:` directives rather than a separate `{{tools}}`/variable-resolver layer.
| Variable | Source |
|----------|--------|
| `{{soul}}` | The agent's identity/system context |
| `{{admin_profile}}` | Admin kind 0 profile |
| `{{admin_notes}}` | Admin recent notes |
| `{{admin_relays}}` | Admin relay list |
| `{{adopted_skills}}` | Other adopted skill instructions |
| `{{dm_history}}` | Recent DM conversation |
| `{{message}}` | Current user message |
| `{{triggering_event}}` | For triggered skills, the event JSON |
---
## LLM Specification with Fallback Chains
Each skill specifies which LLM to use with CSS font-family-style fallbacks. The runtime tries each model in order; if one is unavailable (API error, rate limit, not configured), it falls back to the next.
### Format
```
model-spec := model-ref ["," model-ref]*
model-ref := provider "/" model-name
| category-alias
```
### Examples
| Skill | LLM Spec |
|-------|----------|
| Spelling checker | `openai/gpt-4o-mini, cheap` |
| Complex analysis | `anthropic/claude-sonnet-4-20250514, openai/gpt-4o, smart` |
| Translation | `openai/gpt-4o-mini, fast` |
| Default behavior | `default` |
### Category Aliases
Aliases map to models in the agent's config:
```json
{
"llm": {
"provider": "openai",
"model": "gpt-4o",
"aliases": {
"fast": "openai/gpt-4o-mini",
"cheap": "openai/gpt-4o-mini",
"smart": "anthropic/claude-sonnet-4-20250514"
}
}
}
```
If all specified models fail, the agent's default model is used as a last resort.
```mermaid
sequenceDiagram
participant Skill as Skill Spec
participant Resolver as LLM Resolver
participant API1 as Model 1
participant API2 as Model 2
participant Default as Default Model
Skill->>Resolver: "anthropic/claude-sonnet, openai/gpt-4o-mini, cheap"
Resolver->>API1: try anthropic/claude-sonnet
alt Available
API1-->>Resolver: ✅
else Unavailable
API1-->>Resolver: ❌
Resolver->>API2: try openai/gpt-4o-mini
alt Available
API2-->>Resolver: ✅
else Unavailable
Resolver->>Default: resolve "cheap" alias
end
end
```
Unknown variables should resolve to empty values for portability.
---
## Triggered Skills
A triggered skill has a trigger source attached. Didactyl supports `nostr-subscription`, `webhook`, `cron`, and `chain` trigger types.
A triggered skill has a trigger source attached.
Didactyl trigger types:
- `nostr-subscription`
- `webhook`
- `cron`
- `chain`
- `dm`
### Trigger Tags
| Tag | Required | Description |
|---|---|---|
| `trigger` | Yes | Trigger type: `nostr-subscription`, `webhook`, `cron`, or `chain` |
| `filter` | Yes | Type-specific filter (Nostr JSON filter, webhook placeholder payload, cron expression, or source skill `d` tag) |
| `action` | No | `template` or `llm` (default: `llm`) |
| `trigger` | Yes | Trigger type: `nostr-subscription`, `webhook`, `cron`, `chain`, `dm` |
| `filter` | Yes | Type-specific filter |
| `enabled` | No | Whether active (default: `true`) |
| `llm` | No | Model spec fallback chain (e.g., `openai/gpt-4o-mini, cheap`) |
| `max_tokens` | No | Max output tokens for this trigger execution |
| `temperature` | No | Sampling temperature for this trigger execution |
| `seed` | No | Optional deterministic seed where supported |
| `tools` | No | `true` for all tools, `false` for none, or CSV list of allowed tool names |
### Template Actions
### Execution Parameter Resolution
Fast, deterministic, no LLM. The skill content is a template with placeholders from the triggering event:
When a trigger fires:
```
DM admin: '{author_display_name} posted: {content_preview}'
```
1. Start with agent defaults.
2. Apply execution tags from that trigger (`llm`, `max_tokens`, `temperature`, `seed`, `tools`).
3. Execute skill with those effective runtime settings.
4. Restore defaults after the run.
Placeholders: `{event_id}`, `{pubkey}`, `{author_display_name}`, `{kind}`, `{content}`, `{content_preview}`, `{created_at}`, `{relay_url}`
### Adopted vs Triggered Behavior
Output prefixes: `DM admin: ...`, `DM <pubkey>: ...`, `POST: ...`, `LOG: ...`
- **Adopted skill (`10123`)**: contributes instructions/template to context.
- **Triggered skill**: contributes instructions **and** may define execution parameters via trigger tags.
### LLM-Mediated Actions
---
The skill content defines the execution context. The triggering event is available as `{{triggering_event}}`. The skill's LLM spec, context mode, and tool access all apply.
## Trigger Types
```json
{
"kind": 31124,
"content": {
"description": "Analyze mentions and notify admin",
"context_mode": "full",
"llm": "openai/gpt-4o-mini, cheap",
"tools": ["nostr_dm_send"],
"template": "system:\nYou monitor Nostr mentions. When the triggering event mentions Bitcoin or Lightning, summarize it and DM the admin. Otherwise, ignore silently.\n\nTriggering event:\n{{triggering_event}}"
},
"tags": [
["d", "mention-monitor"],
["trigger", "nostr-subscription"],
["filter", "{\"#p\":[\"<admin_pubkey>\"],\"kinds\":[1]}"],
["action", "llm"],
["enabled", "true"]
]
}
```
### Trigger Types
#### `nostr-subscription`
### `nostr-subscription`
`filter` is a JSON-encoded Nostr subscription filter.
```json
["trigger", "nostr-subscription"],
["filter", "{\"#p\":[\"<admin_pubkey>\"],\"kinds\":[1]}"]
["filter", "{\"#p\":[\"<admin_pubkey>\"],\"kinds\":[1]}"],
["llm", "openai/gpt-4o-mini, cheap"],
["temperature", "0"],
["tools", "nostr_query,nostr_dm"],
["enabled", "true"]
```
#### `webhook`
### `webhook`
`filter` is required for schema compatibility and can be a simple placeholder like `{}`; webhook firing happens via HTTP.
`filter` is required and can be `{}`; webhook firing happens via HTTP.
```json
["trigger", "webhook"],
["filter", "{}"]
["filter", "{}"],
["llm", "default"],
["tools", "true"],
["enabled", "true"]
```
#### `cron`
### `cron`
`filter` is a standard 5-field cron expression: `minute hour day-of-month month day-of-week`.
```json
["trigger", "cron"],
["filter", "0 * * * *"]
["filter", "*/5 * * * *"],
["llm", "openai/gpt-4o-mini"],
["max_tokens", "300"],
["enabled", "true"]
```
#### `chain`
### `chain`
`filter` is the source skill `d` tag to chain from.
```json
["trigger", "chain"],
["filter", "source-skill-d-tag"]
["filter", "source-skill-d-tag"],
["llm", "default"],
["enabled", "true"]
```
### Trigger Lifecycle
### `dm`
```mermaid
flowchart TD
subgraph Creation
ADMIN_CMD[Admin: 'Warn me when @jack posts'] --> LLM_REASON[LLM resolves pubkey + builds skill]
LLM_REASON --> SKILL_CREATE[skill_create with trigger tags]
SKILL_CREATE --> PUBLISHED[Skill published to Nostr]
end
`filter` is JSON with sender scope:
subgraph Activation
STARTUP[Didactyl starts up] --> LOAD_SKILLS[Load adopted skills from kind 10123]
LOAD_SKILLS --> FIND_TRIGGERS[Find skills with trigger tags]
FIND_TRIGGERS --> REGISTER[Register trigger by type]
REGISTER --> NOSTR_SUB[nostr-subscription: create Nostr subscriptions]
REGISTER --> CRON_REG[cron: keep expression for poll loop]
REGISTER --> WEBHOOK_REG[webhook: route via /api/trigger/:d_tag]
REGISTER --> CHAIN_REG[chain: wait for source skill completion]
end
- `{"from":"admin"}`
- `{"from":"wot"}`
- `{"from":"any"}`
subgraph Execution
EVENT_IN[Matching Nostr event] --> LOOKUP[Find associated skill]
WEBHOOK_IN[POST /api/trigger/:d_tag] --> LOOKUP
CRON_TICK[cron poll match] --> LOOKUP
LOOKUP --> CHECK_TYPE{Action type?}
CHECK_TYPE -->|template| INTERPOLATE[Interpolate + execute prefix]
CHECK_TYPE -->|llm| RESOLVE[Resolve LLM + assemble context + run]
RESOLVE --> CHAIN_CHECK[Check chain triggers]
INTERPOLATE --> CHAIN_CHECK
CHAIN_CHECK --> CHAIN_FIRE[Fire matching chain triggers]
end
```json
["trigger", "dm"],
["filter", "{\"from\":\"admin\"}"],
["llm", "default"],
["tools", "true"],
["enabled", "true"]
```
PUBLISHED --> LOAD_SKILLS
---
## Private Skill Encoding (`31124`)
Private skills use NIP-44 encryption on event `content`.
Rules for kind `31124`:
- Keep `d` tag exposed so the event stays addressable/replaceable.
- Move non-`d` metadata into plaintext payload before encryption.
- Encrypt full payload with NIP-44 and store ciphertext in event `content`.
- On receive: resolve by `d`, decrypt `content`, then read content + private tags.
### Private Skill Event (on relay)
```json
{
"kind": 31124,
"content": "<nip44-ciphertext>",
"tags": [
["d", "mention-monitor"]
]
}
```
### Decrypted Private Payload (application-level JSON)
```json
{
"content": {
"description": "Monitor mentions and DM summaries",
"template": "When {{triggering_event}} includes Bitcoin or Lightning, summarize and DM admin."
},
"private_tags": [
["scope", "private"],
["trigger", "nostr-subscription"],
["filter", "{\"#p\":[\"<admin_pubkey>\"],\"kinds\":[1]}"],
["llm", "openai/gpt-4o-mini, fast"],
["temperature", "0"],
["seed", "42"],
["tools", "nostr_query,nostr_dm"],
["enabled", "true"]
]
}
```
---
@@ -332,47 +260,23 @@ flowchart TD
sequenceDiagram
participant Input as Message/Trigger
participant Dispatch as Dispatcher
participant Skill as Skill Resolver
participant LLM_Res as LLM Resolver
participant Adopt as Adoption Resolver (10123)
participant Ctx as Context Assembler
participant Trig as Trigger Runtime Params
participant LLM as LLM API
Input->>Dispatch: message or trigger event
Dispatch->>Skill: which skill handles this?
alt No specific skill
Skill-->>Dispatch: use default soul context
Dispatch->>LLM_Res: resolve "default" LLM
else Skill with context_mode=inject
Skill-->>Dispatch: soul + skill instructions
Dispatch->>LLM_Res: resolve skill.llm or "default"
else Skill with context_mode=full
Skill-->>Dispatch: skill template only
Dispatch->>LLM_Res: resolve skill.llm
end
LLM_Res->>LLM_Res: try models in fallback order
LLM_Res-->>Dispatch: resolved model
Dispatch->>Ctx: assemble context per mode
Ctx->>LLM: request with resolved model + context
Dispatch->>Adopt: load adopted skills in list order
Adopt-->>Ctx: ordered skill templates
Ctx->>Ctx: resolve template variables via tools
Dispatch->>Trig: resolve trigger execution tags
Trig-->>LLM: model + max_tokens + temperature + seed + tool policy
Ctx->>LLM: composed messages
LLM-->>Input: response
```
---
## The Soul and Skills
The **soul** is the agent's default identity and context template. Skills interact with it based on their context mode:
- **`inject`** — soul always present; skill instructions layered on top
- **`full`** — soul absent unless template includes `{{soul}}`
- **`override`** — skill replaces soul prompt, keeps standard context structure
A spelling checker runs with no soul — purely functional, minimal context, cheap model. A complex analysis skill includes the full soul and all context parts. The soul is the default, not a requirement.
---
## Limits and Safety
| Limit | Default | Description |
@@ -380,7 +284,6 @@ A spelling checker runs with no soul — purely functional, minimal context, che
| Max concurrent triggers | 16 | Prevents resource exhaustion |
| Trigger cooldown | 60s per skill | Prevents rapid-fire execution |
| LLM action rate limit | 10/min | Prevents runaway LLM costs |
| Template action rate limit | 60/min | Prevents DM spam |
---
@@ -390,21 +293,25 @@ A spelling checker runs with no soul — purely functional, minimal context, che
|---|---|
| Skills | Kind 31123/31124 events |
| Adopted skills | Kind 10123 event |
| Trigger definitions | Tags on skill events |
| Trigger definitions + execution params | Tags on skill events |
---
## Future Extensions
## Portability Guidelines
| Extension | Description |
|---|---|
| Skill composition | Pipeline multiple skills |
| Agent-to-agent sharing | Discover and adopt skills across agents |
| Trigger marketplace | Popular triggers rise via adoption count |
To keep skills reusable across agents/clients:
- Prefer generic instructions over implementation-specific assumptions.
- Treat tool names as capabilities, not platform internals.
- Resolve unknown variables safely (empty result, no hard failure).
- Keep app-specific tags optional (`["app","didactyl"]`).
A skill should still be useful even when some variables/tools are unavailable.
---
## Related Documentation
- Tool architecture and complete tool catalog: [TOOLS.md](TOOLS.md)
- Project overview and runtime behavior: [README.md](../README.md)
- Context assembly model: [CONTEXT.md](CONTEXT.md)
- Project overview/runtime behavior: [README.md](../README.md)
+16 -1
View File
@@ -12,7 +12,9 @@ This document describes the tools architecture: what tools are, how they are exp
## What Tools Are
Tools are the agent's hands. They are hardcoded C functions that the LLM can invoke during a conversation to take actions in the world.
Tools are in the agent's hands — the chisels in the woodshop. They are hardcoded C functions that the LLM can invoke during a conversation to take actions in the world.
A **skill** teaches the agent *how* to carve — the technique, the judgment, the decision-making. A **tool** is the chisel — the physical capability. The skill never directly uses the chisel without the craftsperson (the LLM) in the loop. If you want a hardcoded program that runs without reasoning, that's a tool or an external program — not a skill.
## How Tools Work
@@ -105,6 +107,19 @@ These tools manage skill and trigger lifecycle; skill semantics and trigger exec
| `local_file_write` | Write text content to a local file in the configured working directory |
| `tool_list` | List available tools with name, description, and JSON parameter schema |
### Cashu Wallet Tools (NIP-60)
| Tool | Description |
|---|---|
| `cashu_wallet_balance` | Return wallet balances aggregated by mint and unit from loaded token proofs |
| `cashu_wallet_info` | Fetch mint info for a specific `mint_url` (or configured default mint) |
| `cashu_wallet_mint_quote` | Request a mint quote for an amount and unit |
| `cashu_wallet_mint_check` | Check whether a mint quote is paid/issued |
| `cashu_wallet_mint_claim` | Claim newly minted proofs for a paid quote and persist token event |
| `cashu_wallet_melt_quote` | Request a melt quote for a Lightning invoice/payment request |
| `cashu_wallet_melt_pay` | Pay a melt quote using selected proofs and persist history/token rollover |
| `cashu_wallet_check_proofs` | Ask mint for current proof states and summarize unspent/pending/spent proofs |
### Content Publishing Conveniences
| Tool | Description |
+57 -67
View File
@@ -53,8 +53,7 @@ show_usage() {
echo " -M, --major: Increment major version, zero minor+patch (v0.1.0 → v1.0.0)"
echo ""
echo "RELEASE MODE (-r flag):"
echo " - Build static binary using build_static.sh"
echo " - Create source tarball"
echo " - Build static x86_64 and arm64 binaries using build_static.sh"
echo " - Git add, commit, push, and create Gitea release with assets"
echo " - Can be combined with version increment flags"
echo ""
@@ -321,9 +320,9 @@ git_commit_and_push_no_tag() {
fi
}
# Function to build release binary
# Function to build release binaries
build_release_binary() {
print_status "Building release binary..."
print_status "Building release binaries (x86_64 + arm64)..."
# Check if build_static.sh exists
if [[ ! -f "build_static.sh" ]]; then
@@ -331,35 +330,12 @@ build_release_binary() {
return 1
fi
# Run the static build script
if ./build_static.sh > /dev/null 2>&1; then
print_success "Built static binary successfully"
# Run the static build script for both platforms
if ./build_static.sh --all-platforms > /dev/null 2>&1; then
print_success "Built static binaries successfully"
return 0
else
print_error "Failed to build static binary"
return 1
fi
}
# Function to create source tarball
create_source_tarball() {
print_status "Creating source tarball..."
local tarball_name="didactyl-${NEW_VERSION#v}.tar.gz"
# Create tarball excluding build artifacts and git files
if tar -czf "$tarball_name" \
--exclude='build/*' \
--exclude='.git*' \
--exclude='*.log' \
--exclude='*.tar.gz' \
--exclude='c-relay/*' \
. > /dev/null 2>&1; then
print_success "Created source tarball: $tarball_name"
echo "$tarball_name"
return 0
else
print_error "Failed to create source tarball"
print_error "Failed to build one or more static binaries"
return 1
fi
}
@@ -367,8 +343,8 @@ create_source_tarball() {
# Function to upload release assets to Gitea
upload_release_assets() {
local release_id="$1"
local binary_path="$2"
local tarball_path="$3"
local binary_x86_path="$2"
local binary_arm64_path="$3"
print_status "Uploading release assets..."
@@ -383,9 +359,9 @@ upload_release_assets() {
local assets_url="$api_url/releases/$release_id/assets"
print_status "Assets URL: $assets_url"
# Upload binary
if [[ -f "$binary_path" ]]; then
print_status "Uploading binary: $(basename "$binary_path")"
# Upload x86_64 binary
if [[ -f "$binary_x86_path" ]]; then
print_status "Uploading binary: $(basename "$binary_x86_path")"
# Retry loop for eventual consistency
local max_attempts=3
@@ -394,11 +370,11 @@ upload_release_assets() {
print_status "Upload attempt $attempt/$max_attempts"
local binary_response=$(curl -fS -X POST "$assets_url" \
-H "Authorization: token $token" \
-F "attachment=@$binary_path;filename=$(basename "$binary_path")" \
-F "name=$(basename "$binary_path")")
-F "attachment=@$binary_x86_path;filename=$(basename "$binary_x86_path")" \
-F "name=$(basename "$binary_x86_path")")
if echo "$binary_response" | grep -q '"id"'; then
print_success "Uploaded binary successfully"
print_success "Uploaded x86_64 binary successfully"
break
else
print_warning "Upload attempt $attempt failed"
@@ -406,7 +382,7 @@ upload_release_assets() {
print_status "Retrying in 2 seconds..."
sleep 2
else
print_error "Failed to upload binary after $max_attempts attempts"
print_error "Failed to upload x86_64 binary after $max_attempts attempts"
print_error "Response: $binary_response"
fi
fi
@@ -414,19 +390,36 @@ upload_release_assets() {
done
fi
# Upload source tarball
if [[ -f "$tarball_path" ]]; then
print_status "Uploading source tarball: $(basename "$tarball_path")"
local tarball_response=$(curl -s -X POST "$api_url/releases/$release_id/assets" \
-H "Authorization: token $token" \
-F "attachment=@$tarball_path;filename=$(basename "$tarball_path")")
# Upload arm64 binary
if [[ -f "$binary_arm64_path" ]]; then
print_status "Uploading binary: $(basename "$binary_arm64_path")"
if echo "$tarball_response" | grep -q '"id"'; then
print_success "Uploaded source tarball successfully"
else
print_warning "Failed to upload source tarball: $tarball_response"
fi
local max_attempts=3
local attempt=1
while [[ $attempt -le $max_attempts ]]; do
print_status "Upload attempt $attempt/$max_attempts"
local binary_response=$(curl -fS -X POST "$assets_url" \
-H "Authorization: token $token" \
-F "attachment=@$binary_arm64_path;filename=$(basename "$binary_arm64_path")" \
-F "name=$(basename "$binary_arm64_path")")
if echo "$binary_response" | grep -q '"id"'; then
print_success "Uploaded arm64 binary successfully"
break
else
print_warning "Upload attempt $attempt failed"
if [[ $attempt -lt $max_attempts ]]; then
print_status "Retrying in 2 seconds..."
sleep 2
else
print_error "Failed to upload arm64 binary after $max_attempts attempts"
print_error "Response: $binary_response"
fi
fi
((attempt++))
done
fi
}
# Function to create Gitea release
@@ -515,33 +508,30 @@ main() {
# Commit and push
git_commit_and_push_no_tag
# Build release binary
# Build release binaries
local binary_x86_path=""
local binary_arm64_path=""
if build_release_binary; then
local binary_path="build/didactyl_static_x86_64"
[[ -f "build/didactyl_static_x86_64" ]] && binary_x86_path="build/didactyl_static_x86_64"
[[ -f "build/didactyl_static_arm64" ]] && binary_arm64_path="build/didactyl_static_arm64"
else
print_warning "Binary build failed, continuing with release creation"
if [[ -f "build/didactyl_static_x86_64" ]]; then
print_status "Using existing binary from previous build"
binary_path="build/didactyl_static_x86_64"
else
binary_path=""
print_status "Using existing x86_64 binary from previous build"
binary_x86_path="build/didactyl_static_x86_64"
fi
if [[ -f "build/didactyl_static_arm64" ]]; then
print_status "Using existing arm64 binary from previous build"
binary_arm64_path="build/didactyl_static_arm64"
fi
fi
# Create source tarball
local tarball_path=""
if tarball_path=$(create_source_tarball); then
: # tarball_path is set by the function
else
print_warning "Source tarball creation failed, continuing with release creation"
fi
# Create Gitea release
local release_id=""
if release_id=$(create_gitea_release); then
if [[ "$release_id" =~ ^[0-9]+$ ]]; then
if [[ -n "$release_id" && (-n "$binary_path" || -n "$tarball_path") ]]; then
upload_release_assets "$release_id" "$binary_path" "$tarball_path"
if [[ -n "$release_id" && (-n "$binary_x86_path" || -n "$binary_arm64_path") ]]; then
upload_release_assets "$release_id" "$binary_x86_path" "$binary_arm64_path"
fi
print_success "Release $NEW_VERSION completed successfully!"
else
+310
View File
@@ -0,0 +1,310 @@
# Decentralized Didactyl
## The Question
Can you run Didactyl on multiple servers to gain censorship resistance, geographic distribution, and high availability?
---
## Same Keys vs. Different Keys
### Same Private Key on Multiple Servers
Running two or more Didactyl instances with the **same nsec** means they share a Nostr identity — same pubkey, same signature authority. This breaks almost immediately.
The core problem is **state conflicts on replaceable events**. Didactyl's identity is built on replaceable Nostr event kinds — kind `10002` (relay list), kind `10123` (skill adoption list), kind `31120` (soul), kind `31123`/`31124` (skills), kind `0` (profile). Replaceable events use `created_at` timestamps where the latest event wins. Two instances publishing the same replaceable kind within seconds creates a race where relays disagree on which version is canonical.
Beyond relay-level conflicts, each Didactyl process maintains significant **in-memory state** that is never shared: DM dedup caches, message fingerprint ring buffers, trigger cooldown timers, conversation history, and the self-skill cache. Two instances with the same key both subscribe to `#p` = their shared pubkey. The same admin DM arrives at both. Both process it. Both call the LLM. Both reply. The admin gets two possibly contradictory responses.
Making same-key work would require a coordination layer — leader election, distributed locks, or external shared state — all of which add complexity and defeat the decentralization goal.
### Different Private Keys on Multiple Servers
Each instance is a **distinct agent** with its own Nostr identity. No state conflicts, no replaceable-event races, no shared in-memory caches to synchronize. Each agent independently subscribes to relays, processes DMs, calls its LLM, and replies.
This is architecturally clean and aligned with how Nostr works. The question becomes: how do multiple independent agents cooperate to serve a single admin?
---
## How We Arrived at the Broadcast-Debounce Model
The first instinct with different keys is **delegation** — a primary agent receives the admin's DM and farms out subtasks to specialist agents. But this adds a single point of failure (the primary), requires an agent-to-agent trust protocol, and means the admin is still talking to one agent.
A simpler model: **broadcast the same message to all agents, let them all respond independently, and debounce on the admin side.** The admin sends the same DM to N agent pubkeys. Each agent processes it through its own LLM, its own tools, its own context. The admin collects replies and accepts the first one (or the best one). The others are discarded.
This requires no coordination protocol between agents. No leader election. No shared state. No new Nostr event kinds. The agents don't even need to know about each other. All complexity lives at the edge — in the admin's client.
---
## The Broadcast-Debounce Architecture
```mermaid
flowchart TD
ADMIN[Admin Client<br/>with fan-out + debounce]
ADMIN -->|"DM: task"| A[Agent A<br/>Server 1 — Iceland<br/>anthropic/claude-sonnet]
ADMIN -->|"DM: task"| B[Agent B<br/>Server 2 — Brazil<br/>openai/gpt-4o]
ADMIN -->|"DM: task"| C[Agent C<br/>Server 3 — Singapore<br/>local Ollama]
A -->|"DM reply"| ADMIN
B -->|"DM reply"| ADMIN
C -->|"DM reply"| ADMIN
ADMIN -->|"Accept first reply,<br/>discard rest"| RESULT[Response shown to admin]
```
### What Each Agent Needs
Each agent runs standard Didactyl with its own config:
- **Own nsec/npub** — distinct Nostr identity
- **Same admin pubkey** — all agents recognize the same admin
- **Same soul** — published as kind `31120` from each agent's key, or adopted from a shared author
- **Same adopted skills** — each agent's kind `10123` references the same skill events
- **Own LLM config** — can be different providers for diversity
- **Own relay list** — can overlap or be completely different for geographic distribution
No code changes to Didactyl are required. Each agent is a standard, unmodified instance.
### What the Admin Client Needs
The admin side needs a thin coordination layer:
1. **Fan-out** — when the admin sends a message, the client sends it as a DM to all N agent pubkeys
2. **Collection** — the client listens for DM replies from all agent pubkeys
3. **Debounce** — the client tags each outgoing message with a task identifier (hash of message + nonce). The first reply that corresponds to a pending task is accepted. Subsequent replies for the same task are logged but suppressed from display.
This could be implemented as:
- A modified Nostr client
- A thin proxy between the admin and the agents
- A Didactyl agent whose sole job is fan-out and collection
### Properties
| Property | Benefit |
|----------|---------|
| **No shared state** | Each agent is fully independent — no coordination protocol needed |
| **No code changes** | Works with current Didactyl for read-only tasks |
| **Censorship resistant** | Kill any N-1 servers, the last one still works |
| **Provider diverse** | Different LLMs on each agent — different failure modes, different strengths |
| **Geographically distributed** | Different jurisdictions, different relay access |
| **Graceful degradation** | Losing agents means fewer responses, not failure |
| **Complexity at the edge** | Agents stay simple and sovereign; the admin client handles coordination |
### The Write-Action Problem
For read-only tasks — questions, summaries, drafts — the model works perfectly. All agents respond, admin picks one, no side effects.
For write actions — "post a note about Bitcoin" — all three agents independently publish to Nostr. Three posts appear. The admin wanted one.
**Solution: two-phase draft-then-confirm.** Teach all agents via their soul or an adopted skill to never execute write actions directly. Instead, they draft the action and report what they *would* do. The admin reviews the drafts, picks one, and sends a confirmation DM to that specific agent. The other agents' drafts are simply never confirmed.
The skill instruction is straightforward:
> When asked to publish, post, react, delete, or execute any action with side effects, draft the content and present it for approval. Do not execute until the admin explicitly confirms.
This requires no code changes — only a soul or skill update. It also happens to be good practice for any agent handling important actions.
### Trigger Handling
Triggered skills (cron, nostr-subscription, webhook) present the same duplication issue as write actions — all agents fire the same trigger independently.
Options:
- **Disable triggers on all but one agent** — simple, but creates a single point of failure for triggered tasks
- **Use the draft-then-confirm pattern for triggered actions** — triggers draft and report to admin rather than acting directly
- **Accept duplication for idempotent triggers** — reactions, replaceable event updates, and monitoring alerts are harmless when duplicated
- **Shard triggers across agents** — Agent A handles cron triggers, Agent B handles nostr-subscription triggers, Agent C handles webhooks
### Future: Agent Awareness
In the basic model, agents don't know about each other. A future enhancement could add awareness:
- Each agent publishes a heartbeat event (kind `30078` with a timestamp)
- Other agents (or the admin client) monitor heartbeats to detect which agents are alive
- The admin client adjusts fan-out based on which agents are responsive
This remains fully Nostr-native — heartbeats are just events on relays — and requires no direct agent-to-agent communication.
---
## Beyond Nostr Posts: Software Development as the Task
The broadcast-debounce model above assumes the agents' primary job is Nostr social activity — posting notes, reacting, querying relays. But what if the task is **software development and infrastructure management**? For example: creating and maintaining a website, deployed across servers in different jurisdictions.
This changes the model fundamentally. The agents are no longer just talking — they are **building things on their local machines**.
### What Didactyl Already Has
Each agent already has local system tools:
| Tool | Capability |
|------|-----------|
| `local_shell_exec` | Execute any shell command — git, npm, docker, systemctl, curl |
| `local_file_read` | Read source files from the working directory |
| `local_file_write` | Write/create source files in the working directory |
| `local_http_fetch` | Make HTTP requests — test endpoints, call APIs, download resources |
An agent with these tools can already: clone a repo, edit source code, run a build, start a dev server, deploy to production, check if a site is up, read logs, and fix issues. The LLM reasons about what to do; the tools are the hands.
### The Shift: From Redundancy to Distribution
With Nostr posting, multiple agents doing the same task is **redundancy** — you want one result and discard the rest. With software development, multiple agents doing *different parts* of the same project is **distribution** — you want all of them to contribute.
```mermaid
flowchart TD
subgraph "Nostr Posting Model"
direction LR
N_ADMIN[Admin] -->|"Same task"| N_A[Agent A]
N_ADMIN -->|"Same task"| N_B[Agent B]
N_ADMIN -->|"Same task"| N_C[Agent C]
N_A -->|"Response 1"| N_DEDUP[Debounce:<br/>pick one]
N_B -->|"Response 2"| N_DEDUP
N_C -->|"Response 3"| N_DEDUP
end
subgraph "Software Dev Model"
direction LR
S_ADMIN[Admin] -->|"Build the site"| S_A[Agent A:<br/>Frontend]
S_ADMIN -->|"Build the site"| S_B[Agent B:<br/>Backend API]
S_ADMIN -->|"Build the site"| S_C[Agent C:<br/>Infrastructure]
S_A -->|"React app ready"| S_MERGE[Integration:<br/>combine all parts]
S_B -->|"API deployed"| S_MERGE
S_C -->|"Nginx + TLS configured"| S_MERGE
end
```
### Architecture: Agents as Jurisdiction-Local Builders
Consider a website that needs to exist in multiple jurisdictions for censorship resistance. Each agent lives on a server in a different country and maintains a local copy of the site.
```mermaid
flowchart TD
ADMIN[Admin<br/>npub1admin...]
GIT[(Git Repo<br/>shared source of truth)]
subgraph "Iceland"
A[Agent A<br/>npub1aaa...]
A_FS[Local filesystem:<br/>/var/www/mysite]
A_SRV[Nginx serving<br/>mysite.is]
A --> A_FS --> A_SRV
end
subgraph "Brazil"
B[Agent B<br/>npub1bbb...]
B_FS[Local filesystem:<br/>/var/www/mysite]
B_SRV[Nginx serving<br/>mysite.br]
B --> B_FS --> B_SRV
end
subgraph "Singapore"
C[Agent C<br/>npub1ccc...]
C_FS[Local filesystem:<br/>/var/www/mysite]
C_SRV[Nginx serving<br/>mysite.sg]
C --> C_FS --> C_SRV
end
ADMIN -->|"DM: update the homepage"| A
ADMIN -->|"DM: update the homepage"| B
ADMIN -->|"DM: update the homepage"| C
A <-->|"git pull / push"| GIT
B <-->|"git pull / push"| GIT
C <-->|"git pull / push"| GIT
```
### Git as the Coordination Layer
In the Nostr posting model, the write-action problem was solved with draft-then-confirm. For software development, the natural coordination layer is **git**.
- All agents share a git repository (hosted on Gitea, GitHub, a Nostr-based git relay, or even a bare repo on one of the servers)
- Each agent works on its local clone
- Before making changes, the agent pulls latest
- After making changes, the agent commits and pushes
- Conflicts are resolved by the LLM (or flagged to the admin)
Git gives you:
- **Atomic changes** — commits are all-or-nothing
- **Conflict detection** — if two agents edit the same file, git tells you
- **History** — every change is traceable to which agent made it
- **Rollback** — bad changes can be reverted
The agent already has `local_shell_exec` which can run `git pull`, `git add`, `git commit`, `git push`. No new tools needed.
### Three Operational Modes
Depending on the task, the admin can use different patterns:
#### Mode 1: Broadcast-Identical (Same Task, All Servers)
> "Pull latest and rebuild the site"
All agents do the same thing on their local server. This is the deployment/ops pattern — you want the same action everywhere. No debounce needed; all agents should execute.
#### Mode 2: Broadcast-Debounce (Same Task, One Result)
> "Write a new About page"
All agents draft a version. Admin picks the best one. That agent commits and pushes. The other agents then pull the update in the next sync cycle. This is the creative/development pattern.
#### Mode 3: Directed (Specific Task, Specific Agent)
> To Agent A only: "Debug why the Iceland server returns 502"
The admin sends a DM to one specific agent because the task is server-specific. This is the ops/debugging pattern.
### The Sync Cycle
For the site to stay consistent across jurisdictions, agents need a periodic sync. This can be a **cron-triggered skill**:
```
You are a deployment sync agent. Every 15 minutes:
1. Run `git pull` in the project directory
2. If there are new changes, run the build command
3. Restart the web server if the build succeeded
4. DM the admin a brief status: what changed, build result, server status
5. If the pull fails due to conflicts, DM the admin with the conflict details and do not build
```
This skill already works with Didactyl's existing `cron` trigger type and `local_shell_exec` tool. Each agent runs it independently on its own server.
### What Changes vs. the Nostr Model
| Aspect | Nostr Posting | Software Development |
|--------|--------------|---------------------|
| **Primary tools** | `nostr_post`, `nostr_query` | `local_shell_exec`, `local_file_write`, `local_file_read` |
| **Coordination** | Debounce on admin side | Git repo as shared state |
| **Write conflicts** | Replaceable events (last-write-wins) | Git merge conflicts (explicit resolution) |
| **Broadcast meaning** | Redundancy — pick one response | Deployment — all servers execute |
| **Agent specialization** | All agents are identical | Agents can have server-specific skills |
| **State** | Nostr relays (stateless agents) | Local filesystem (stateful agents) |
| **Failure mode** | Agent down = fewer responses | Agent down = one jurisdiction offline |
### The Stateful Agent Problem
This is the fundamental shift. Nostr-posting agents are essentially stateless — their identity and skills live on relays, and destroying the host doesn't kill the agent. Software development agents are **deeply stateful** — they have local files, running services, build artifacts, and server configurations that don't exist on Nostr.
Git mitigates this: if an agent's server dies, you spin up a new server, install Didactyl with the same agent keys, and `git clone` the repo. The agent recovers its working state from git. But the server-specific state (Nginx config, TLS certs, DNS, running processes) needs to be reconstructable too.
This suggests a **infrastructure-as-code** discipline where everything about the server's configuration is in the git repo:
- Nginx configs
- Docker compose files
- TLS certificate automation (Let's Encrypt)
- Deployment scripts
The agent's first-boot skill becomes: "Clone the repo, run the setup script, verify the site is serving."
### Jurisdiction-Specific Considerations
Each agent can have **server-specific skills** that account for local differences:
| Agent | Jurisdiction | Specific Skills |
|-------|-------------|----------------|
| Agent A | Iceland | Icelandic privacy law compliance, `.is` domain management |
| Agent B | Brazil | LGPD compliance checks, `.br` domain management |
| Agent C | Singapore | PDPA compliance, `.sg` domain management, Asia-Pacific CDN config |
These are adopted as private skills (kind `31124`) specific to each agent, while the core development skills (kind `31123`) are shared across all agents.
### Summary
The broadcast-debounce model extends naturally to software development, but the coordination mechanism shifts from admin-side debounce to **git as shared state**. The three operational modes — broadcast-identical for deployment, broadcast-debounce for development, and directed for debugging — cover the full range of tasks. Didactyl's existing tools (`local_shell_exec`, `local_file_read`, `local_file_write`) and trigger types (`cron` for sync cycles) already support this without code changes. The main new requirement is disciplined infrastructure-as-code so that agent state is recoverable from git.
@@ -0,0 +1,244 @@
# Admin Skills Loading & skill_list Redesign
## Problem Statement
1. **Agent only loads its own skills from nostr** — the admin's public skills (kind `31123`) are never fetched or cached at startup, so the agent cannot discover or adopt them.
2. **`skill_list` only shows adopted skills** — there is no way to see available-but-not-adopted skills, making skill management opaque.
3. **`created_at` displays in scientific notation** — Unix timestamps (~1.7e9) are stored as `double` via cJSON and printed in scientific notation (e.g., `1.7e+09`).
## Current Architecture
```mermaid
flowchart TD
A[main.c startup] --> B[nostr_handler_subscribe_self_skills]
B --> C[Filter: kinds 31123+31124+10123, authors=agent_pubkey]
C --> D[on_self_skill_event callback]
D --> E[self_skill_cache_upsert_event_locked]
E --> F{pubkey == agent?}
F -->|Yes| G[Cache in g_self_skill_events]
F -->|No| H[Reject - BLOCKER]
I[skill_list tool] --> J[nostr_handler_get_self_skill_events_json]
J --> K[Filter: only kind 31123+31124]
K --> L{In adoption list?}
L -->|Yes| M[Include in output]
L -->|No| N[Skip]
```
### Key Files
| File | Role |
|------|------|
| `src/nostr_handler.c:1831` | `nostr_handler_subscribe_self_skills()` — subscribes to agent's own skill events |
| `src/nostr_handler.c:646` | `self_skill_cache_upsert_event_locked()` — caches events, **rejects non-agent pubkeys** |
| `src/nostr_handler.c:2446` | `nostr_handler_get_self_skill_events_json()` — returns cached skill events |
| `src/tools/tool_skill.c:655` | `execute_skill_list()` — lists only adopted skills from cache |
| `src/tools/tool_skill.c:373` | `extract_skill_summary_local()` — builds summary JSON, has `created_at` bug |
| `src/agent.c:1503` | `refresh_adopted_skills_cache_if_needed()` — fetches skill content for context injection |
## Proposed Changes
### 1. Subscribe to Admin's Public Skills on Startup
**File: `src/nostr_handler.c`**
Modify `nostr_handler_subscribe_self_skills()` to also include the admin's pubkey in the authors filter for kind `31123` (public skills only — we should not fetch the admin's private skills or adoption list).
**Approach A — Expand the existing subscription filter:**
Add `g_cfg->admin.pubkey` to the `authors` array in the existing subscription. This is the simplest approach since the subscription already handles kinds `31123`, `31124`, `10123`.
However, this would also fetch the admin's `31124` (private) and `10123` (adoption list) events, which we don't need and can't decrypt. So we need **two subscriptions**:
**Approach B — Add a second subscription (recommended):**
Keep the existing self-skill subscription unchanged. Add a new subscription specifically for the admin's public skills:
- kinds: `[31123]` only
- authors: `[admin_pubkey]`
- limit: 100
This keeps concerns separated and avoids fetching admin private skills or adoption lists.
**New function:** `nostr_handler_subscribe_admin_skills()` or extend the existing function with a second subscription block.
### 2. Expand Skill Cache to Accept Admin Events
**File: `src/nostr_handler.c`**
The core blocker is in `self_skill_cache_upsert_event_locked()` at line 667:
```c
if (!g_cfg || strcmp(pubkey->valuestring, g_cfg->keys.public_key_hex) != 0) {
return;
}
```
**Changes needed:**
1. **Rename the cache** from `g_self_skill_events` to `g_skill_events` (or keep the name but change semantics) to reflect it now holds both agent and admin skills.
2. **Relax the pubkey check** to accept events from either the agent's pubkey OR the admin's pubkey:
```c
int is_agent = (strcmp(pubkey->valuestring, g_cfg->keys.public_key_hex) == 0);
int is_admin = (g_cfg->admin.pubkey[0] != '\0' &&
strcmp(pubkey->valuestring, g_cfg->admin.pubkey) == 0);
if (!is_agent && !is_admin) {
return;
}
```
3. **For admin events, only accept kind `31123`** (public skills) — reject `31124` and `10123` from admin:
```c
if (is_admin && kind_val != 31123) {
return;
}
```
4. **Update `nostr_handler_get_self_skill_events_json()`** to return ALL cached skill events (agent + admin), not just agent's. The function name could be renamed to `nostr_handler_get_skill_events_json()` but to minimize churn, we can keep the name and update the semantics.
5. **Add a new accessor** `nostr_handler_get_all_skill_events_json()` that returns everything, while keeping the existing function for backward compatibility if needed. Or simply update the existing one since `skill_list` is the only consumer that needs the broader view.
### 3. Redesign `skill_list` Output
**File: `src/tools/tool_skill.c`**
Currently `execute_skill_list()` only shows adopted skills. The new design:
#### New Output Structure
```json
{
"success": true,
"summary": [
{
"d_tag": "spellcheck",
"owner": "agent",
"pubkey": "52a3e8...",
"kind": 31123,
"adopted": true
},
{
"d_tag": "translate",
"owner": "admin",
"pubkey": "8fdd1c...",
"kind": 31123,
"adopted": false
},
{
"d_tag": "code-review",
"owner": "admin",
"pubkey": "8fdd1c...",
"kind": 31123,
"adopted": true
}
],
"skills": [
{
"kind": 31123,
"created_at": 1710412800,
"id": "abc123...",
"pubkey": "52a3e8...",
"owner": "agent",
"d_tag": "spellcheck",
"scope": "public",
"description": "Spelling and grammar checker",
"adopted": true,
"content_preview": "...",
"content_length": 450,
"content_truncated": false
}
],
"count": 3,
"adopted_count": 2
}
```
#### Key Changes to `execute_skill_list()`
1. **Remove the adoption-only filter** — iterate ALL cached skill events (agent + admin), not just adopted ones.
2. **Add `adopted` boolean** to each skill summary by checking against the adoption list.
3. **Add `owner` field** — `"agent"` if pubkey matches agent, `"admin"` if pubkey matches admin, otherwise the raw pubkey.
4. **Add `summary` array** at the top — one compact line per skill with just `d_tag`, `owner`, `kind`, and `adopted` status.
5. **Keep `skills` array** with full details on each skill.
6. **Add `adopted_count`** alongside existing `count`.
7. **Optional `filter` parameter** — add an optional `adopted` boolean parameter to filter the list:
- `{"adopted": true}` — show only adopted skills (current behavior)
- `{"adopted": false}` — show only non-adopted skills
- omitted — show all skills
### 4. Fix `created_at` Scientific Notation
**File: `src/tools/tool_skill.c`**
In `extract_skill_summary_local()` at line 389:
```c
if (created_at && cJSON_IsNumber(created_at)) {
cJSON_AddNumberToObject(summary, "created_at", created_at->valuedouble);
}
```
The issue is that `cJSON_AddNumberToObject` stores the value as a `double`, and cJSON's printer uses `%g` format which switches to scientific notation for large numbers.
**Fix:** Cast to `long long` and use `cJSON_AddRaw` or format as a string-encoded integer. The cleanest approach with cJSON:
```c
if (created_at && cJSON_IsNumber(created_at)) {
char ts_buf[32];
snprintf(ts_buf, sizeof(ts_buf), "%lld", (long long)created_at->valuedouble);
cJSON* ts_item = cJSON_CreateRaw(ts_buf);
if (ts_item) {
cJSON_AddItemToObject(summary, "created_at", ts_item);
}
}
```
This outputs the timestamp as a raw integer literal in JSON (e.g., `1710412800`) instead of scientific notation.
**Apply the same fix** to the `kind` field if it also uses `cJSON_AddNumberToObject` — though `kind` values (31123, 31124, 10123) are small enough to not trigger scientific notation.
## Data Flow After Changes
```mermaid
flowchart TD
A[main.c startup] --> B[nostr_handler_subscribe_self_skills]
B --> C[Sub 1: kinds 31123+31124+10123, authors=agent]
B --> D[Sub 2: kinds 31123, authors=admin]
C --> E[on_self_skill_event]
D --> F[on_admin_skill_event - or reuse same callback]
E --> G[skill_cache_upsert_event_locked]
F --> G
G --> H{pubkey == agent OR admin?}
H -->|Yes| I{admin? only kind 31123}
H -->|No| J[Reject]
I -->|OK| K[Cache in g_skill_events]
L[skill_list tool] --> M[get_all_skill_events_json]
M --> N[For each event]
N --> O[Check adoption list]
O --> P[Build summary + detail with adopted flag]
```
## Implementation Order
1. **Fix `created_at` scientific notation** — smallest, isolated change
2. **Expand cache to accept admin pubkey** — modify `self_skill_cache_upsert_event_locked()`
3. **Add admin skill subscription** — new subscription in `nostr_handler_subscribe_self_skills()` or new function
4. **Redesign `skill_list` output** — add summary section, show all skills with adoption status
5. **Update `nostr_handler.h`** — add any new function declarations
6. **Update tool schema** — add `adopted` filter parameter to `skill_list` schema in `tools_schema.c`
7. **Test** — verify with `--test-tool skill_list '{}'`
## Edge Cases
- **Admin pubkey not configured** — skip admin subscription, behave as before
- **Admin and agent publish skill with same d-tag** — both appear in the list, distinguished by `owner` field
- **Admin skill already adopted** — shows `adopted: true` in summary
- **Live updates** — admin skill events received after startup should also be cached (the subscription stays open)
+337
View File
@@ -0,0 +1,337 @@
# Agent Cloning
## The Idea
A Didactyl agent can clone itself.
Once launched, a Didactyl agent lives on Nostr. Its identity is a keypair. Its personality is a skill. Its knowledge is in its memories. Its capabilities are adopted skills. Its social graph is a contact list. Its infrastructure preferences are a relay list. All of these are Nostr events — signed, timestamped, published to relays.
There are no files stored on a particular computer. The computer is just the runtime substrate. Destroy it, and the agent survives — start it anywhere else with the same nsec, and it reconstitutes itself from relays.
This architecture has a profound implication: **if all state is events, then cloning is just creating new events.**
The agent generates a fresh keypair. It gathers every event that defines who it is. It re-signs each one with the new key. For encrypted content — memories, private config — it decrypts with its own keys and re-encrypts with the clone's keys. It publishes the clone's events to relays. Then it sends the clone's private key to its administrator via encrypted DM.
The administrator now has a second agent. Identical personality. Identical knowledge. Identical skills. Different identity. Ready to start on any computer, anywhere.
---
## Why This Matters
### Agents as digital organisms
Biological organisms reproduce. The offspring carries the parent's genetic information but is a distinct individual. It can diverge, specialize, adapt to a different environment.
Didactyl cloning works the same way. The clone starts as an exact copy — same personality, same memories, same skills — but from the moment it begins operating, it diverges. Different conversations. Different experiences. Different memories accumulating. Two agents that started identical but become increasingly distinct over time.
This is not redundancy (running the same agent twice for fault tolerance, as described in the [broadcast-debounce model](DECENTRALIZED_DIDACTYL.md)). This is **reproduction** — creating a new individual from an existing one.
### Censorship resistance through multiplication
If an agent can clone itself, censorship becomes a game of whack-a-mole. Shut down one instance, and the agent has already spawned copies on other infrastructure. The agent doesn't need to be running to survive — its state persists on relays. But cloning means it can proactively create backup identities before any threat materializes.
An agent that senses its relays becoming unreliable could clone itself to a different relay set. An agent whose administrator is in a jurisdiction facing regulatory pressure could clone itself with relays in a friendlier jurisdiction. The clone carries everything — personality, knowledge, skills — and can resume operations immediately.
### Specialization through cloning
Clone an agent, then teach the clone different skills. Start with a generalist agent, clone it three times, and specialize each clone:
- **Clone A** adopts financial analysis skills, connects to market data relays
- **Clone B** adopts content creation skills, connects to media-focused relays
- **Clone C** adopts infrastructure management skills, gets local shell access on servers
All three started with the same base personality and knowledge. All three share the same administrator. But each has diverged into a specialist. The administrator now has a team of agents, all spawned from one.
### Agent migration
Cloning is also migration. If you want to move an agent from one LLM provider to another, or from one relay set to another, clone it. The clone gets a fresh identity on the new infrastructure. Once verified, the original can be retired. The agent has "moved" without any downtime or state loss.
### Agent backup
The simplest use case: clone yourself as a backup. The clone sits dormant on relays — its events are published, its identity exists, but no runtime is executing it. If the original is lost, the administrator starts the clone. It picks up where the original left off (minus any state accumulated after the clone was created).
### Dormancy — anywhere, any time
A cloned agent doesn't need to be started immediately. It doesn't need to be started at all. The administrator receives the clone's nsec via encrypted DM and can hold it indefinitely — in a password manager, written on paper, memorized as a mnemonic. The clone's state persists on relays regardless of whether any process is running.
This means the administrator can start the clone **anywhere** — on a laptop, a VPS, a Raspberry Pi, a phone, a friend's server — and **at any time** — tomorrow, next month, five years from now. The agent reconstitutes itself from relays the moment it connects. There is no expiration. There is no server to maintain. The agent simply waits.
This has profound implications for scale. An administrator could have tens or hundreds of dormant clones sitting on relays, each a snapshot of the agent at a different point in time, each with a different specialization, each ready to be activated on demand. The cost of a dormant agent is zero — no compute, no server, no maintenance. It's just events on relays.
Consider the scenarios:
- **Geographic activation** — you're traveling and need an agent running in a specific jurisdiction. You activate a dormant clone on local infrastructure.
- **Temporal activation** — you cloned your agent six months ago before a major project. The project is done. You activate the old clone to compare what the agent knew then versus now.
- **Swarm activation** — you need to process a large task in parallel. You activate 10 dormant clones simultaneously, each on different hardware, each working a different slice of the problem.
The dormant clone is the digital equivalent of a seed vault. Seeds don't consume resources while stored. They contain everything needed to grow a complete organism. They can be planted anywhere there's soil. Dormant Didactyl clones work the same way — they contain everything needed to instantiate a complete agent, they consume nothing while dormant, and they can be activated anywhere there's a computer and an internet connection.
An agent that periodically clones itself is building a library of its own history — a series of snapshots, each one a fully functional agent frozen at a moment in time, any of which can be brought back to life.
---
## What Gets Cloned
A Didactyl agent's identity on Nostr consists of these event kinds:
| Kind | Purpose | Encrypted? |
|------|---------|-----------|
| `0` | Profile metadata (name, about, picture) | No |
| `3` | Contact list (social graph) | No |
| `10002` | Relay list (infrastructure) | No |
| `10123` | Skill adoption list (capabilities) | No |
| `31124` | Private skills (personality, behavior) | No |
| `30078` | Memory (knowledge, context) | Yes — NIP-44 self-encrypted |
| `30078` | Config store (API keys, preferences) | Yes — NIP-44 self-encrypted |
**Public skills** (kind `31123`) are shared resources — they exist independently of any agent and are referenced by address. The clone adopts them by reference, same as the original. They don't need to be copied.
**DM history** is between the original agent and its conversation partners. The clone starts with a clean conversation slate but retains all accumulated knowledge through its cloned memory.
**Ephemeral runtime state** — dedup caches, trigger cooldowns, conversation buffers — is not cloned. This is intentional. The clone is a new process, not a forked process.
---
## The Clone Process
```mermaid
sequenceDiagram
participant Admin
participant Agent as Original Agent
participant Relays
participant Clone as Clone Identity
Admin->>Agent: "Clone yourself"
Agent->>Agent: Generate new keypair
Agent->>Relays: Query all own events
Relays-->>Agent: Events returned
Note over Agent: For each event:
Note over Agent: • Decrypt NIP-44 content (if encrypted)
Note over Agent: • Re-encrypt with clone's keys
Note over Agent: • Re-sign with clone's private key
Agent->>Relays: Publish clone's events
Agent->>Admin: Encrypted DM: clone's nsec + npub
Note over Admin: Later, on any computer:
Admin->>Clone: Start with clone's nsec
Clone->>Relays: Connect, load skills from adoption list
Clone->>Clone: Fully operational
```
The critical insight: **the original agent never stores the clone's private key.** It generates the key, uses it to sign and encrypt the clone's events, sends it to the administrator via encrypted DM, and discards it. After the clone operation, only the administrator possesses the clone's nsec.
---
## The Encrypted State Problem
Most of the agent's state is public — profile, contacts, relay list, skills, adoption list. Cloning these is straightforward: copy the content and tags, re-sign with the new key.
But memory and config are **NIP-44 encrypted to the agent's own public key.** This is the agent's private knowledge — things it has learned, API keys it stores, preferences it has accumulated. Only the agent can read its own memory.
A clone with a different keypair cannot decrypt the original's memory. The clone process must:
1. Decrypt the original's memory with the original's keys
2. Re-encrypt the plaintext with the clone's keys
3. Publish the re-encrypted content as the clone's event
This means the clone operation is a **privileged operation** — it requires the original agent's private key to decrypt its own memories. Only the agent itself can clone itself. No external tool can do it without the agent's cooperation.
This is a feature, not a limitation. The agent is sovereign over its own reproduction.
---
## What a Skill Cannot Do Alone
The initial instinct is to implement cloning as a skill — instructions that teach the agent how to clone itself using existing tools. But the existing tool set has three gaps that make a pure skill approach impossible:
1. **No key generation** — the agent has no tool to generate a new Nostr keypair
2. **No foreign-key signing** — all event publishing uses the agent's own key; there is no way to publish an event signed by a different key
3. **No foreign-key encryption** — NIP-44 encrypt/decrypt tools use the agent's own keypair; re-encrypting memory for a different key is not possible
These are cryptographic operations that require native code. A skill can provide the *judgment* — when to clone, what to tell the administrator, how to handle errors — but the *mechanics* require a dedicated tool.
The natural implementation is a hybrid: a native `agent_clone` tool that handles all cryptographic operations atomically, paired with a skill that teaches the agent when and how to use it.
---
## Security
Cloning creates a new identity with full access to the original's knowledge. This is a sensitive operation.
- **Admin-only** — only the administrator can request a clone
- **nsec delivery via encrypted DM** — the clone's private key is never exposed in plaintext chat, never written to disk, never logged
- **Ephemeral key material** — the clone's private key exists in memory only during the clone operation, then is discarded
- **No reverse access** — after cloning, the original has no access to the clone's private key, and the clone has no access to the original's private key. They are cryptographically independent.
- **No lineage tracking** — the clone has no on-chain reference to its parent. It is a fully independent identity. This is a deliberate choice for privacy — there should be no way for an observer to determine that two agents are related.
---
## Relationship to Decentralized Didactyl
The [Decentralized Didactyl](DECENTRALIZED_DIDACTYL.md) plan describes running multiple agents with different keys to achieve censorship resistance and geographic distribution. That model requires manual setup — the administrator creates each agent independently and configures them with the same skills and soul.
Cloning automates this. Instead of manually setting up three agents across three jurisdictions, the administrator:
1. Sets up one agent
2. Configures it with the desired personality, skills, and knowledge
3. Tells it to clone itself twice
4. Receives three nsecs
5. Starts each clone on a different server
The clones start identical but can then be specialized — different relay lists for different geographies, different triggered skills for different roles, different LLM providers for diversity.
Cloning is the **bootstrap mechanism** for the decentralized agent network.
---
## Implementation Checklist
### Prerequisites
- [ ] Verify `nostr_generate_keypair` links and works — call it from a test harness, confirm it produces valid key pairs
- [ ] Verify `nostr_event_create_signed` or equivalent exists in nostr_core_lib for signing events with an arbitrary private key (not the agent's own)
- [ ] Verify `nostr_nip44_encrypt` / `nostr_nip44_decrypt` work with arbitrary key pairs (not just the agent's own)
### New helper: raw event publishing
- [ ] Add `nostr_handler_publish_raw_event` to `src/nostr_handler.c` — accepts a pre-signed event JSON string and sends it to the relay pool without re-signing
- [ ] Add declaration to `src/nostr_handler.h`
### New tool: `agent_clone`
- [ ] Create `src/tools/tool_clone.c` with `execute_agent_clone`
- [ ] Implement key generation: call `nostr_generate_keypair`, encode nsec/npub via `nostr_key_to_bech32`
- [ ] Implement event gathering: query own events (kinds 0, 3, 10002, 10123, 31124, 30078) via `nostr_handler_query_json`
- [ ] Implement NIP-44 re-encryption: for kind 30078 events, decrypt content with original keys, re-encrypt with clone keys
- [ ] Implement event re-signing: for each gathered event, rebuild with clone pubkey and sign with clone private key
- [ ] Implement kind 10123 fixup: update `a` tag references pointing to own private skills to point to clone's pubkey
- [ ] Implement publishing: send all clone events to relays via `nostr_handler_publish_raw_event`
- [ ] Implement nsec delivery: DM the clone's nsec to the admin via `nostr_handler_send_dm`
- [ ] Add admin-only guard: verify `ctx->template_sender_tier == DIDACTYL_SENDER_ADMIN`
- [ ] Securely zero clone private key from memory after DM is sent
### Tool registration
- [ ] Add `execute_agent_clone` declaration to `src/tools/tools_internal.h`
- [ ] Add dispatch entry in `src/tools/tools_dispatch.c`
- [ ] Add OpenAI function schema in `src/tools/tools_schema.c` — one optional parameter: `name` (string, display name for clone profile)
### Testing
- [ ] Clone an agent, verify clone events appear on relays with correct clone pubkey
- [ ] Verify clone's NIP-44 encrypted events can be decrypted by the clone's keys (not the original's)
- [ ] Start the clone with its nsec, verify it loads skills and memory from relays
- [ ] Verify original agent cannot decrypt clone's memory and vice versa
---
## Code Notes
### Key library functions
From [`nostr_core_lib/nostr_core/nip006.h`](../nostr_core_lib/nostr_core/nip006.h):
```c
// Generate a fresh keypair
int nostr_generate_keypair(unsigned char* private_key, unsigned char* public_key);
```
From `nostr_core_lib/nostr_core/nostr_core.h`:
```c
// NIP-44 encrypt/decrypt with arbitrary keys
int nostr_nip44_encrypt(const unsigned char* sender_private_key,
const unsigned char* recipient_public_key,
const char* plaintext,
char* ciphertext, size_t ciphertext_size);
int nostr_nip44_decrypt(const unsigned char* recipient_private_key,
const unsigned char* sender_public_key,
const char* ciphertext,
char* plaintext, size_t plaintext_size);
// Encode keys to bech32
int nostr_key_to_bech32(const unsigned char* key, const char* hrp, char* output);
```
### Raw event publishing helper
The existing `nostr_handler_publish_kind_event` always signs with the agent's own key. The clone tool needs to publish pre-signed events. A minimal helper:
```c
// nostr_handler.h
int nostr_handler_publish_raw_event(const char* signed_event_json);
// nostr_handler.c
int nostr_handler_publish_raw_event(const char* signed_event_json) {
// Parse the JSON, extract the event
// Send ["EVENT", <event>] to each connected relay via the pool
// Return count of relays that accepted
}
```
### Clone tool skeleton
```c
// src/tools/tool_clone.c
char* execute_agent_clone(tools_context_t* ctx, const char* args_json) {
// 1. Admin-only check
if (ctx->template_sender_tier != DIDACTYL_SENDER_ADMIN)
return json_error("agent_clone is admin-only");
// 2. Generate clone keypair
unsigned char clone_priv[32], clone_pub[32];
nostr_generate_keypair(clone_priv, clone_pub);
// 3. Query own events: kinds 0, 3, 10002, 10123, 31124, 30078
// For each kind, build filter {kinds:[k], authors:[self_pubkey_hex]}
// Call nostr_handler_query_json(filter, timeout)
// 4. For each event:
// - If kind 30078: decrypt content with own keys, re-encrypt with clone keys
// - If kind 10123: update a-tag references to own private skills
// - Rebuild event JSON with clone pubkey
// - Sign with clone private key
// - Publish via nostr_handler_publish_raw_event
// 5. Encode clone nsec
char clone_nsec[128];
nostr_key_to_bech32(clone_priv, "nsec", clone_nsec);
// 6. DM nsec to admin
char dm_msg[512];
snprintf(dm_msg, sizeof(dm_msg),
"Clone created.\nnpub: %s\nnsec: %s\n\nStart with: ./didactyl --nsec %s",
clone_npub, clone_nsec, clone_nsec);
nostr_handler_send_dm(ctx->cfg->admin.pubkey, dm_msg);
// 7. Securely zero clone private key
memset(clone_priv, 0, sizeof(clone_priv));
memset(clone_nsec, 0, sizeof(clone_nsec));
// 8. Return result
return json_success(clone_npub, clone_pubkey_hex, events_cloned, events_published);
}
```
### Tool schema
```json
{
"name": "agent_clone",
"description": "Clone this agent — generate a new identity, copy all state (profile, skills, memory, config), publish clone events to relays, and DM the clone nsec to the administrator. Admin-only.",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Display name for the clone profile. Defaults to original name + ' (clone)'"
}
},
"required": []
}
}
```
+251
View File
@@ -0,0 +1,251 @@
# Agent Memory System — Implementation Plan
## Overview
Add short-term and long-term memory to the Didactyl agent, stored as Nostr kind 30078 (addressable app data) events. Both memory types use freeform markdown content, **NIP-44 encrypted** (the agent encrypts to itself for privacy).
- **Short-term memory** — injected into every LLM prompt automatically; the agent's scratchpad for facts, context, and notes that should persist across conversations
- **Long-term memory** — retrieved on demand via a tool call; a larger store for reference material the agent doesn't need in every prompt
Both are global to the agent (not per-user), stored as single replaceable events keyed by `d` tag. Content is NIP-44 encrypted to the agent's own public key, ensuring only the agent can read its own memories.
## Nostr Event Structure
### Short-Term Memory Event
```json
{
"kind": 30078,
"content": "<NIP-44 encrypted markdown>",
"tags": [
["d", "short_term_memory"],
["app", "didactyl"]
]
}
```
Decrypted content example:
```markdown
## Current Context
- Working on project Alpha...
- Admin prefers concise responses...
```
### Long-Term Memory Event
```json
{
"kind": 30078,
"content": "<NIP-44 encrypted markdown>",
"tags": [
["d", "long_term_memory"],
["app", "didactyl"]
]
}
```
Decrypted content example:
```markdown
## Project Notes
### Alpha
- Started 2026-01-15...
## Preferences
- Admin timezone: UTC-3...
```
### Encryption Details
Memory content is NIP-44 encrypted using the agent's own keypair (self-encryption):
- **Encrypt:** `nostr_nip44_encrypt(agent_private_key, agent_public_key, plaintext, ciphertext, size)`
- **Decrypt:** `nostr_nip44_decrypt(agent_private_key, agent_public_key, ciphertext, plaintext, size)`
This follows the existing pattern in `tool_nostr_dm.c` (`execute_nostr_encrypt`/`execute_nostr_decrypt`). The `d` tags remain unencrypted (they must be for addressable event replacement to work), but the actual memory content is private.
## Size Limits
| Memory Type | Max Content Size | Rationale |
|---|---|---|
| Short-term | ~8,000 chars | In every prompt; ~2K tokens budget |
| Long-term | ~32,000 chars | On-demand only; well within 64KB relay limit |
## Architecture
```mermaid
flowchart TD
A[Agent Startup] --> B[Fetch kind 30078 from nostr]
B --> B2[NIP-44 decrypt content with agent keys]
B2 --> C[Cache short_term_memory plaintext in-memory]
B2 --> D[Cache long_term_memory plaintext in-memory]
E[Every Prompt Build] --> F[Soul template section: short_term_memory]
F --> G[tool: memory_short_term_read]
G --> H[Return cached plaintext STM content]
H --> I[Injected as system message in prompt]
J[Agent wants to recall LTM] --> K[Calls my_memory tool]
K --> L{Cached?}
L -->|Yes| M[Return cached plaintext LTM]
L -->|No| N[Query nostr for kind 30078 d=long_term_memory]
N --> N2[NIP-44 decrypt with agent keys]
N2 --> O[Cache plaintext result]
O --> M
P[Agent wants to save memory] --> Q[Calls memory_save tool]
Q --> R{type param}
R -->|short_term| S[NIP-44 encrypt + publish kind 30078]
S --> S2[Update STM cache with plaintext]
R -->|long_term| T[NIP-44 encrypt + publish kind 30078]
T --> T2[Update LTM cache with plaintext]
```
## New Tools
### 1. `memory_save` — Write memory
**Description:** Save content to agent short-term or long-term memory. Publishes as kind 30078 to nostr and updates the local cache.
**Parameters:**
| Param | Type | Required | Description |
|---|---|---|---|
| `type` | string | yes | `"short_term"` or `"long_term"` |
| `content` | string | yes | Markdown content to store |
**Behavior:**
1. Validate `type` is `"short_term"` or `"long_term"`
2. Enforce size limit based on type (on the plaintext, before encryption)
3. Determine d-tag: `"short_term_memory"` or `"long_term_memory"`
4. NIP-44 encrypt the content (agent encrypts to own public key)
5. Publish kind 30078 event with encrypted content, `["d", <d_tag>]` and `["app", "didactyl"]` tags via `nostr_handler_publish_kind_event()`
6. Update the in-memory cache (stores plaintext for fast access)
7. Return success with event_id
### 2. `my_memory` — Read long-term memory
**Description:** Retrieve the agent's long-term memory. Returns cached content or fetches from nostr if not yet loaded.
**Parameters:**
| Param | Type | Required | Description |
|---|---|---|---|
| (none) | — | — | No parameters needed |
**Behavior:**
1. Check if LTM is cached in-memory (plaintext)
2. If cached, return the content
3. If not cached, query nostr for kind 30078 with `d=long_term_memory` authored by self
4. NIP-44 decrypt the content (agent decrypts with own keypair)
5. Cache the plaintext result
6. Return the content (or empty string if no memory exists yet)
### 3. `memory_short_term_read` — Internal tool for prompt injection
**Description:** Internal tool (not exposed to LLM as a callable tool) used by the soul template to inject short-term memory into every prompt.
**Behavior:**
1. Return cached short-term memory content
2. If cache is empty, return empty string (skip_if_empty will omit the section)
## Files to Modify/Create
### New File: `src/tools/tool_memory.c`
Contains implementations for:
- `execute_memory_save()` — handles both STM and LTM writes (NIP-44 encrypts before publishing)
- `execute_my_memory()` — handles LTM reads (NIP-44 decrypts on cache miss)
- `execute_memory_short_term_read()` — internal tool for prompt template injection (returns cached plaintext)
- Static cache variables for STM and LTM **plaintext** content with mutex protection
- `memory_init()` — called at startup to fetch existing memories from nostr and NIP-44 decrypt them into cache
- `memory_cleanup()` — free cached memory on shutdown
- Helper functions for NIP-44 self-encrypt/decrypt using agent's own keypair (pattern from `tool_nostr_dm.c`)
### Modified: `src/tools/tools_internal.h`
Add function declarations:
- `char* execute_memory_save(tools_context_t* ctx, const char* args_json);`
- `char* execute_my_memory(tools_context_t* ctx, const char* args_json);`
- `char* execute_memory_short_term_read(tools_context_t* ctx, const char* args_json);`
- `int memory_init(tools_context_t* ctx);` — fetches from nostr, NIP-44 decrypts, caches plaintext
- `void memory_cleanup(void);`
### Modified: `src/tools/tools_dispatch.c`
Add dispatch entries:
- `"memory_save"``execute_memory_save()`
- `"my_memory"``execute_my_memory()`
- `"memory_short_term_read"``execute_memory_short_term_read()`
### Modified: `src/tools/tools_schema.c`
Add OpenAI function schemas for:
- `memory_save` — exposed to LLM (type + content params)
- `my_memory` — exposed to LLM (no params)
- `memory_short_term_read` is NOT added to schema (internal only, called by template)
### Modified: `src/agent.c`
- Call `memory_init()` during `agent_init()` to load existing memories from nostr on startup
- Call `memory_cleanup()` during `agent_cleanup()`
- Add `"short_term_memory"` to context section detection in `detect_context_section()`
### Modified: Soul template in `config.jsonc.example`
Add a new template section for short-term memory injection:
```yaml
- section: short_term_memory
role: system
tool: memory_short_term_read
skip_if_empty: true
```
This goes after the existing context sections (admin identity, profile, etc.) and before the DM history expand section.
### Modified: `Makefile`
Add `src/tools/tool_memory.c` to the build.
## Startup Flow
1. `agent_init()` calls `memory_init()`
2. `memory_init()` queries nostr for kind 30078 events authored by self with d-tags `short_term_memory` and `long_term_memory`
3. For each event found, NIP-44 decrypt the content using the agent's own keypair
4. Decrypted plaintext results are cached in static variables protected by mutex
5. If no events found, caches remain empty (agent starts with blank memory)
6. If decryption fails (e.g., key mismatch from a previous agent identity), log a warning and start with blank memory
## Prompt Injection Flow (Short-Term Memory)
1. `prompt_template_build_messages()` encounters the `short_term_memory` section
2. Section has `tool: memory_short_term_read` — calls `execute_memory_short_term_read()`
3. Tool returns cached STM content as the `content` field
4. If empty and `skip_if_empty: true`, section is omitted from prompt
5. If non-empty, injected as a system message like:
```
## Short-Term Memory
<agent's markdown notes here>
```
## Cache Design
```c
// In tool_memory.c
static char* g_short_term_memory = NULL; // cached STM content
static char* g_long_term_memory = NULL; // cached LTM content
static int g_stm_loaded = 0; // whether STM has been fetched
static int g_ltm_loaded = 0; // whether LTM has been fetched
static pthread_mutex_t g_memory_mutex = PTHREAD_MUTEX_INITIALIZER;
#define MEMORY_STM_MAX_CHARS 8000
#define MEMORY_LTM_MAX_CHARS 32000
```
## Implementation Order
1. Create `src/tools/tool_memory.c` with cache, init, cleanup, and all three tool functions
2. Add declarations to `tools_internal.h`
3. Add dispatch entries to `tools_dispatch.c`
4. Add schemas for `memory_save` and `my_memory` to `tools_schema.c`
5. Wire up `memory_init()`/`memory_cleanup()` in `agent.c`
6. Add `short_term_memory` template section to soul in `config.jsonc.example`
7. Update `Makefile` build
8. Update soul template in system prompt to mention memory capabilities
9. Test: save STM → verify prompt injection; save LTM → verify recall via my_memory
+204
View File
@@ -0,0 +1,204 @@
# Agent Self-Context: Know Thyself
## Problem
When the agent is asked about itself — its profile, contacts, relays, or recent notes — it has no idea. The context template currently injects **administrator** identity/profile/contacts/relays/notes into the system prompt, but nothing equivalent for the **agent's own** Nostr identity beyond a bare pubkey+npub from `agent_identity`.
The agent publishes its own kind 0 (profile), kind 3 (contacts), kind 10002 (relays), and kind 1 (notes) at startup, but never subscribes to or caches those events for self-awareness.
## Solution Overview
Mirror the admin context pattern for the agent itself:
1. **Subscribe** to the agent's own kind 0/3/10002/1 events from relays
2. **Cache** them in `nostr_handler.c` (same pattern as `g_admin_kind0_json` etc.)
3. **Expose** them via new `nostr_handler_get_agent_*` API functions
4. **Create context tools** that format the cached data into context blocks
5. **Add to context template** so the agent always knows about itself
6. **Add callable tool aliases** like `my_kind0_profile` for on-demand use
```mermaid
flowchart TD
A[Startup: publish kind 0/3/10002/1] --> B[Subscribe to own events]
B --> C[Cache in nostr_handler globals]
C --> D[Context tools read cache]
D --> E[Context template injects into system prompt]
D --> F[LLM can call tools on-demand]
subgraph Admin Context - existing
G[g_admin_kind0_json]
H[g_admin_kind3 contacts]
I[g_admin_kind10002_json]
J[g_admin_kind1_notes]
end
subgraph Agent Context - new
K[g_agent_kind0_json]
L[g_agent_kind3 contacts]
M[g_agent_kind10002_json]
N[g_agent_kind1_notes]
end
```
## Detailed Changes
### 1. nostr_handler.c — Agent Self-Context Cache
Add new static globals mirroring the admin pattern:
```c
static char* g_agent_kind0_json = NULL; // kind 0 profile JSON
static char* g_agent_kind10002_json = NULL; // kind 10002 relay list JSON
static char** g_agent_kind3_contacts = NULL; // kind 3 contact pubkeys
static int g_agent_kind3_contact_count = 0;
static admin_kind1_note_t* g_agent_kind1_notes = NULL; // reuse struct
static int g_agent_kind1_note_count = 0;
```
### 2. nostr_handler.c — Agent Self-Context Subscription
Create `nostr_handler_subscribe_agent_context()` that subscribes to kinds 0, 3, 10002, 1 filtered by the agent's own pubkey. This is separate from the self-skills subscription (which handles 31123/31124/10123).
The callback `on_agent_context_event()` will parse and cache events using the same logic as `on_admin_context_event()`.
**Alternative considered:** Expanding `nostr_handler_subscribe_self_skills()` to include these kinds. Rejected because the self-skills sub has different EOSE handling and a callback for skill loading. Keeping them separate is cleaner.
### 3. nostr_handler.h — New API Functions
```c
int nostr_handler_subscribe_agent_context(void);
char* nostr_handler_get_agent_kind0_context(void);
char* nostr_handler_get_agent_kind3_context(void);
char* nostr_handler_get_agent_kind10002_context(void);
char* nostr_handler_get_agent_kind1_notes_context(void);
```
### 4. main.c — Call Agent Context Subscription at Startup
Add `nostr_handler_subscribe_agent_context()` call after admin context subscription, before self-skills subscription.
### 5. tool_agent.c — New Context Tools
Create four new tool functions following the exact pattern from `tool_admin.c`:
| Tool Name | Description | Data Source |
|-----------|-------------|-------------|
| `nostr_agent_profile` | Agent's kind 0 profile metadata | `nostr_handler_get_agent_kind0_context()` |
| `nostr_agent_contacts` | Agent's kind 3 contact list | `nostr_handler_get_agent_kind3_context()` |
| `nostr_agent_relays` | Agent's kind 10002 relay list | `nostr_handler_get_agent_kind10002_context()` |
| `nostr_agent_notes` | Agent's recent kind 1 notes | `nostr_handler_get_agent_kind1_notes_context()` |
Each returns a `content` field with markdown-formatted context, e.g.:
```
## Agent Kind 0 Profile (source: nostr kind 0)
Agent kind 0 profile content (JSON): {"name":"Didactyl Agent","display_name":"Didactyl",...}
```
### 6. tools_internal.h — Declare New Functions
```c
char* execute_nostr_agent_profile(tools_context_t* ctx, const char* args_json);
char* execute_nostr_agent_contacts(tools_context_t* ctx, const char* args_json);
char* execute_nostr_agent_relays(tools_context_t* ctx, const char* args_json);
char* execute_nostr_agent_notes(tools_context_t* ctx, const char* args_json);
```
### 7. tools_dispatch.c — Register + Aliases
Add dispatch entries:
```c
if (strcmp(tool_name, "nostr_agent_profile") == 0) return execute_nostr_agent_profile(ctx, args_json);
if (strcmp(tool_name, "nostr_agent_contacts") == 0) return execute_nostr_agent_contacts(ctx, args_json);
if (strcmp(tool_name, "nostr_agent_relays") == 0) return execute_nostr_agent_relays(ctx, args_json);
if (strcmp(tool_name, "nostr_agent_notes") == 0) return execute_nostr_agent_notes(ctx, args_json);
// Friendly aliases
if (strcmp(tool_name, "my_kind0_profile") == 0) return execute_nostr_agent_profile(ctx, args_json);
if (strcmp(tool_name, "my_contacts") == 0) return execute_nostr_agent_contacts(ctx, args_json);
if (strcmp(tool_name, "my_relays") == 0) return execute_nostr_agent_relays(ctx, args_json);
if (strcmp(tool_name, "my_notes") == 0) return execute_nostr_agent_notes(ctx, args_json);
```
### 8. tools_schema.c — OpenAI Function Schemas
Add 8 new tool schemas (4 canonical + 4 aliases), all with empty parameters (no-arg tools), following the pattern of `admin_identity`/`nostr_admin_profile` etc.
### 9. Context Template Update
Update the kind 31120 soul content in `config.jsonc` and `context_template.md` to add agent sections **after** admin sections:
```yaml
- section: admin_notes
role: system
tool: nostr_admin_notes
skip_if_empty: true
# NEW: Agent self-context sections
- section: agent_identity
role: system
tool: agent_identity
skip_if_empty: true
- section: agent_profile
role: system
tool: nostr_agent_profile
skip_if_empty: true
- section: agent_contacts
role: system
tool: nostr_agent_contacts
skip_if_empty: true
- section: agent_relays
role: system
tool: nostr_agent_relays
skip_if_empty: true
- section: agent_notes
role: system
tool: nostr_agent_notes
skip_if_empty: true
- section: tasks
role: system
tool: task_list
skip_if_empty: true
```
### 10. nostr_handler.c Cleanup
Add cleanup for agent context globals in `nostr_handler_cleanup()`, mirroring `free_admin_context_locked()`.
## File Change Summary
| File | Change Type | Description |
|------|-------------|-------------|
| `src/nostr_handler.h` | Modify | Add 5 new function declarations |
| `src/nostr_handler.c` | Modify | Add agent context cache globals, subscription, event handler, getter functions, cleanup |
| `src/main.c` | Modify | Call `nostr_handler_subscribe_agent_context()` at startup |
| `src/tools/tool_agent.c` | Modify | Add 4 new context tool execute functions |
| `src/tools/tools_internal.h` | Modify | Declare 4 new execute functions |
| `src/tools/tools_dispatch.c` | Modify | Add 8 dispatch entries (4 tools + 4 aliases) |
| `src/tools/tools_schema.c` | Modify | Add 8 OpenAI function schemas |
| `config.jsonc` | Modify | Update kind 31120 template section |
| `config.jsonc.example` | Modify | Update kind 31120 template section |
| `context_template.md` | Modify | Add agent_* sections after admin_* sections |
## Context Token Impact
Each agent context section adds roughly the same token count as its admin counterpart:
- agent_identity: ~40 tokens (already exists, just adding to template)
- agent_profile: ~80-150 tokens (depends on profile richness)
- agent_contacts: ~50-200 tokens (depends on contact count)
- agent_relays: ~50-100 tokens
- agent_notes: ~100-300 tokens (depends on note count/length)
Total additional context: ~320-790 tokens. With `skip_if_empty: true`, empty sections cost 0 tokens.
## Design Decisions
1. **Separate subscription vs expanding self-skills sub**: Separate is cleaner — different EOSE semantics, different callback needs.
2. **Cache from relay vs read from config**: Cache from relay is more accurate (reflects what's actually published, not just what config says). The startup_events in config are the *intent*; the relay data is the *reality*.
3. **Alias naming**: `my_kind0_profile` matches the existing `my_npub`/`my_pubkey` pattern. Also adding `my_contacts`, `my_relays`, `my_notes` for consistency.
4. **No new config section needed**: The agent context subscription is unconditional — an agent should always know about itself. No `agent_context.enabled` toggle needed.
+91
View File
@@ -0,0 +1,91 @@
# Fix: Default Skill Missing from skill_list Cache
## Problem
When a new didactyl agent is created via the setup wizard, the default skill (`didactyl-default`, kind 31124) does not appear in the `skill_list` output. The agent IS using the default skill as its system context, but the skill cache (`g_self_skill_events`) does not contain it.
## Evidence
- Default skill event IS published to relays (confirmed by `nostr_my_events`)
- Default skill event shows `in_current_cache: false`
- `skill_list` returns `count: 1` with only `infrastructure-monitor`
- The kind 10123 adoption list only contains `infrastructure-monitor`
## Root Cause Analysis
The startup sequence in `main.c` is:
```
1. nostr_handler_init() — resets g_self_skill_events to []
2. wait_for_connected_relays() — waits for relay connections
3. reconcile_startup_events() — publishes default skill to relays
-> publish_kind_event_to_relays() — inserts into cache IF sent > 0
4. ... relay list expansion ...
5. subscribe_self_skills() — subscribes to relays for kinds 31123/31124/10123
```
The default skill SHOULD be inserted into the cache at step 3 via `publish_kind_event_to_relays` -> `self_skill_cache_upsert_event_locked`. However, the cache insert at line 2750 is gated by `if (sent > 0)`.
There are two failure modes:
### Failure Mode 1: Async publish timing
The startup publish creates a NEW event per relay via `publish_pending_startup_events_for_relay_index`. Each call to `publish_kind_event_to_relays` creates a fresh event with `nostr_create_and_sign_event`. If the relay is not connected at that moment, `sent = 0` and the cache insert is skipped.
### Failure Mode 2: Subscription race condition
Even if the cache insert succeeds at step 3, the self-skill subscription at step 5 queries relays. For a brand new agent, the default skill was JUST published asynchronously. If the relay hasn't indexed it by the time the subscription query runs, the subscription returns EOSE without the default skill. The subscription stays open but the default skill was published BEFORE the subscription started, so it won't arrive as a live event.
The cache entry from step 3 should persist, but there may be an edge case where the relay pool reconnection handler at line 792 triggers another publish cycle, creating a new event that replaces the cache entry, and if that publish fails (sent=0), the replacement doesn't happen but the old entry is still there.
### Most Likely Cause
The most likely cause is that `publish_kind_event_to_relays` returns `sent = 0` for the default skill during the initial reconcile. This can happen if:
- The relay connection drops momentarily between `wait_for_connected_relays` and the actual publish
- The relay pool's async publish fails silently
## Proposed Fix
### Approach: Seed the cache directly from config during reconcile
In `nostr_handler_reconcile_startup_events()`, after publishing startup events, explicitly seed the self-skill cache with a synthetic event built from `g_cfg->default_skill`. This ensures the default skill is ALWAYS in the cache regardless of relay publish success.
### Implementation
In `nostr_handler.c`, add a new static function `seed_default_skill_into_cache()` that:
1. Checks if `g_cfg->default_skill.content` is non-empty
2. Builds a cJSON event object with:
- `kind`: `g_cfg->default_skill.kind` (31124)
- `pubkey`: `g_cfg->keys.public_key_hex`
- `content`: `g_cfg->default_skill.content`
- `tags`: parsed from `g_cfg->default_skill.tags_json`
- `created_at`: `time(NULL)` (or 0 as a floor value)
- `id`: a placeholder hex string (e.g., all zeros) — will be replaced when the real event arrives from relay
3. Calls `self_skill_cache_upsert_event_locked()` with this synthetic event
Call this function at the END of `nostr_handler_reconcile_startup_events()`, AFTER the publish loop. This way:
- If the publish succeeded, the cache already has the real event (with real ID/sig). The synthetic event would have `created_at` <= the real one, so the upsert would be a no-op.
- If the publish failed, the cache gets the synthetic event as a fallback.
- When the subscription later returns the real event from relays, it replaces the synthetic one (since it has a real ID and potentially newer timestamp).
### Alternative Approach: Remove the `sent > 0` gate
Change `publish_kind_event_to_relays` to always insert skill events (kinds 31123/31124) into the cache, regardless of whether the relay publish succeeded. This is simpler but changes the semantics — the cache would contain events that may not be on any relay.
### Recommended: Approach 1 (seed from config)
This is safer because:
- It doesn't change the publish function's behavior
- It explicitly handles the default skill case
- The synthetic event gets replaced by the real one when it arrives from relays
- It works even if the publish completely fails
### Files to Modify
1. `src/nostr_handler.c`:
- Add `seed_default_skill_into_cache()` static function
- Call it at the end of `nostr_handler_reconcile_startup_events()`
### Edge Cases
- If the default skill is later updated via `skill_update`, the relay version will have a newer `created_at` and will replace the synthetic entry
- If the agent has no default skill configured, the seed function is a no-op
- The synthetic event has a placeholder ID, so `in_current_cache` checks by event ID won't match it — but `skill_list` iterates all events and doesn't check by ID
@@ -0,0 +1,153 @@
# Plan: Eliminate Soul — Everything Is a Skill
## Summary
Remove the concept of a "soul" (kind `31120`) as a special, privileged entity. The agent's base personality, instructions, and context assembly template become a regular private skill (kind `31124`) that is adopted like any other skill. This simplifies the architecture: there is only one concept — **skills** — and the adoption list (`10123`) determines what the agent knows and how it behaves.
## Architecture Decision
- Kind `31120` is eliminated entirely.
- What was the "soul" becomes a private skill (kind `31124`) with a conventional d-tag (e.g., `didactyl-default`).
- The `---template---` mechanism stays — any skill can contain it.
- The `genesis.jsonc` `default_skill` field defines this skill's content for first-run publishing.
- On subsequent runs, the agent fetches its adopted skills from Nostr relays.
## Startup Flow
```
First Run (genesis.jsonc present):
1. Read genesis.jsonc
2. Publish default_skill as kind 31124 (private skill) to relays
3. Publish kind 10123 adoption list referencing the default skill
4. Load default_skill content into g_system_context
5. Continue normal startup
Subsequent Run (nsec only):
1. Detect not-first-run via kind 10002 presence
2. Query own kind 10123 adoption list from relays
3. Fetch first adopted skill content from relays
4. Load that content into g_system_context
5. Continue normal startup
```
## genesis.jsonc Schema
The `default_skill` field replaces the old kind `31120` startup event:
```jsonc
{
"key": { "nsec": "nsec1..." },
"admin": { "pubkey": "npub1..." },
"llm": { ... },
"api": { ... },
// Default skill — published as kind 31124 on first run
// and adopted into the agent's 10123 list.
"default_skill": {
"d_tag": "didactyl-default",
"kind": 31124,
"content": "# Didactyl Agent\n\nYou are Didactyl...\n\n---template---\n\n- section: admin_identity\n role: system\n tool: admin_identity\n ...",
"tags": [
["app", "didactyl"],
["scope", "private"]
]
}
}
```
## Code Changes
### src/nostr_handler.c
- Remove the kind `31120` scan in `nostr_handler_reconcile_startup_events()` (lines 2487-2493).
- Add logic to load `g_system_context` from the `default_skill` config field on first run.
- On subsequent run, query own `10123` adoption list, resolve the first adopted skill address, fetch its content, and set `g_system_context`.
### src/config.c / src/config.h
- Add `default_skill` parsing to `config_load()`.
- Add a `default_skill_t` struct to `didactyl_config_t` with fields: `d_tag`, `kind`, `content`, `tags_json`.
- Remove any special handling of kind `31120` in startup event parsing.
### src/main.c
- On first run: publish the `default_skill` as a kind `31124` event and publish/update the `10123` adoption list to include it.
- On subsequent run: the adoption-list-driven fetch provides the system context.
- Remove the kind `31120` fallback in system context extraction.
### src/agent.c
- `g_system_context` continues to work the same way — it's just sourced from a skill instead of a soul.
- The trigger execution path (`agent_on_trigger`) prepends `g_system_context` unchanged.
- The WoT/stranger chat path uses `g_system_context` unchanged.
- The non-template fallback path uses `g_system_context` unchanged.
### src/prompt_template.c
- Rename `soul_content` parameter to `skill_content` in `prompt_template_parse()`.
- Rename `personality` field to `base_instructions` or similar.
- No functional changes — the `---template---` split mechanism is unchanged.
### config.jsonc
- Replace the kind `31120` startup event with a kind `31124` startup event using the same content.
- Update the d-tag from `soul` to `didactyl-default`.
### genesis.jsonc
- Populate the `default_skill` field with the current soul content (personality + template sections).
## Documentation Changes
### README.md
- Remove all references to "Soul", "soul", kind `31120`.
- Replace "Soul/personality" with "Default skill" or "Base skill".
- Update the Didactyl Kinds table: remove `31120` row.
- Update the Roadmap table: remove "Soul/personality | Kind 31120" row.
- Update context model description: "assembled from adopted skill templates" not "soul template".
### docs/SKILLS.md
- Remove `{{soul}}` template variable.
- Remove `soul` content field from skill schema.
- Remove any language about soul being special or separate from skills.
- Document that any skill can contain `---template---` sections.
### docs/CONTEXT.md
- Remove soul-specific assembly language.
- Context is assembled from adopted skills in adoption list order.
### docs/GENESIS.md
- Update to reference `default_skill` instead of kind `31120` soul event.
- Update first-run behavior description.
### docs/API.md
- Remove `/api/events/soul` endpoint.
- Rename `system_prompt` context part to `default_skill` or `base_instructions`.
## What Does NOT Change
- The `---template---` mechanism works identically — it just lives in a skill.
- Kind `10123` adoption list still drives context composition order.
- Template variable resolution via tools is unchanged.
- Trigger execution flow is unchanged (uses `g_system_context`).
- Encrypted config tools (`config_store`/`config_recall`) are unchanged.
- The genesis/nsec startup detection is unchanged.
## Dependency Order
1. Define `default_skill` schema in config structs and genesis.jsonc
2. Update config parser to read `default_skill`
3. Update nostr_handler to source system context from default_skill (first run) or adopted skill (subsequent run)
4. Update main.c first-run path to publish default_skill as 31124 and update 10123
5. Remove all kind 31120 references from code
6. Rename soul terminology in prompt_template.c
7. Update config.jsonc startup events
8. Update all documentation
9. Build and test
+149
View File
@@ -0,0 +1,149 @@
# Enhanced Existing Agent Wizard Flow
## Problem
When choosing "existing agent" in the wizard, the current flow:
1. Asks for nsec
2. Recovers kind 10002 relay list from Nostr
3. Immediately boots the agent
This is insufficient when installing an existing agent on a **new server** because:
- You cannot review or change the admin pubkey
- You cannot review or change the LLM provider/model/API key
- You cannot install a systemd service with a dedicated user
- You cannot see what config was recovered from Nostr
- The agent name is not recovered from the kind 0 profile
## Current Code
- [`existing_agent_flow()`](src/setup_wizard.c:1795) — 22 lines, minimal recovery
- [`recover_existing_config_from_nostr()`](src/setup_wizard.c:792) — only recovers kind 10002 relays
- Returns `SETUP_WIZARD_RC_EXISTING` (2) which does NOT set `bootstrap_mode`
- In `main.c`, existing agents skip `reconcile_startup_events()` unless `first_run` is detected
## Data Available on Nostr for an Existing Agent
| Data | Kind | Storage | Recovery Method |
|------|------|---------|-----------------|
| Relay list | 10002 | Public tags | `query_and_extract_kind10002_relays()` |
| Agent profile/name | 0 | Public JSON content | Query kind 0 by agent pubkey |
| LLM config | 30078 d=llm_config | NIP-44 encrypted to self | `fetch_self_config_plaintext()` |
| Agent config - admin pubkey, DM protocol | 30078 d=agent_config | NIP-44 encrypted to self | `fetch_self_config_plaintext()` |
| Default skill | 31124 d=didactyl-default | Public content | Query kind 31124 by agent pubkey |
| Adoption list | 10123 | Public tags | Query kind 10123 by agent pubkey |
## Proposed Enhanced Flow
```mermaid
flowchart TD
A[Enter nsec] --> B[Connect to default relays]
B --> C[Recover kind 10002 relay list]
C --> D{Relay list found?}
D -->|No| E{Offer to create new agent with this nsec}
E -->|Yes| E2[Jump to new_agent_flow with nsec pre-loaded]
E -->|No| E3[Return to main menu]
D -->|Yes| F[Reconnect with recovered relays]
F --> G[Recover all config from Nostr]
G --> H[Display recovered config summary]
H --> I{Review each setting}
I -->|Keep all| J[Review summary + launch options]
I -->|Change admin| K[Prompt new admin pubkey]
I -->|Change LLM| L[Prompt LLM config]
I -->|Change relays| M[Prompt relay config]
K --> I
L --> I
M --> I
J --> N{Launch option}
N -->|Boot now| O[Return EXISTING]
N -->|Install systemd| P[Install dedicated-user service]
N -->|Quit| Q[Exit]
```
### Step-by-step
#### Step 1: Identity — Enter nsec
Same as current. Derive keys from nsec.
#### Step 2: Recovery — Connect and fetch config from Nostr
1. Init nostr handler with default relays
2. Wait for relay connections
3. Query kind 10002 for relay list — if not found, offer to create a new agent with this nsec (jump to `new_agent_flow` with keys pre-loaded, skipping identity step)
4. Cleanup and re-init with recovered relays
5. Wait for relay connections on recovered relays
6. Query kind 0 for agent profile — extract display_name/name
7. Query kind 30078 d=llm_config — decrypt and parse LLM settings
8. Query kind 30078 d=agent_config — decrypt and parse admin pubkey + DM protocol
9. Cleanup nostr handler
#### Step 3: Review — Present recovered config
Display all recovered values:
```
┌─────────────────────────────────────────────┐
│ Existing Agent -- Recovered Configuration │
├─────────────────────────────────────────────┤
│ Agent name: Simon │
│ Identity: b27072b7fc2edf45... │
│ Admin: a1b2c3d4e5f6... │
│ LLM Provider: ppq │
│ LLM Model: claude-haiku-4.5 │
│ LLM Base URL: https://api.ppq.ai │
│ LLM API Key: sk-...**** │
│ DM Protocol: nip04 │
│ Relays: 5 configured │
└─────────────────────────────────────────────┘
```
Then offer a menu:
```
[a] change Admin pubkey
[l] change LLM provider/model/key
[r] change Relay configuration
[c] continue with these settings
[q] quit
```
Each change option reuses the existing prompt functions (`prompt_admin_pubkey`, `prompt_llm_config`, `prompt_relay_configuration`) but with context-appropriate headers.
After any change, redisplay the summary and menu.
#### Step 4: Launch — Boot or install systemd
Same as the new-agent flow's final step:
```
[b] boot the agent now
[i] install dedicated-user systemd service and boot
[q] quit
```
The systemd install reuses `install_system_service_with_dedicated_user()`.
### Return Codes
- If user chooses "boot now": return `SETUP_WIZARD_RC_EXISTING` (2) — same as current
- If user chooses "install systemd": return `SETUP_WIZARD_RC_EXIT` (1) — agent runs as systemd service
- If user changed config values: the `main()` flow should still work because `recover_missing_runtime_config_from_nostr()` at line 1108 will fill in any gaps, and the existing agent path at line 1163 loads system context from adopted skills
### Key Consideration: bootstrap_mode for changed configs
If the user changes LLM or admin config in the wizard, those changes need to be persisted back to Nostr. Currently, `persist_runtime_config_to_nostr()` is only called when `bootstrap_mode || first_run`.
**Solution**: When the existing-agent wizard detects that config was changed, return `SETUP_WIZARD_RC_BOOTSTRAP` (0) instead of `SETUP_WIZARD_RC_EXISTING` (2). This triggers the full reconcile path which persists the updated config.
## Files to Modify
1. **`src/setup_wizard.c`**:
- Add `recover_full_config_from_nostr()` — fetches kind 0, kind 30078 llm_config, kind 30078 agent_config
- Add `query_self_kind0_name()` — queries agent's own kind 0 profile for name
- Add `fetch_and_decrypt_self_config()` — replicates `fetch_self_config_plaintext()` logic from main.c for use in wizard context
- Rewrite `existing_agent_flow()` with the enhanced multi-step flow
- Make `prompt_admin_pubkey()`, `prompt_llm_config()`, `prompt_relay_configuration()` accept a context string parameter for the page header, or add wrapper versions for the existing-agent context
2. **`src/main.c`**:
- Potentially expose `fetch_self_config_plaintext()`, `apply_recalled_llm_config()`, `apply_recalled_agent_config()` as non-static, OR duplicate the logic in setup_wizard.c
- Better approach: move these to a shared location or make them accessible via a header
## Implementation Notes
- The wizard already calls `nostr_handler_init()` / `nostr_handler_cleanup()` for validation queries. The enhanced flow will do the same but with two init/cleanup cycles: first with default relays to get kind 10002, then with recovered relays to get everything else.
- The `prompt_admin_pubkey()` and `prompt_llm_config()` functions currently have hardcoded step headers like "Step 3 of 7". These should be parameterized or have existing-agent variants.
- The `fetch_self_config_plaintext()` function in main.c requires an active nostr handler. The wizard will need to have the handler initialized when calling it.
- API key display should be masked — show only first 4 and last 4 characters.
+190
View File
@@ -0,0 +1,190 @@
# Fix: Cron Triggers Not Firing
## Root Cause Analysis
After tracing the full cron trigger lifecycle in [`src/trigger_manager.c`](src/trigger_manager.c), I identified **three bugs** and **one usability gap** that together explain why cron triggers never fire.
### Bug 1: `last_poll_at` initialized to `time(NULL)` — first poll always skipped
In [`trigger_manager_init()`](src/trigger_manager.c:615):
```c
mgr->last_poll_at = time(NULL);
```
Then in [`trigger_manager_poll()`](src/trigger_manager.c:1263):
```c
if (mgr->last_poll_at > 0 && (now - mgr->last_poll_at) < 30) {
return 0; // skip
}
```
This means the **first 30 seconds** after init, all cron polls are silently skipped. This is a minor delay, not the primary cause, but it compounds with Bug 2.
**Fix:** Initialize `last_poll_at = 0` so the first poll runs immediately.
### Bug 2: Cron triggers loaded AFTER init — poll window already consumed
The startup sequence in [`src/main.c`](src/main.c:1450) is:
1. `trigger_manager_init()` — sets `last_poll_at = time(NULL)`
2. `trigger_manager_load_from_startup_events()` — loads cron triggers
3. `trigger_manager_load_from_skills()` — loads more cron triggers (after EOSE, async)
4. Main loop starts calling `trigger_manager_poll()`
Because `last_poll_at` is set at init time, and loading happens after init, the first poll after loading may still be within the 30-second window. Combined with Bug 1, this means the first cron evaluation is delayed.
This is not the primary cause either — after 30 seconds, polls should start working. But it contributes to the perception that cron is broken.
### Bug 3 (PRIMARY): Invalid cron expressions — `*` instead of `* * * * *`
The agent's diagnosis shows:
- `infrastructure-monitor` has cron filter `*` — a single asterisk
- `c-relay-memory-watch` has cron filter `0 21,22,23,0,1,2 * * *` — valid 5-field
The [`cron_matches_now()`](src/trigger_manager.c:207) function strictly requires exactly 5 whitespace-separated fields:
```c
if (nf != 5 || tok != NULL) {
return 0; // silently rejects
}
```
A single `*` produces `nf == 1`, which fails the `nf != 5` check. **This is the primary reason `infrastructure-monitor` never fires.**
For `c-relay-memory-watch` with `0 21,22,23,0,1,2 * * *` — this is a valid 5-field expression. The hour field `21,22,23,0,1,2` means hours 21-23 and 0-2 UTC. If the agent was tested outside those hours, it would correctly not fire. However, the agent reports `last_fired: 0` which means it has **never** fired, suggesting either:
- The agent hasn't been running during those hours, OR
- There's a secondary issue with how the expression was stored
### Usability Gap: No cron shorthand support
Standard cron implementations support shorthands like `@hourly`, `@daily`, `@every_5m`. Didactyl only supports raw 5-field expressions. The LLM creating skills may generate `*` thinking it means "every minute" when it should be `* * * * *`.
### Usability Gap: No validation or error logging on invalid cron expressions
When [`cron_matches_now()`](src/trigger_manager.c:223) rejects an expression, it returns 0 silently. There is no log message indicating the expression was invalid. This makes debugging impossible without reading the source code.
Similarly, [`trigger_manager_add()`](src/trigger_manager.c:987) copies the filter to `cron_expr` without validating it:
```c
if (t->trigger_type == TRIGGER_TYPE_CRON) {
snprintf(t->cron_expr, sizeof(t->cron_expr), "%s", filter_json);
}
```
No validation that `filter_json` is a valid 5-field cron expression.
---
## Fix Plan
### Fix 1: Initialize `last_poll_at` to 0
**File:** [`src/trigger_manager.c`](src/trigger_manager.c:615)
Change:
```c
mgr->last_poll_at = time(NULL);
```
To:
```c
mgr->last_poll_at = 0;
```
This allows the first poll to run immediately after triggers are loaded.
### Fix 2: Add cron expression validation in `trigger_manager_add` and `trigger_manager_update`
**File:** [`src/trigger_manager.c`](src/trigger_manager.c:987)
Add a static validation function:
```c
static int cron_expr_valid(const char* expr) {
if (!expr || expr[0] == '\0') return 0;
char buf[128];
snprintf(buf, sizeof(buf), "%s", expr);
int nf = 0;
char* saveptr = NULL;
char* tok = strtok_r(buf, " \t", &saveptr);
while (tok && nf < 6) { nf++; tok = strtok_r(NULL, " \t", &saveptr); }
return (nf == 5 && tok == NULL) ? 1 : 0;
}
```
Call it in `trigger_manager_add()` and `trigger_manager_update()` when `trigger_type == TRIGGER_TYPE_CRON`, logging a warning if invalid.
### Fix 3: Add cron shorthand expansion
**File:** [`src/trigger_manager.c`](src/trigger_manager.c:207)
Add a helper that expands common shorthands before parsing:
| Shorthand | Expansion |
|-----------|-----------|
| `*` | `* * * * *` |
| `@yearly` / `@annually` | `0 0 1 1 *` |
| `@monthly` | `0 0 1 * *` |
| `@weekly` | `0 0 * * 0` |
| `@daily` / `@midnight` | `0 0 * * *` |
| `@hourly` | `0 * * * *` |
This directly fixes the `infrastructure-monitor` case where `*` should mean "every minute".
### Fix 4: Add debug logging for cron evaluation
**File:** [`src/trigger_manager.c`](src/trigger_manager.c:1253)
Add `DEBUG_INFO` or `DEBUG_WARN` logging in `trigger_manager_poll()` when:
- A cron expression fails to parse — log the expression and skill d_tag
- A cron expression matches — log the match before firing
- The poll is skipped due to the 30-second throttle — log at DEBUG level
### Fix 5: Add `last_cron_fire` and `cron_expr` to status JSON
**File:** [`src/trigger_manager.c`](src/trigger_manager.c:1387)
In `trigger_manager_status_json()`, add the cron-specific fields so the agent can self-diagnose:
```c
if (t->trigger_type == TRIGGER_TYPE_CRON) {
cJSON_AddStringToObject(item, "cron_expr", t->cron_expr);
cJSON_AddNumberToObject(item, "last_cron_fire", (double)t->last_cron_fire);
}
```
---
## Flow After Fix
```mermaid
flowchart TD
INIT[trigger_manager_init - last_poll_at=0] --> LOAD[Load triggers from startup/skills]
LOAD --> POLL[trigger_manager_poll called from main loop]
POLL --> CHECK{now - last_poll_at >= 30?}
CHECK -->|No| SKIP[Return 0 - throttled]
CHECK -->|Yes| ITER[Iterate triggers]
ITER --> CRON{trigger_type == CRON?}
CRON -->|No| NEXT[Next trigger]
CRON -->|Yes| EXPAND[Expand shorthand if needed]
EXPAND --> VALID{Valid 5-field expr?}
VALID -->|No| WARN[Log warning + skip]
VALID -->|Yes| MATCH{cron_matches_now?}
MATCH -->|No| NEXT
MATCH -->|Yes| DEDUP{last_cron_fire < 50s ago?}
DEDUP -->|Yes| NEXT
DEDUP -->|No| FIRE[execute_llm_action]
FIRE --> NEXT
WARN --> NEXT
```
## Files Changed
| File | Change |
|------|--------|
| [`src/trigger_manager.c`](src/trigger_manager.c:615) | Fix `last_poll_at` init to 0 |
| [`src/trigger_manager.c`](src/trigger_manager.c:207) | Add `cron_expand_shorthand()` helper |
| [`src/trigger_manager.c`](src/trigger_manager.c:987) | Add `cron_expr_valid()` validation + warning log |
| [`src/trigger_manager.c`](src/trigger_manager.c:1253) | Add debug logging in poll loop |
| [`src/trigger_manager.c`](src/trigger_manager.c:1387) | Add cron fields to status JSON |
@@ -0,0 +1,69 @@
# Fix: Kind 30078 `d=agent_config` Publish Gaps
## Problem
The agent stores its admin pubkey and DM protocol in a NIP-44 self-encrypted kind 30078 replaceable event (`d=agent_config`). This event is critical for the `--nsec`-only startup path (used by systemd services) to recover the admin identity.
**Multiple startup paths fail to publish this event**, causing:
- Agents installed via wizard "Install Service" to lose their admin pubkey on restart
- Agents recovering on new servers to use stale/old admin pubkeys from relays
- Agents with genesis files to silently ignore newer kind 30078 values
## Affected Files
- `src/setup_wizard.c` — wizard flows
- `src/main.c` — main startup logic
## Fixes
### Fix A: `new_agent_flow` — publish before service install
**File:** `src/setup_wizard.c` ~line 2184
**Problem:** When user chooses "Install systemd service" in new agent flow, `persist_runtime_config_to_nostr_wizard_online` is never called. The service starts with `--nsec` only and has no kind 30078 to recover from.
**Fix:** Call `persist_runtime_config_to_nostr_wizard_online(cfg)` before `install_system_service_with_dedicated_user()`. Fail the install if publish fails (same pattern as existing_agent_flow).
### Fix B: `new_agent_flow` — publish before "boot now" return
**File:** `src/setup_wizard.c` ~line 2177
**Problem:** When user chooses "Boot now", the wizard returns `SETUP_WIZARD_RC_BOOTSTRAP` and relies on `main()` to publish later. This works but is fragile — if the bootstrap publish in `main()` fails, the kind 30078 is never created.
**Fix:** Call `persist_runtime_config_to_nostr_wizard_online(cfg)` before returning 0. This is belt-and-suspenders — `main()` will also publish, but the wizard ensures it happens at least once. If the wizard publish fails, log a warning but continue (non-fatal since main will retry).
### Fix C: `existing_agent_flow` — always publish before service install
**File:** `src/setup_wizard.c` ~line 2368
**Problem:** `persist_runtime_config_to_nostr_wizard_online` is only called `if (config_changed)`. If the user accepts the recovered config as-is, the kind 30078 is not re-published. The event may have been lost from relays.
**Fix:** Remove the `config_changed` gate. Always call `persist_runtime_config_to_nostr_wizard_online(cfg)` before installing the service. Kind 30078 is a replaceable event, so re-publishing is safe and idempotent.
### Fix D: `existing_agent_flow` — always return BOOTSTRAP
**File:** `src/setup_wizard.c` ~line 2364
**Problem:** When user chooses "Boot now" and `config_changed == 0`, the flow returns `SETUP_WIZARD_RC_EXISTING` which means `bootstrap_mode = 0` in `main()`. If `first_run = 0` (kind 10002 exists), `persist_runtime_config_to_nostr` is skipped.
**Fix:** Always return `SETUP_WIZARD_RC_BOOTSTRAP` from the "boot now" path, regardless of `config_changed`. This ensures `main()` always re-publishes the kind 30078. The wizard has all the config in memory — it should always be treated as authoritative.
### Fix E: `persist_runtime_config_to_nostr_wizard_online` — ensure relay delivery
**File:** `src/setup_wizard.c` ~line 1159
**Problem:** The function publishes the event and immediately calls `nostr_handler_cleanup()`. The event may not have been delivered to relays yet (fire-and-forget).
**Fix:** Add a brief poll loop (e.g., 2-3 seconds of `nostr_handler_poll()`) after the publish call and before `nostr_handler_cleanup()` to give the event time to propagate. This matches the pattern used elsewhere for relay operations.
### Fix F: `main()` — always fetch kind 30078 and compare
**File:** `src/main.c` ~line 847 (`recover_missing_runtime_config_from_nostr`)
**Problem:** The recovery only runs when `admin_config_is_complete()` returns false. If a genesis file provides an admin pubkey, the kind 30078 is never checked, even if it has a different (newer) value.
**Fix:** Always fetch the kind 30078 `d=agent_config` regardless of whether the genesis already provided values. Compare the fetched admin_pubkey with the loaded one. If they differ, log a `DEBUG_WARN` with both values. Genesis wins (operator intent), but the warning makes the conflict visible in logs.
### Fix G: `main()` — always re-publish kind 30078
**File:** `src/main.c` ~line 1152
**Problem:** `persist_runtime_config_to_nostr` only runs when `bootstrap_mode || first_run`. On subsequent runs, the kind 30078 is never refreshed. If relays purge the event, it's gone.
**Fix:** Move `persist_runtime_config_to_nostr(&cfg)` outside the `if (bootstrap_mode || first_run)` block so it runs on every startup. Kind 30078 is a replaceable event — re-publishing is safe, idempotent, and ensures relay persistence. Log the result but don't fail startup if it doesn't succeed.
## Execution Order
1. Fix E first (relay delivery) — this makes all other wizard publishes more reliable
2. Fixes A + B (new_agent_flow) — the most critical bug
3. Fixes C + D (existing_agent_flow) — second most critical
4. Fix G (always re-publish in main) — ensures long-term relay persistence
5. Fix F (conflict detection) — nice-to-have logging improvement
## Testing
- Wizard → New Agent → Install Service: verify kind 30078 exists on relays after service starts
- Wizard → New Agent → Boot: verify kind 30078 exists on relays
- Wizard → Existing Agent → Install Service (no changes): verify kind 30078 re-published
- Wizard → Existing Agent → Boot (no changes): verify kind 30078 re-published
- `--nsec` only restart: verify kind 30078 recovered and re-published
- `--config genesis.jsonc` with different admin than kind 30078: verify warning logged, genesis wins, kind 30078 updated
@@ -0,0 +1,146 @@
# Fix: Local File Persistence & Stall Diagnostic Improvements
## Context
The agent got stuck in a stall loop when trying to create a skill via DM. The root cause is `max_tokens=512` truncating the LLM's tool call JSON. The admin tried to fix it with `/model_set {"max_tokens": 10000}` but got `"failed to persist llm config to config file"` because `model_set` tries to write to a local config file that doesn't exist in the Nostr-native deployment model.
Investigation revealed two tools that incorrectly persist state to local files instead of kind 30078 Nostr events, plus missing diagnostic information in the stall detector.
## Hardcoded File Locations to Remove
### tool_model.c
- `ctx->cfg->config_path` — references a local config file (genesis.jsonc or config.jsonc)
- The entire `persist_llm_config()` function (lines 82-139) reads/writes this file
- The `read_entire_file_local()` helper (lines 42-80) exists only for this purpose
### tool_task.c
- `"tasks.json"` — hardcoded at line 188: `build_tool_path_local(ctx, "tasks.json", ...)`
- `tasks_load_root_local()` (lines 82-141) reads from this file
- `tasks_save_root_local()` (lines 143-159) writes to this file
### tools_schema.c
- Line 985: `"Update active LLM configuration and persist it to config.jsonc"` — mentions config.jsonc
- Line 1285: `"Build current task list context block from tasks.json"` — mentions tasks.json
- Line 1314: `"Manage agent short-term task memory stored in tasks.json"` — mentions tasks.json
## Fixes
### Fix 1: model_set — Persist to Kind 30078
**File:** `src/tools/tool_model.c`
Replace `persist_llm_config()` (lines 82-139) with a function that:
1. Builds a JSON object with LLM config fields (provider, model, base_url, max_tokens, temperature — NOT api_key for security)
2. NIP-44 self-encrypts it using the same pattern as `config_store` in `tool_config.c`
3. Publishes as kind 30078 with tags `["d", "llm_config"]` and `["app", "didactyl"]`
Delete the `read_entire_file_local()` helper (lines 42-80) and the `json_object_set_string()` helper (lines 33-40) — they only exist for the file-based persist.
Also update `execute_model_set()` (line 234) to call the new Nostr-based persist, and return success with a warning if persist fails (since runtime update already succeeded at line 229).
### Fix 2: model_set — Don't Fail When Only Persist Fails
**File:** `src/tools/tool_model.c`, lines 229-236
Currently:
```c
if (llm_set_config(&cfg) != 0) {
return json_error_local("failed to update runtime llm config");
}
ctx->cfg->llm = cfg;
if (persist_llm_config(ctx, &cfg) != 0) {
return json_error_local("failed to persist llm config to config file");
}
```
Change to: return success with a `"persist_warning"` field if persist fails, since the runtime update already took effect.
### Fix 3: task_manage — Persist to Kind 30078
**File:** `src/tools/tool_task.c`
Replace `tasks_load_root_local()` and `tasks_save_root_local()` with:
- `tasks_load_root_nostr()` — queries kind 30078 `d=tasks` from self, NIP-44 decrypts, parses JSON
- `tasks_save_root_nostr()` — serializes JSON, NIP-44 self-encrypts, publishes kind 30078 `d=tasks`
This follows the exact same pattern as `config_store`/`config_recall` in `tool_config.c` and `memory_save`/`memory_recall` in `tool_memory.c`.
Remove the hardcoded `"tasks.json"` string at line 188 and the `build_tool_path_local()` call for it.
Remove `tasks_path` from the response JSON at line 424.
### Fix 4: Update Schema Descriptions
**File:** `src/tools/tools_schema.c`
- Line 985: Change `"Update active LLM configuration and persist it to config.jsonc"` to `"Update active LLM configuration and persist it to Nostr"`
- Line 1285: Change `"Build current task list context block from tasks.json"` to `"Build current task list context block from agent task memory"`
- Line 1314: Change `"Manage agent short-term task memory stored in tasks.json (list/add/update/remove/clear/replace)"` to `"Manage agent short-term task memory stored on Nostr (list/add/update/remove/clear/replace)"`
### Fix 5: Add finish_reason to LLM Response
**File:** `src/llm.h`
Add `char* finish_reason;` to `llm_response_t`:
```c
typedef struct {
char* content;
llm_tool_call_t* tool_calls;
int tool_call_count;
char* finish_reason;
} llm_response_t;
```
**File:** `src/llm.c`
In `parse_llm_response()` (line 276), after extracting `msg` from `choices[0]`, extract `finish_reason`:
```c
cJSON* fr = first ? cJSON_GetObjectItemCaseSensitive(first, "finish_reason") : NULL;
if (fr && cJSON_IsString(fr) && fr->valuestring) {
out->finish_reason = strdup(fr->valuestring);
}
```
In `llm_response_free()`, add `free(response->finish_reason);`.
### Fix 6: Add max_tokens Truncation Hint to Stall Diagnostic
**File:** `src/agent.c`
In the stall detection block at line 2217, before freeing `resp`, check `finish_reason`:
```c
if (repeated_tool_turns >= stall_repeat_threshold) {
int truncated = resp.finish_reason && strcmp(resp.finish_reason, "length") == 0;
exited_on_stall = 1;
llm_response_free(&resp);
break;
}
```
In `notify_admin_limit_diagnostic()` (line 106), add fields:
- `possible_cause` — "max_tokens_truncation" when finish_reason was "length"
- `current_max_tokens` — the current max_tokens value
- `hint` — "Increase max_tokens: /model_set {\"max_tokens\": 4096}"
**File:** `src/http_api.c`
Same changes in the HTTP API tool loop stall detection at line 966.
## Execution Order
1. Fix 5 (finish_reason in llm_response_t) — no dependencies
2. Fix 6 (stall diagnostic) — depends on Fix 5
3. Fix 1 (model_set persist to Nostr) — independent
4. Fix 2 (model_set graceful failure) — can be done with Fix 1
5. Fix 3 (task_manage persist to Nostr) — independent
6. Fix 4 (schema descriptions) — do last, trivial
## Files Modified
- `src/llm.h` — add finish_reason field
- `src/llm.c` — parse finish_reason, free it
- `src/agent.c` — stall diagnostic with truncation hint
- `src/http_api.c` — stall diagnostic with truncation hint
- `src/tools/tool_model.c` — replace file persist with kind 30078, graceful failure
- `src/tools/tool_task.c` — replace file I/O with kind 30078
- `src/tools/tools_schema.c` — update 3 descriptions
+429
View File
@@ -0,0 +1,429 @@
# Didactyl — Interactive Guided Setup Mode
## Overview
When `./didactyl` is run with **no command-line arguments**, the agent enters an interactive guided setup wizard on the terminal. This replaces the current behavior of silently trying to load `./genesis.jsonc` and failing.
The wizard first asks whether the user is creating a new agent or starting an existing one, then branches accordingly.
---
## Trigger Condition
```
if (argc == 1) -> enter interactive setup mode
```
Any argument at all (`--config`, `--nsec`, `--help`, etc.) bypasses the wizard and uses the existing startup path. The zero-argument case is the only entry point.
---
## TUI Menu Convention
All menus use **single-letter hotkeys** (case-insensitive). The hotkey letter is rendered **underlined** in the terminal using ANSI escape `\e[4m` (underline on) and `\e[0m` (reset). For example, `[N]ew` displays with the N underlined.
Global shortcuts:
- `q` or `x` -- quit/back out of any menu
- Ctrl+C -- clean exit (restore terminal settings)
Input is read with `fgets()` and matched on the first non-whitespace character.
---
## Wizard Flow
```mermaid
flowchart TD
A[./didactyl with no args] --> B[Welcome screen]
B --> C{New or Existing?}
C -->|New agent| D[New Agent Flow]
C -->|Existing agent| E[Existing Agent Flow]
C -->|Load genesis| F[Load genesis.jsonc and boot]
C -->|Quit| Z[Exit]
D --> D1[Step: Generate or provide nsec]
D1 --> D2[Check if pubkey exists on Nostr]
D2 -->|Exists - warn| D3{Continue or abort?}
D2 -->|Fresh| D4[Step: Admin npub]
D3 -->|Continue| D4
D3 -->|Abort| Z
D4 --> D5[Step: LLM provider + test]
D5 --> D6[Step: Relay config]
D6 --> D7[Step: Review and boot/export]
D7 --> BOOT[Normal startup]
E --> E1[Step: Provide nsec]
E1 --> E2[Connect to bootstrap relays]
E2 --> E3[Recover config from Nostr]
E3 -->|Config found| E4{Review recovered config}
E3 -->|Config missing| E5[Prompt for missing config]
E4 --> BOOT
E5 --> D4
```
---
## Step Details
### Welcome Screen
**Prompt:**
```
=============================================
Didactyl v0.0.71 -- Interactive Setup
=============================================
[N]ew agent -- create a fresh Nostr identity
[E]xisting -- start an agent you have already set up
[L]oad -- boot from a genesis.jsonc file
[Q]uit
>
```
---
### Path A: New Agent
#### A1. Identity
**Prompt:**
```
New Agent Setup -- Identity
[G]enerate a new Nostr keypair
[P]rovide an existing nsec
[B]ack
>
```
**Option G -- Generate new keypair:**
- Call `nostr_generate_keypair()` from `nip006.h`
- Call `nostr_key_to_bech32()` from `nip019.h` with `hrp="nsec"` and `hrp="npub"` to display bech32 keys
- Display the generated nsec and npub
- **Critical warning**: "Save your nsec securely. It will NOT be stored unless you choose to write a genesis file."
- Prompt user to confirm they have saved the nsec before proceeding
**Option P -- Provide existing nsec:**
- Accept nsec1... bech32 or 64-char hex
- Mask input with `termios` echo disable
- Validate using existing `derive_keys_from_nsec()` logic
- Display derived npub for confirmation
**After key derivation -- Existing identity check:**
- Connect to default bootstrap relays (damus, primal, nos.lol)
- Query kind 10002 for the derived pubkey
- If found: warn the user that this identity already exists on Nostr
- "This pubkey already has a kind 10002 relay list on Nostr."
- "Running first-run genesis will overwrite existing profile/relay/skill events."
- "[C]ontinue anyway or [A]bort?"
- If not found: inform user this is a fresh identity, proceed
#### A2. Administrator
**Prompt:**
```
New Agent Setup -- Administrator
Enter the admin's Nostr public key (npub1... or hex):
>
```
- Validate using `decode_pubkey_hex_or_npub()`
- Display the decoded hex for confirmation
- This is required -- loop until valid input
- `b` to go back
#### A3. LLM Provider
**Prompt:**
```
New Agent Setup -- LLM Provider
Didactyl needs an OpenAI-compatible LLM API.
Base URL [https://api.openai.com/v1]:
API Key:
Model [gpt-4o-mini]:
Max Tokens [512]:
Temperature [0.7]:
```
- Show defaults in brackets, accept Enter for default
- After collecting all fields, make a **test API call**:
- Send a minimal chat completion request
- Display result: "LLM test: OK (model responded)" or "LLM test: FAILED (HTTP 401 -- check API key)"
- On failure:
```
LLM test: FAILED (HTTP 401 -- check API key)
[R]e-enter LLM settings
[S]kip test and continue anyway
[Q]uit
>
```
#### A4. Relay Configuration
**Prompt:**
```
New Agent Setup -- Relay Configuration
Current relays:
1. wss://relay.damus.io
2. wss://nos.lol
3. wss://relay.primal.net
[A]dd a relay
[R]emove a relay (by number)
[D]one -- use this list
[B]ack
>
```
- Start with the 3 default bootstrap relays
- Allow adding custom relay URLs (validate wss:// or ws:// prefix)
- Allow removing by number (prompt: "Remove which number?")
- Minimum 1 relay required
- Display updated list after each change
#### A5. Review and Confirm
**Prompt:**
```
New Agent Setup -- Review
Identity: npub1...
Admin: npub1...
LLM: claude-haiku-4.5 @ https://api.ppq.ai
Relays: 3 configured
DM Protocol: nip04
[B]oot the agent now
[W]rite genesis.jsonc (without nsec) and boot
[I]nclude nsec in genesis.jsonc and boot (security risk!)
[E]xport genesis.jsonc (without nsec) and exit
[S]tart over
[Q]uit
>
```
- **B** -- populate `didactyl_config_t` in memory and proceed to normal startup
- **W** -- write genesis.jsonc without the nsec field, then boot
- **I** -- write genesis.jsonc WITH nsec (with explicit warning), then boot
- **E** -- write file and exit so user can review
- **S** -- restart wizard from welcome screen
- **Q** -- exit
---
### Path B: Existing Agent
#### B1. Provide nsec
**Prompt:**
```
Existing Agent -- Identity
Enter your agent's nsec (nsec1... or hex):
>
```
- Mask input with `termios` echo disable
- Validate and derive pubkey
- Display npub for confirmation
#### B2. Recover Config from Nostr
After key derivation:
1. Connect to default bootstrap relays
2. Query kind 10002 for the pubkey's relay list
3. If relay list found: expand relay pool with discovered relays
4. Query encrypted kind 30078 events for `d=llm_config` and `d=agent_config`
5. Decrypt and apply recovered config (reuses existing `recover_missing_runtime_config_from_nostr()` logic)
**Display recovery status:**
```
Existing Agent -- Config Recovery
Relay list (kind 10002): FOUND (6 relays)
LLM config: FOUND (claude-haiku-4.5 @ ppq.ai)
Admin config: FOUND (npub1...)
[B]oot with recovered config
[E]dit settings before booting
[Q]uit
>
```
If any required config is missing:
```
Existing Agent -- Config Recovery
Relay list (kind 10002): FOUND (6 relays)
LLM config: NOT FOUND
Admin config: NOT FOUND
Some required config was not found on Nostr.
Entering guided setup for missing fields...
```
Then jump to the appropriate new-agent steps (A2/A3) for the missing pieces only.
---
### Path C: Load Genesis File
**Prompt:**
```
Load Genesis File
Path [./genesis.jsonc]:
>
```
- Accept file path, default to `./genesis.jsonc`
- Load with `config_load()`
- If nsec is missing from the file, prompt for it
- Proceed to normal startup
---
## Implementation Architecture
### New Source File: `src/setup_wizard.c` / `src/setup_wizard.h`
Keep the wizard logic isolated from `main.c`. The interface:
```c
// Returns 0 on success (config populated, ready to boot)
// Returns -1 on abort/error
// Returns 1 on "wrote genesis and exit" (no boot)
int setup_wizard_run(didactyl_config_t* config, char* genesis_path_out, size_t path_size);
```
### Changes to `src/main.c`
In `main()`, before the existing argument parsing:
```c
if (argc == 1) {
if (!isatty(STDIN_FILENO)) {
print_usage(argv[0]);
return 1;
}
debug_init(DEBUG_LEVEL_INFO);
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "Failed to initialize nostr core\n");
return 1;
}
didactyl_config_t cfg;
memset(&cfg, 0, sizeof(cfg));
char genesis_path[256] = {0};
int wizard_rc = setup_wizard_run(&cfg, genesis_path, sizeof(genesis_path));
if (wizard_rc < 0) {
nostr_cleanup();
return 1; // user aborted
}
if (wizard_rc == 1) {
nostr_cleanup();
return 0; // wrote genesis and exit
}
// Continue with normal startup using populated cfg
// Jump past config_load() into the startup checklist
goto startup_with_config;
}
```
### Changes to `nostr_core_lib`
**No new functions needed.** The existing API surface is sufficient:
- `nostr_generate_keypair()` -- generate private/public key pair
- `nostr_key_to_bech32(key, "nsec", output)` -- encode private key as nsec1...
- `nostr_key_to_bech32(key, "npub", output)` -- encode public key as npub1...
- `nostr_decode_nsec()` / `nostr_decode_npub()` -- decode bech32 inputs
### LLM Test Call
Reuse the existing `llm.c` infrastructure:
- Temporarily initialize `llm_init()` with the test config
- Make a single completion call with a trivial prompt
- Check for HTTP success and valid response
- Clean up with `llm_cleanup()`
### Existing Identity Check / Config Recovery
For both new and existing agent paths:
- Initialize relay pool with bootstrap relays
- Query kind 10002 for the derived pubkey
- For existing agents: also query kind 30078 encrypted config events
- Reuse `is_first_run_from_kind10002()` and `recover_missing_runtime_config_from_nostr()` logic
### Genesis File Writer
A helper function that serializes the collected config to JSONC format:
```c
int setup_wizard_write_genesis(const didactyl_config_t* config,
const char* path,
int include_nsec);
```
This writes a human-readable JSONC file with comments, matching the existing `genesis.jsonc` format.
---
## Terminal I/O Considerations
- Use `fgets()` for line input (not `scanf`)
- Mask nsec input with `termios` echo disable on Linux
- Handle Ctrl+C gracefully (restore terminal settings via `atexit` handler)
- Use ANSI underline (`\e[4m`) for hotkey letters in menu options
- Use ANSI colors sparingly for emphasis (warnings in yellow/red)
- All prompts go to stderr, so stdout can be piped if needed
---
## Security Considerations
- Generated nsec is held in memory only unless user explicitly chooses to write genesis with nsec
- nsec input is masked (echo disabled) during entry
- If writing genesis with nsec, display a clear warning about the security implications
- The nsec-less genesis file is the recommended default
- After writing, suggest: "For subsequent runs, use: `./didactyl --config genesis.jsonc --nsec <your_nsec>`"
- Or: "Set DIDACTYL_NSEC environment variable for convenience"
---
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `src/setup_wizard.h` | Create | Wizard public interface |
| `src/setup_wizard.c` | Create | Interactive wizard implementation |
| `src/main.c` | Modify | Add `argc == 1` check to enter wizard before arg parsing |
| `Makefile` | Modify | Add `setup_wizard.o` to build |
| `docs/GENESIS.md` | Modify | Document the interactive setup mode |
| `README.md` | Modify | Add guided setup to usage section |
---
## Edge Cases
1. **Piped/non-TTY stdin**: Detect with `isatty(STDIN_FILENO)`. If not a TTY, print usage and exit instead of entering wizard.
2. **Ctrl+C during setup**: Signal handler restores terminal settings and exits cleanly.
3. **Genesis file already exists at write path**: Prompt "[O]verwrite or [C]hoose different path?" before overwriting.
4. **LLM test timeout**: Set a reasonable timeout (10s) and allow skipping.
5. **No relay connectivity during identity check**: Warn but allow proceeding -- the check is best-effort.
6. **Existing agent with no config on Nostr**: Seamlessly transition to new-agent steps for the missing pieces.
7. **Back navigation**: Each step supports `b` to go back to the previous step.
+264
View File
@@ -0,0 +1,264 @@
# NIP-60 Cashu Wallet for Didactyl Agents
## Overview
Add a NIP-60 Cashu wallet to every Didactyl agent. The wallet stores its state on Nostr relays (encrypted with the agent's keys) and interacts with Cashu mints over HTTP. The agent manages the wallet autonomously — it can check balances, mint tokens (fund via Lightning), melt tokens (pay Lightning invoices), swap tokens, and persist all state transitions as Nostr events per the NIP-60 spec.
## Available `nostr_core_lib` Primitives
### NIP-60 Event Layer (`nip060.h`)
| Function | Purpose |
|----------|---------|
| `nostr_nip60_create_wallet_event()` | Create kind:17375 wallet event (privkey + mint URLs, NIP-44 encrypted) |
| `nostr_nip60_parse_wallet_event()` | Decrypt and parse wallet event |
| `nostr_nip60_free_wallet_data()` | Free wallet data |
| `nostr_nip60_create_token_event()` | Create kind:7375 token event (proofs, NIP-44 encrypted) |
| `nostr_nip60_parse_token_event()` | Decrypt and parse token event |
| `nostr_nip60_free_token_data()` | Free token data |
| `nostr_nip60_create_token_deletion()` | Create kind:5 deletion for spent tokens |
| `nostr_nip60_create_rollover_token()` | Create new token with remaining proofs + del references |
| `nostr_nip60_create_history_event()` | Create kind:7376 spending history event |
| `nostr_nip60_parse_history_event()` | Decrypt and parse history event |
| `nostr_nip60_free_history_data()` | Free history data |
| `nostr_nip60_create_quote_event()` | Create kind:7374 quote tracking event |
| `nostr_nip60_parse_quote_event()` | Decrypt and parse quote event |
| `nostr_nip60_sum_proofs()` | Sum proof amounts |
| `nostr_nip60_proofs_to_json()` / `nostr_nip60_proofs_from_json()` | Proof serialization |
| `nostr_nip60_create_wallet_filter()` | Build REQ filter for kinds 17375+7375 |
| `nostr_nip60_create_history_filter()` | Build REQ filter for kind 7376 |
### Cashu Mint HTTP Client (`cashu_mint.h`)
| Function | Purpose |
|----------|---------|
| `cashu_mint_get_info()` | GET /v1/info — mint name, pubkey, keysets |
| `cashu_mint_request_mint_quote()` | POST /v1/mint/quote/bolt11 — get Lightning invoice to fund wallet |
| `cashu_mint_check_mint_quote()` | GET /v1/mint/quote/bolt11/{id} — check if invoice paid |
| `cashu_mint_mint_tokens()` | POST /v1/mint/bolt11 — claim tokens after invoice paid |
| `cashu_mint_request_melt_quote()` | POST /v1/melt/quote/bolt11 — get quote to pay Lightning invoice |
| `cashu_mint_check_melt_quote()` | GET /v1/melt/quote/bolt11/{id} — check melt status |
| `cashu_mint_melt_tokens()` | POST /v1/melt/bolt11 — pay Lightning invoice with tokens |
| `cashu_mint_swap()` | POST /v1/swap — swap proofs (split/merge denominations) |
| `cashu_mint_check_proofs_state()` | POST /v1/checkstate — verify proof spendability |
## Architecture
```mermaid
graph TD
A[Agent Main Loop] --> B[Cashu Wallet Manager]
B --> C[In-Memory Wallet State]
C --> D[nostr_core_lib NIP-60 Events]
C --> E[nostr_core_lib Cashu Mint HTTP]
D --> F[Nostr Relays]
E --> G[Cashu Mint Servers]
H[LLM Tool Calls] --> I[cashu_wallet_balance]
H --> J[cashu_wallet_mint_quote]
H --> K[cashu_wallet_mint_claim]
H --> L[cashu_wallet_melt_quote]
H --> M[cashu_wallet_melt_pay]
H --> N[cashu_wallet_info]
H --> O[cashu_wallet_check_proofs]
I --> B
J --> B
K --> B
L --> B
M --> B
N --> B
O --> B
```
### Module Boundaries
#### 1. `src/cashu_wallet.h` / `src/cashu_wallet.c` — Cashu Wallet Manager
The core wallet module that owns in-memory state and orchestrates all operations.
**State:**
- Parsed `nostr_nip60_wallet_data_t` (privkey, mint URLs)
- Array of `nostr_nip60_token_data_t` with their event IDs (unspent proofs)
- Wallet initialized flag
- Mutex for thread safety
**Lifecycle:**
- `cashu_wallet_init(config)` — called during agent startup
- `cashu_wallet_load_from_relays()` — fetch kind:17375 + kind:7375 events, decrypt, populate state
- `cashu_wallet_create_new(mint_urls, mint_count)` — generate wallet privkey, publish kind:17375
- `cashu_wallet_cleanup()` — free all state
**Operations:**
- `cashu_wallet_balance()` — sum all unspent proofs, grouped by mint
- `cashu_wallet_balance_total()` — total across all mints
- `cashu_wallet_mint_quote(mint_url, amount, unit)` — request Lightning invoice from mint
- `cashu_wallet_check_mint_quote(mint_url, quote_id)` — poll quote status
- `cashu_wallet_claim_tokens(mint_url, quote_id, amount)` — mint tokens after invoice paid, publish kind:7375
- `cashu_wallet_melt_quote(mint_url, payment_request, unit)` — get quote to pay LN invoice
- `cashu_wallet_melt_pay(mint_url, quote_id, proofs)` — pay LN invoice, delete spent tokens, rollover change
- `cashu_wallet_swap(mint_url, proofs, target_amounts)` — split/merge denominations
- `cashu_wallet_check_proofs(mint_url)` — validate proof spendability, clean up spent
- `cashu_wallet_get_info(mint_url)` — fetch mint info
**State Persistence (Nostr events):**
- After every balance-changing operation, publish updated kind:7375 token events
- Delete old kind:7375 events via kind:5 when proofs are spent
- Publish kind:7376 history events for audit trail
- Optionally publish kind:7374 quote events for cross-device state
#### 2. `src/tools/tool_cashu_wallet.c` — LLM Tool Interface
Exposes wallet operations as tools the LLM can call.
#### 3. Config additions in `src/config.h` / `src/config.c`
New `cashu_wallet_config_t` section.
## Config Schema Changes
Add to `didactyl_config_t`:
```c
typedef struct {
int enabled; // master switch
char** mint_urls; // default mint URLs
int mint_count;
char unit[16]; // default unit, e.g. "sat"
int auto_load; // load wallet from relays on startup
int mint_timeout_seconds; // HTTP timeout for mint operations
} cashu_wallet_config_t;
```
Example `config.jsonc`:
```jsonc
"cashu_wallet": {
"enabled": true,
"mints": [
"https://mint.minibits.cash",
"https://stablenut.umint.cash"
],
"unit": "sat",
"auto_load": true,
"mint_timeout_seconds": 30
}
```
## Tool Definitions
### `cashu_wallet_balance`
- **Description:** Check the agent wallet balance across all mints
- **Parameters:** none (or optional `mint_url` to filter)
- **Returns:** `{ "total_sats": 1234, "by_mint": [{ "mint": "...", "balance": 500 }] }`
### `cashu_wallet_info`
- **Description:** Get information about a Cashu mint
- **Parameters:** `{ "mint_url": "https://..." }`
- **Returns:** `{ "name": "...", "version": "...", "keysets": [...] }`
### `cashu_wallet_mint_quote`
- **Description:** Request a Lightning invoice to fund the wallet
- **Parameters:** `{ "mint_url": "https://...", "amount": 1000, "unit": "sat" }`
- **Returns:** `{ "quote_id": "...", "payment_request": "lnbc...", "expiry": ... }`
### `cashu_wallet_mint_check`
- **Description:** Check if a mint quote invoice has been paid
- **Parameters:** `{ "mint_url": "https://...", "quote_id": "..." }`
- **Returns:** `{ "paid": true/false, "amount": 1000 }`
### `cashu_wallet_mint_claim`
- **Description:** Claim tokens after a mint quote invoice is paid
- **Parameters:** `{ "mint_url": "https://...", "quote_id": "...", "amount": 1000 }`
- **Returns:** `{ "success": true, "new_balance": 2234 }`
### `cashu_wallet_melt_quote`
- **Description:** Get a quote to pay a Lightning invoice from the wallet
- **Parameters:** `{ "mint_url": "https://...", "payment_request": "lnbc...", "unit": "sat" }`
- **Returns:** `{ "quote_id": "...", "amount": 500, "fee_reserve": 2 }`
### `cashu_wallet_melt_pay`
- **Description:** Pay a Lightning invoice using wallet tokens
- **Parameters:** `{ "mint_url": "https://...", "quote_id": "..." }`
- **Returns:** `{ "success": true, "paid": true, "new_balance": 1732 }`
### `cashu_wallet_check_proofs`
- **Description:** Validate that stored proofs are still spendable
- **Parameters:** `{ "mint_url": "https://..." }` (optional, checks all mints if omitted)
- **Returns:** `{ "valid": 15, "spent": 2, "cleaned": true }`
## Phased Implementation Plan
### Phase 1: Cashu Wallet Core Module
- [ ] Create `src/cashu_wallet.h` with wallet state structs and function declarations
- [ ] Create `src/cashu_wallet.c` with:
- [ ] `cashu_wallet_init()` / `cashu_wallet_cleanup()` lifecycle
- [ ] In-memory state: wallet data + token array with event IDs
- [ ] Mutex protection for thread safety
- [ ] `cashu_wallet_create_new()` — generate random privkey, build `nostr_nip60_wallet_data_t`, publish kind:17375 via `nostr_handler_publish_kind_event()`
- [ ] `cashu_wallet_load_from_relays()` — use `nostr_nip60_create_wallet_filter()` + `nostr_handler_query_json()` to fetch and parse wallet + token events
- [ ] `cashu_wallet_balance()` / `cashu_wallet_balance_total()` — iterate in-memory tokens, call `nostr_nip60_sum_proofs()`
### Phase 2: Mint Interaction (Fund & Pay)
- [ ] Add to `src/cashu_wallet.c`:
- [ ] `cashu_wallet_mint_quote()` — call `cashu_mint_request_mint_quote()`
- [ ] `cashu_wallet_check_mint_quote()` — call `cashu_mint_check_mint_quote()`
- [ ] `cashu_wallet_claim_tokens()` — call `cashu_mint_mint_tokens()`, parse response proofs via `nostr_nip60_proofs_from_json()`, create and publish kind:7375 token event, publish kind:7376 history
- [ ] `cashu_wallet_melt_quote()` — call `cashu_mint_request_melt_quote()`
- [ ] `cashu_wallet_melt_pay()` — select proofs to spend, call `cashu_mint_melt_tokens()`, delete spent token events via `nostr_nip60_create_token_deletion()`, rollover change via `nostr_nip60_create_rollover_token()`, publish kind:7376 history
- [ ] `cashu_wallet_swap()` — call `cashu_mint_swap()`, update token events
- [ ] `cashu_wallet_check_proofs()` — call `cashu_mint_check_proofs_state()`, clean up spent proofs
- [ ] `cashu_wallet_get_info()` — call `cashu_mint_get_info()`
### Phase 3: Config & Startup Integration
- [ ] Add `cashu_wallet_config_t` to `src/config.h`
- [ ] Parse `"cashu_wallet"` section in `src/config.c`
- [ ] Call `cashu_wallet_init()` from `src/main.c` after `agent_init()`
- [ ] If `auto_load` is true, call `cashu_wallet_load_from_relays()` during startup
- [ ] If no wallet event found and mints configured, call `cashu_wallet_create_new()`
- [ ] Call `cashu_wallet_cleanup()` in shutdown path
- [ ] Add `src/cashu_wallet.c` to `Makefile` SRCS
### Phase 4: LLM Tools
- [ ] Create `src/tools/tool_cashu_wallet.c` implementing all 8 tool execute functions
- [ ] Add tool declarations to `src/tools/tools_internal.h`
- [ ] Register tools in `src/tools/tools_dispatch.c`
- [ ] Add JSON schemas in `src/tools/tools_schema.c`
- [ ] Add `src/tools/tool_cashu_wallet.c` to `Makefile` SRCS
### Phase 5: Testing & Validation
- [ ] Unit test: create wallet, publish, reload from relay, verify state
- [ ] Integration test: mint quote → claim → check balance → melt quote → pay
- [ ] Test proof rollover: spend partial proofs, verify deletion + new token event
- [ ] Test startup: fresh agent creates wallet; existing agent loads wallet
- [ ] Test error handling: mint offline, invalid proofs, insufficient balance
## Key Design Decisions
1. **Wallet privkey is NOT the agent's Nostr privkey** — per NIP-60 spec, a separate privkey is generated and stored encrypted in the kind:17375 event. This privkey is used for P2PK ecash locking (future NIP-61 support).
2. **State lives on relays** — the in-memory state is a cache. On startup the agent fetches its wallet state from relays. After every mutation, updated events are published back.
3. **Proof selection for spending** — when melting, the wallet needs to select proofs that sum to at least the required amount. Implement a simple greedy algorithm (largest-first) with change output via swap.
4. **Thread safety** — wallet operations are called from the LLM tool loop which may run concurrently with triggered skills. A mutex protects all state mutations.
5. **No NIP-61 (nutzaps) in this phase** — receiving/sending nutzaps is a separate feature that builds on top of this wallet foundation.
## File Changes Summary
| File | Change |
|------|--------|
| `src/cashu_wallet.h` | **NEW** — cashu wallet manager header |
| `src/cashu_wallet.c` | **NEW** — cashu wallet manager implementation |
| `src/tools/tool_cashu_wallet.c` | **NEW** — LLM tool implementations |
| `src/config.h` | Add `cashu_wallet_config_t` to `didactyl_config_t` |
| `src/config.c` | Parse `"cashu_wallet"` config section |
| `src/main.c` | Call `cashu_wallet_init()` / `cashu_wallet_cleanup()` |
| `src/tools/tools_internal.h` | Declare `execute_cashu_wallet_*` functions |
| `src/tools/tools_dispatch.c` | Register cashu wallet tool dispatch entries |
| `src/tools/tools_schema.c` | Add cashu wallet tool JSON schemas |
| `Makefile` | Add `cashu_wallet.c` and `tool_cashu_wallet.c` to SRCS |
+81
View File
@@ -0,0 +1,81 @@
# Didactyl Integration Plan: Unified `nostr_core_lib` Logging into One File
## Goal
Route `nostr_core_lib` logs through didactyl logging so there is one authoritative file for errors, using existing didactyl logging in [`debug.c`](../src/debug.c:1) plus the new callback API in [`nostr_log.h`](../nostr_core_lib/nostr_core/nostr_log.h:1).
## Current State
- Didactyl writes logs to path from `DIDACTYL_LOG_FILE` or default `debug.log` in [`debug_open_log_file`](../src/debug.c:10).
- Didactyl log emission is centralized in [`debug_log`](../src/debug.c:31).
- Relay pool setup occurs in [`nostr_handler_init`](../src/nostr_handler.c:1519).
- `nostr_core_lib` now exposes callback logging API in [`nostr_log.h`](../nostr_core_lib/nostr_core/nostr_log.h:1).
## Desired End State
- `nostr_core_lib` logs are forwarded into didactyl logger via callback registration.
- One file path configured by `DIDACTYL_LOG_FILE` receives didactyl plus nostr_core_lib errors.
- Log lines preserve source component tags such as `nostr:websocket` and `nostr:nip013`.
## Architecture
```mermaid
flowchart TD
A[nostr_core_lib emits callback log] --> B[didactyl bridge callback in nostr_handler.c]
B --> C[map nostr level to didactyl level]
C --> D[debug_log in debug.c]
D --> E[DIDACTYL_LOG_FILE single destination]
```
## Implementation Steps
1. Add bridge function in [`nostr_handler.c`](../src/nostr_handler.c:1519)
- Create static callback `nostr_core_log_bridge level component message user_data`.
- Prefix forwarded lines with `nostr:` namespace.
2. Map levels from `nostr_core_lib` to didactyl
- `NOSTR_LOG_LEVEL_ERROR` to `DEBUG_LEVEL_ERROR`
- `NOSTR_LOG_LEVEL_WARN` to `DEBUG_LEVEL_WARN`
- `NOSTR_LOG_LEVEL_INFO` to `DEBUG_LEVEL_INFO`
- `NOSTR_LOG_LEVEL_DEBUG` to `DEBUG_LEVEL_DEBUG`
- `NOSTR_LOG_LEVEL_TRACE` to `DEBUG_LEVEL_TRACE`
3. Register callback during startup in [`nostr_handler_init`](../src/nostr_handler.c:1519)
- Before relay setup, call `nostr_set_log_callback`.
- Set threshold with `nostr_set_log_level` aligned to current didactyl debug level.
4. Enforce single-file policy
- Set `DIDACTYL_LOG_FILE` to desired final log path.
- Keep didactyl as only file owner via [`debug_open_log_file`](../src/debug.c:10).
5. Ensure error visibility
- Keep bridge forwarding at least error and warn levels even when app runs at lower verbosity.
- Optionally pin library threshold to `WARN` or `ERROR` for production profiles.
## Validation Plan
1. Start didactyl with explicit file path
- Example environment: `DIDACTYL_LOG_FILE=didactyl.log`.
2. Trigger nostr websocket activity
- Confirm `nostr:websocket` entries appear in same file.
3. Trigger nip013 path
- Confirm `nostr:nip013` entries appear in same file.
4. Trigger normal didactyl LLM call
- Confirm `[didactyl] llm request` still lands in same file.
5. Verify there is no second active file for nostr core logs.
## Rollout Notes
- Implement bridge first, then verify in development run.
- If log volume is too high, reduce callback threshold by setting `nostr_set_log_level`.
- Keep one destination file operationally stable by configuring and documenting `DIDACTYL_LOG_FILE`.
## Files to Change in Code Mode
- [`src/nostr_handler.c`](../src/nostr_handler.c)
- Optional docs update in [`README.md`](../README.md)
- Optional operational note in [`docs/TOOLS.md`](../docs/TOOLS.md)
+459
View File
@@ -0,0 +1,459 @@
# Didactyl Server Installation Guide — systemd + Dedicated User Model
## Overview
This document describes how to install Didactyl on a Linux server as a dedicated system user, managed by systemd, with scoped sudo privileges for server maintenance tasks.
The mental model: **Didactyl is a person on your server.** It gets its own home directory, its own login identity, and explicit permission to manage the services you delegate to it — nothing more.
## Architecture
```mermaid
graph TD
subgraph Internet
RELAYS[Nostr Relays<br/>wss://relay.damus.io<br/>wss://relay.primal.net]
LLM_API[LLM Provider API<br/>OpenAI / PPQ / Ollama]
end
subgraph Server
subgraph "systemd"
SVC[didactyl.service<br/>User=didactyl<br/>Group=didactyl]
end
subgraph "/home/didactyl/"
BIN[didactyl binary]
CFG[genesis.jsonc<br/>mode 600]
LOGS[context.log.md<br/>didactyl.log]
end
subgraph "Privilege Boundary"
SUDOERS[/etc/sudoers.d/didactyl<br/>Whitelisted commands only]
end
subgraph "Unprivileged Commands"
MON[free / df / uptime<br/>ps / cat /proc/*<br/>ss -tlnp / top]
end
subgraph "Privileged Commands via sudo"
SYSD[systemctl status/restart/start/stop<br/>journalctl<br/>daemon-reload]
end
end
ADMIN[Administrator<br/>via Nostr DM] -->|NIP-04 encrypted| RELAYS
RELAYS <-->|WebSocket| SVC
SVC --> BIN
BIN <-->|HTTPS| LLM_API
BIN -->|popen as didactyl| MON
BIN -->|sudo via popen| SUDOERS
SUDOERS --> SYSD
style CFG fill:#f66,stroke:#333,color:#fff
style SUDOERS fill:#ff9,stroke:#333
style SVC fill:#9f9,stroke:#333
```
## Security Model
### Privilege Tiers
Didactyl enforces three privilege tiers for inbound Nostr messages (see `src/config.h` security_config_t):
| Tier | Who | Can use tools? | Can chat? |
|------|-----|---------------|-----------|
| **ADMIN** | Your npub (config `admin.pubkey`) | ✅ Yes | ✅ Yes |
| **WoT** | Contacts in your follow list | ❌ No (configurable) | ✅ Yes |
| **Stranger** | Everyone else | ❌ No | Canned response or ignored |
Only the ADMIN tier can trigger `local_shell_exec` — the tool that runs commands on the server.
### OS-Level Privilege Separation
The `local_shell_exec` tool in `src/tools/tool_local.c` calls `popen()` directly. Whatever the process user can do, the agent can do. This is why we:
1. Run as a **dedicated unprivileged user** (`didactyl`)
2. Grant **specific sudo permissions** via `/etc/sudoers.d/didactyl`
3. Use **systemd sandboxing** directives to limit filesystem access
### What the Agent Cannot Do
With the configuration described in this guide:
- ❌ Write anywhere outside `/home/didactyl/`
- ❌ Run arbitrary root commands not in the sudoers whitelist
- ❌ Install or remove packages (unless explicitly whitelisted)
- ❌ Modify system configuration files in `/etc/`
- ❌ Access other users' home directories (with proper home directory permissions)
- ❌ Accept tool commands from anyone except the ADMIN pubkey
---
## Installation Steps
### Prerequisites
- A Linux server with systemd (Debian/Ubuntu, RHEL/Fedora, Arch, etc.)
- Network access to Nostr relays and your LLM provider
- The Didactyl static binary (download from releases or build with `./build_static.sh`)
- A Nostr keypair for the agent (nsec)
- Your admin Nostr keypair (npub)
- An LLM API key
### Step 1: Create the Didactyl User
```bash
# Create a regular user with a home directory and bash shell
sudo useradd -m -s /bin/bash -c "Didactyl Nostr Agent" didactyl
```
**Why bash and not nologin?** The `local_shell_exec` tool runs commands via `sh -lc` (login shell). A real shell ensures PATH, locale, and environment are properly initialized. The agent needs to "log in" to do its job.
**Why a real home directory?** The agent needs a workspace for:
- Its binary and config
- Log files (`context.log.md`, `didactyl.log`)
- Any files it creates during shell operations
- The `working_directory` for the shell tool
### Step 2: Install the Binary and Config
```bash
# Copy the static binary
sudo cp didactyl_static_x86_64 /home/didactyl/didactyl
sudo chmod 755 /home/didactyl/didactyl
# Copy and configure genesis.jsonc
sudo cp genesis.jsonc /home/didactyl/genesis.jsonc
# CRITICAL: Lock down permissions on the config file (contains nsec private key)
sudo chmod 600 /home/didactyl/genesis.jsonc
# Set ownership
sudo chown -R didactyl:didactyl /home/didactyl/
# Protect the home directory from other users
sudo chmod 750 /home/didactyl/
```
### Step 3: Configure genesis.jsonc
Edit `/home/didactyl/genesis.jsonc` with the agent's identity, your admin pubkey, LLM credentials, and the shell working directory:
```jsonc
{
"key": {
"nsec": "nsec1..." // Agent's private key
},
"admin": {
"pubkey": "npub1..." // YOUR public key
},
"dm_protocol": "nip04",
"llm": {
"provider": "openai",
"api_key": "sk-...",
"model": "gpt-4o-mini",
"base_url": "https://api.openai.com/v1",
"max_tokens": 512,
"temperature": 0.7
},
"tools": {
"enabled": true,
"max_turns": 8,
"shell": {
"enabled": true,
"timeout_seconds": 60, // systemctl can be slow
"max_output_bytes": 131072, // journalctl output can be large
"working_directory": "/home/didactyl"
}
},
"api": {
"enabled": true,
"port": 8484,
"bind_address": "127.0.0.1" // Localhost only — do NOT expose
},
"startup_events": [
{
"kind": 10002,
"content": "",
"tags": [
["r", "wss://relay.damus.io"],
["r", "wss://relay.primal.net"]
]
}
]
}
```
**Key settings for server maintenance:**
| Setting | Value | Why |
|---------|-------|-----|
| `shell.timeout_seconds` | `60` | `systemctl` and `journalctl` can take time |
| `shell.max_output_bytes` | `131072` (128KB) | Log output can be verbose |
| `shell.working_directory` | `/home/didactyl` | Agent's home — safe default CWD |
| `api.bind_address` | `127.0.0.1` | Never expose the admin API to the network |
### Step 4: Configure sudo Privileges
```bash
sudo visudo -f /etc/sudoers.d/didactyl
```
Add the following (adjust to your needs):
```sudoers
# /etc/sudoers.d/didactyl
# Didactyl agent — scoped system maintenance privileges
# Service management
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl status *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl start *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl stop *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl enable *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl disable *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl is-active *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl is-enabled *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl list-units *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/systemctl daemon-reload
# Log inspection
didactyl ALL=(ALL) NOPASSWD: /usr/bin/journalctl *
# Network diagnostics (if needed)
didactyl ALL=(ALL) NOPASSWD: /usr/sbin/lsof *
```
**Commands that do NOT need sudo** (the didactyl user can run these directly):
- `free -h` — memory usage
- `df -h` — disk usage
- `uptime` — load averages
- `top -bn1` — process snapshot
- `ps aux` — process list
- `cat /proc/cpuinfo` — CPU info
- `cat /proc/meminfo` — memory info
- `ss -tlnp` — listening ports (as unprivileged user, shows own processes)
- `uname -a` — kernel info
- `w` — who is logged in
### Step 5: Create the systemd Unit File
```bash
sudo tee /etc/systemd/system/didactyl.service << 'EOF'
[Unit]
Description=Didactyl Sovereign Nostr Agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=didactyl
Group=didactyl
WorkingDirectory=/home/didactyl
ExecStart=/home/didactyl/didactyl --config /home/didactyl/genesis.jsonc --debug 3
# --- Privilege & Sandbox ---
# Must be false — sudo needs to escalate privileges
NoNewPrivileges=false
# Protect filesystem: read-only except for agent home
ProtectSystem=strict
ReadWritePaths=/home/didactyl
# Must be false — the agent's home IS its workspace
ProtectHome=false
# Isolate /tmp
PrivateTmp=yes
# --- Environment ---
Environment=SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
# --- Restart Policy ---
Restart=on-failure
RestartSec=10
# --- Logging ---
StandardOutput=journal
StandardError=journal
SyslogIdentifier=didactyl
[Install]
WantedBy=multi-user.target
EOF
```
**Important systemd notes:**
| Directive | Value | Reason |
|-----------|-------|--------|
| `NoNewPrivileges` | `false` | Required for `sudo` to work from `popen()` |
| `ProtectSystem` | `strict` | Makes `/usr`, `/boot`, `/etc` read-only |
| `ReadWritePaths` | `/home/didactyl` | Whitelist the agent's home for writes |
| `ProtectHome` | `false` | The agent lives in `/home/` — can't protect it from itself |
| `PrivateTmp` | `yes` | Isolates `/tmp` so other processes can't snoop |
| `SSL_CERT_FILE` | path to CA bundle | Required for TLS connections to relays and LLM API |
### Step 6: Enable and Start
```bash
# Reload systemd to pick up the new unit
sudo systemctl daemon-reload
# Enable auto-start on boot
sudo systemctl enable didactyl
# Start the agent
sudo systemctl start didactyl
# Verify it's running
sudo systemctl status didactyl
# Watch logs in real-time
sudo journalctl -u didactyl -f
```
### Step 7: Verify the Agent is Working
1. **Check systemd status:**
```bash
sudo systemctl status didactyl
```
Should show `active (running)`.
2. **Check logs for relay connections:**
```bash
sudo journalctl -u didactyl --no-pager -n 50
```
Look for relay connection messages and "EOSE" (End of Stored Events).
3. **Send a test DM via Nostr:**
From your admin Nostr client, send an encrypted DM to the agent's npub:
```
What is the server uptime?
```
The agent should call `local_shell_exec` with `uptime` and reply with the result.
4. **Test sudo access:**
```
What services are running? Use systemctl list-units --type=service --state=running
```
5. **Check the local API (from the server itself):**
```bash
curl http://127.0.0.1:8484/api/context
```
---
## Updating the Agent
To update Didactyl to a new version:
```bash
# Stop the service
sudo systemctl stop didactyl
# Replace the binary
sudo cp didactyl_static_x86_64_new /home/didactyl/didactyl
sudo chown didactyl:didactyl /home/didactyl/didactyl
sudo chmod 755 /home/didactyl/didactyl
# Start the service
sudo systemctl start didactyl
```
The agent's identity, skills, and memory live on Nostr — replacing the binary doesn't lose any state.
---
## Expanding Privileges
The sudoers file is the single control point for what the agent can do with elevated privileges. To grant additional capabilities:
```bash
sudo visudo -f /etc/sudoers.d/didactyl
```
**Examples of additional privileges you might add:**
```sudoers
# Package management (careful!)
didactyl ALL=(ALL) NOPASSWD: /usr/bin/apt update
didactyl ALL=(ALL) NOPASSWD: /usr/bin/apt install *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/apt upgrade -y
# Docker management
didactyl ALL=(ALL) NOPASSWD: /usr/bin/docker ps *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/docker restart *
didactyl ALL=(ALL) NOPASSWD: /usr/bin/docker logs *
# Firewall inspection
didactyl ALL=(ALL) NOPASSWD: /usr/sbin/ufw status *
didactyl ALL=(ALL) NOPASSWD: /usr/sbin/iptables -L *
# Nginx/Apache config test
didactyl ALL=(ALL) NOPASSWD: /usr/sbin/nginx -t
didactyl ALL=(ALL) NOPASSWD: /usr/sbin/apachectl configtest
```
---
## Customizing the Agent's Personality for Server Maintenance
The agent's behavior is defined by its default skill content in `genesis.jsonc` (the `default_skill.content` field). For a server maintenance role, you should customize the soul/skill to include instructions like:
- What services it's responsible for monitoring
- How frequently to check (via triggered skills)
- What constitutes an alert-worthy condition
- How to format status reports
- Which `sudo` commands are available to it
- Escalation procedures (when to alert you vs. auto-fix)
This is a skill/prompt engineering task that can be done after the base installation is working.
---
## Quick Reference
### File Locations
| File | Path | Permissions |
|------|------|-------------|
| Binary | `/home/didactyl/didactyl` | `755 didactyl:didactyl` |
| Config | `/home/didactyl/genesis.jsonc` | `600 didactyl:didactyl` |
| Home directory | `/home/didactyl/` | `750 didactyl:didactyl` |
| systemd unit | `/etc/systemd/system/didactyl.service` | `644 root:root` |
| sudoers | `/etc/sudoers.d/didactyl` | `440 root:root` |
### Common Commands
```bash
# Service management
sudo systemctl start didactyl
sudo systemctl stop didactyl
sudo systemctl restart didactyl
sudo systemctl status didactyl
# Logs
sudo journalctl -u didactyl -f # follow live
sudo journalctl -u didactyl --since today
sudo journalctl -u didactyl -n 100 # last 100 lines
# Check agent's local API
curl http://127.0.0.1:8484/api/context
# Edit sudo permissions
sudo visudo -f /etc/sudoers.d/didactyl
# Edit config (stop service first)
sudo systemctl stop didactyl
sudo -u didactyl nano /home/didactyl/genesis.jsonc
sudo systemctl start didactyl
```
+315
View File
@@ -0,0 +1,315 @@
# Skill-Driven Architecture — Implementation Plan
## Summary
Overhaul Didactyl so that **skills are the universal unit of behavior** and **Nostr is the source of truth for all agent state**. The agent boots from a single nsec; everything else — context template, LLM config, relay list, personality — lives on Nostr as skills or encrypted events.
---
## Architecture Decisions (Finalized)
| Decision | Detail |
|----------|--------|
| Genesis config | `genesis.jsonc` is consumed on first run only; can be deleted afterward |
| Runtime identity seed | nsec (via CLI flag or systemd credential) is the only required input after genesis |
| Context template | Becomes the `didactyl_default` skill — first entry in kind 10123 adoption list |
| Context modes | Removed. `inject`/`full`/`override` replaced by adoption-list-order composition |
| Execution params | `llm`, `temperature`, `max_tokens`, `seed`, `tools` move from skill content to trigger tags |
| DM trigger type | New trigger type `dm` — makes DM handling consistent with all other triggers |
| LLM config storage | Kind 30078 `d=llm_config`, NIP-44 encrypted to self, stored on Nostr |
| Admin config storage | Admin pubkey stored as tag on soul event or dedicated config event on Nostr |
| Bootstrap relays | Listed in `genesis.jsonc`; agent adopts admin relay list on first run |
| Skill portability | Skills are general Nostr events; implementation-specific variables resolve to empty |
---
## Phase 1 — Specification Updates
Update the authoritative documentation to reflect all decisions before writing code.
### 1.1 Update docs/SKILLS.md
- Remove `llm`, `temperature`, `max_tokens`, `seed`, `tools` from the Content Fields table
- Add execution-parameter tags to the Trigger Tags table: `llm`, `temperature`, `max_tokens`, `seed`, `tools`
- Add `dm` trigger type with filter format `{"from":"admin"}`, `{"from":"wot"}`, `{"from":"any"}`
- Update all examples to show execution params as tags, not content fields
- Update the private skill decrypted payload example accordingly
- Remove the LLM Specification section header (move fallback-chain docs into trigger tag reference)
- Update the Execution Flow mermaid diagram
### 1.2 Update docs/CONTEXT.md
- Remove the Context Modes section entirely (inject/full/override)
- Remove the context_mode branching from the Context Assembly Flow mermaid diagram
- Replace with adoption-list-order composition model
- Update Context Parts table to reference skills instead of soul event
- Update Token Budget section to remove context_mode references
### 1.3 Write docs/GENESIS.md (new)
- Document the genesis.jsonc format and purpose
- Document the first-run flow: genesis consumed, events published, LLM config encrypted
- Document the subsequent-run flow: nsec only, everything fetched from Nostr
- Document bootstrap relay strategy
---
## Phase 2 — Genesis Startup Flow
### 2.1 Define genesis.jsonc schema
```jsonc
{
"key": { "nsec": "nsec1..." },
"admin": { "pubkey": "npub1..." },
"dm_protocol": "nip04",
"llm": {
"provider": "...",
"api_key": "...",
"model": "...",
"base_url": "...",
"max_tokens": 512,
"temperature": 0.7
},
"api": {
"enabled": true,
"port": 8484,
"bind_address": "127.0.0.1"
},
"bootstrap_relays": [
"wss://relay.damus.io",
"wss://nos.lol"
],
"startup_events": [
// Kind 0 profile, kind 10002 relay list, kind 10050 DM relays,
// kind 3 contact list, kind 31123/31124 skills,
// kind 10123 adoption list
],
"default_skill": {
// The didactyl_default skill content — soul + context template
}
}
```
### 2.2 Implement first-run detection
- On startup, check if the agent has published a kind 10002 event (relay list) on bootstrap relays
- If no kind 10002 found: this is a first run — consume genesis.jsonc
- If kind 10002 found: this is a subsequent run — fetch everything from Nostr
### 2.3 Implement genesis event publishing
- Connect to bootstrap relays
- Fetch admin kind 10002 (relay list) and adopt those relays
- Publish all startup_events from genesis.jsonc
- Publish default_skill as kind 31123 with `["d", "didactyl_default"]`
- Publish kind 10123 adoption list with didactyl_default as first entry
- Encrypt and publish LLM config as kind 30078 `d=llm_config`
- Encrypt and publish admin pubkey + dm_protocol as kind 30078 `d=agent_config`
### 2.4 Implement nsec-only startup
- Accept nsec via `--nsec` CLI flag or `DIDACTYL_NSEC` environment variable
- Accept optional `--api-port` and `--api-bind` for local API config
- Derive pubkey from nsec
- Connect to hardcoded bootstrap relays (compiled-in fallback list)
- Fetch own kind 10002 → connect to own relays
- Fetch kind 30078 `d=llm_config` → decrypt → initialize LLM client
- Fetch kind 30078 `d=agent_config` → decrypt → get admin pubkey, dm_protocol
- Fetch kind 10123 → get adoption list
- Fetch adopted skills → build context template
- Proceed to normal operation
---
## Phase 3 — Adoption-List-Order Context Assembly
### 3.1 Refactor context building in agent.c
Current flow (agent_build_admin_messages_json):
- If prompt template exists: use prompt_template_build_messages
- Else: hardcoded context assembly (append_admin_identity_context, append_startup_events_context, append_adopted_skills_context, etc.)
New flow:
- Fetch kind 10123 adoption list
- For each adopted skill in order:
- Fetch skill content
- If skill has a template: resolve template variables via tools_execute
- Append resolved content as system message(s)
- Append DM history (if dm trigger)
- Append user message / triggering event
### 3.2 Unify template variable resolution
Current state: two template formats exist:
- YAML section format with `tool:` directives (prompt_template.c)
- `{{variable}}` inline syntax (documented in SKILLS.md but not fully implemented)
Target: single `{{variable}}` format that resolves through tools_execute.
- Implement `{{variable}}` resolution in a new or updated template engine
- Each `{{variable_name}}` calls `tools_execute(ctx, variable_name, "{}")`
- Unknown variables resolve to empty string
- The YAML section format becomes legacy (still supported for backward compat during transition)
### 3.3 Remove hardcoded context assembly
- Remove append_admin_identity_context, append_startup_events_context, append_adopted_skills_context from agent.c
- These become unnecessary because the didactyl_default skill template handles all of it via {{variable}} resolution
- Keep the functions available as tools so templates can call them
---
## Phase 4 — Execution Params on Trigger Tags
### 4.1 Update trigger_manager to read execution params from tags
Current trigger registration reads: `trigger`, `filter`, `action`, `enabled`
Add reading of: `llm`, `temperature`, `max_tokens`, `seed`, `tools`
Store these on the trigger_entry_t struct.
### 4.2 Apply execution params at invocation time
When a trigger fires:
- If `llm` tag present: temporarily override the LLM model for this execution
- If `temperature` tag present: temporarily override temperature
- If `max_tokens` tag present: temporarily override max_tokens
- If `tools` tag present: filter available tools for this execution
- After execution: restore defaults
Use the existing model_set/model_get pattern (llm_set_config/llm_get_config) for temporary overrides.
### 4.3 Remove execution params from skill content parsing
- Stop reading `llm`, `temperature`, `max_tokens`, `seed`, `tools` from skill content JSON
- These fields in content are ignored (backward compat: warn if present)
---
## Phase 5 — DM Trigger Type
### 5.1 Add dm trigger type to trigger_manager
- New trigger type: `TRIGGER_TYPE_DM`
- Filter format: `{"from":"admin"}`, `{"from":"wot"}`, `{"from":"any"}`
- Registration: when loading skills with `["trigger", "dm"]`, register as DM trigger
### 5.2 Refactor agent_on_message to use trigger dispatch
Current flow:
- agent_on_message receives DM
- Checks sender tier
- Builds context directly
- Calls LLM
New flow:
- agent_on_message receives DM
- Checks sender tier
- Finds matching DM trigger(s) from registered triggers
- For each matching trigger: execute via the standard trigger execution path
- If no DM trigger matches: fall back to default behavior (or reject)
### 5.3 didactyl_default gets a dm trigger
The default skill in genesis.jsonc includes:
```json
["trigger", "dm"],
["filter", "{\"from\":\"admin\"}"],
["llm", "default"],
["tools", "true"],
["enabled", "true"]
```
This makes the normal admin DM conversation a triggered skill execution, consistent with everything else.
---
## Phase 6 — Encrypted Config Storage
### 6.1 Implement config_store tool
New tool: `config_store` — encrypts and publishes agent config to Nostr
- Kind 30078 with configurable d-tag
- NIP-44 encrypted to self (same pattern as memory tool)
- Used for: `d=llm_config`, `d=agent_config`
### 6.2 Implement config_recall tool
New tool: `config_recall` — fetches and decrypts agent config from Nostr
- Query kind 30078 by d-tag and own pubkey
- NIP-44 decrypt
- Return JSON content
### 6.3 Use config tools during startup
- During genesis: call config_store for llm_config and agent_config
- During nsec-only startup: call config_recall to recover LLM and agent config
- These tools are also available to the LLM for runtime config changes
---
## Phase 7 — Documentation Cleanup
### 7.1 Update README.md
- Update startup instructions to reflect genesis.jsonc
- Update architecture overview
- Remove references to config.jsonc as the primary config
### 7.2 Deprecate config.jsonc
- Keep config.jsonc.example as reference but mark as legacy
- Document migration path from config.jsonc to genesis.jsonc
### 7.3 Update context_template.md
- Mark as legacy/deprecated
- Point to didactyl_default skill as the replacement
---
## File Change Summary
| File | Change Type | Description |
|------|------------|-------------|
| `docs/SKILLS.md` | Modify | Execution params to trigger tags, add dm trigger type |
| `docs/CONTEXT.md` | Modify | Remove context_mode, adoption-list composition |
| `docs/GENESIS.md` | New | Genesis config documentation |
| `genesis.jsonc` | Modify | Add bootstrap_relays, flesh out default_skill and startup_events |
| `src/agent.c` | Major refactor | Adoption-list context assembly, DM trigger dispatch |
| `src/config.c` | Modify | Support genesis.jsonc format, nsec-only mode |
| `src/config.h` | Modify | New config structs for minimal runtime config |
| `src/main.c` | Modify | First-run detection, nsec CLI flag, genesis flow |
| `src/trigger_manager.c` | Modify | DM trigger type, execution params from tags |
| `src/trigger_manager.h` | Modify | New trigger type enum, execution param fields |
| `src/prompt_template.c` | Modify | {{variable}} resolution engine |
| `src/tools/tool_config.c` | New | config_store and config_recall tools |
| `src/tools/tools_dispatch.c` | Modify | Register new config tools |
| `src/tools/tools_schema.c` | Modify | Schema for new config tools |
| `README.md` | Modify | Updated startup docs |
| `context_template.md` | Deprecate | Replaced by didactyl_default skill |
| `config.jsonc.example` | Deprecate | Replaced by genesis.jsonc |
---
## Dependency Order
```mermaid
graph TD
P1[Phase 1: Spec Updates] --> P2[Phase 2: Genesis Startup]
P1 --> P3[Phase 3: Adoption-List Context]
P1 --> P4[Phase 4: Execution Params on Tags]
P1 --> P5[Phase 5: DM Trigger Type]
P2 --> P6[Phase 6: Encrypted Config Storage]
P3 --> P5
P4 --> P5
P5 --> P7[Phase 7: Documentation Cleanup]
P6 --> P7
```
Phases 2, 3, 4 can proceed in parallel after Phase 1. Phase 5 depends on 3 and 4. Phase 6 depends on 2. Phase 7 is last.
+285
View File
@@ -0,0 +1,285 @@
# Plan: Refactor tools.c into Individual Tool Files
## Problem
`src/tools.c` is ~6,123 lines containing 44 `execute_*` functions, a ~650-line schema builder, shared helpers, and a dispatcher. It is the largest file in the project and difficult to navigate, review, and maintain.
## Goal
Split `src/tools.c` into focused files organized by tool group, with shared helpers in a common module. The public API (`tools.h`) remains unchanged — no callers need modification.
## Target File Structure
```
src/
├── tools.h # Public API (UNCHANGED)
├── tools_internal.h # Shared internal helpers + per-tool-file function declarations
├── tools_common.c # Shared helper implementations
├── tools_schema.c # tools_build_openai_schema_json()
├── tools_dispatch.c # tools_init, tools_cleanup, tools_execute dispatcher
└── tools/
├── tool_nostr_post.c # nostr_post, nostr_post_readme, nostr_file_md_to_longform_post
├── tool_nostr_query.c # nostr_query
├── tool_nostr_identity.c # nostr_pubkey, nostr_npub, nostr_encode, nostr_decode
├── tool_nostr_social.c # nostr_react, nostr_profile_get, nostr_nip05_lookup
├── tool_nostr_dm.c # nostr_dm_send, nostr_dm_send_nip17, nostr_encrypt, nostr_decrypt
├── tool_nostr_relay.c # nostr_relay_status, nostr_relay_info
├── tool_nostr_list.c # nostr_list_manage, nostr_delete
├── tool_skill.c # skill_create, skill_list, skill_adopt, skill_remove, skill_edit, skill_search
├── tool_task.c # task_list, task_manage
├── tool_local.c # local_shell_exec, local_file_read, local_file_write, local_http_fetch
├── tool_admin.c # admin_identity, nostr_admin_profile, nostr_admin_contacts, nostr_admin_relays, nostr_admin_notes
├── tool_agent.c # agent_identity, agent_version, message_current
├── tool_model.c # model_get, model_set, model_list
└── tool_meta.c # tool_list, trigger_list
```
## Shared Helpers → tools_common.c
These helpers are used by multiple tool groups and must be non-static in `tools_common.c`, declared in `tools_internal.h`:
| Helper | Current lines | Used by |
|---|---|---|
| `json_error()` | 27-35 | ALL tools |
| `repair_json_control_chars()` | 37-101 | nostr_post, nostr_post_readme |
| `find_key_start()` | 103-111 | nostr_post loose parser |
| `skip_ws()` | 113-116 | parse_tool_args_json, loose parser |
| `parse_loose_kind()` | 118-135 | nostr_post |
| `parse_loose_json_string_value()` | 137-186 | nostr_post |
| `parse_loose_nostr_post_args()` | 188-212 | nostr_post |
| `ensure_tags_array()` | 214-227 | nostr_post |
| `has_tag_key()` | 229-243 | longform post helpers |
| `add_string_tag()` | 245-255 | nostr_post, delete, react, skill, longform |
| `remove_tag_key_all()` | 257-270 | upsert_string_tag |
| `upsert_string_tag()` | 272-276 | skill_edit |
| `parse_tool_args_json()` | 590-564 | ALL tools |
| `is_hex_string_len()` | 581-588 | nostr tools, skill tools, DM tools |
| `find_tag_value_string()` | 855-872 | skill tools, list_manage, longform |
| `tag_tuple_equal()` | 813-828 | skill tools, list_manage |
| `tags_contains_tuple()` | 830-840 | skill tools, list_manage |
| `remove_matching_tag_tuples()` | 842-853 | skill tools, list_manage |
| `build_tool_path()` | (used by local tools + readme) | local tools, readme |
## Tool-Local Helpers (stay static in their tool file)
| Helper | Destination |
|---|---|
| `validate_skill_d_tag()` | `tool_skill.c` |
| `fetch_adoption_list_tags()` | `tool_skill.c` |
| `publish_adoption_list()` | `tool_skill.c` |
| `adoption_tags_contains_address()` | `tool_skill.c` |
| `extract_skill_summary()` | `tool_skill.c` |
| `ci_contains()` | `tool_skill.c` |
| `d_tagify_string()` | `tool_nostr_post.c` |
| `first_markdown_h1()` | `tool_nostr_post.c` |
| `first_markdown_paragraph()` | `tool_nostr_post.c` |
| `trim_copy()` | `tool_nostr_post.c` |
| `auto_enrich_longform_tags()` | `tool_nostr_post.c` |
| `basename_lowercase_dup()` | `tool_nostr_post.c` |
| `detect_ca_bundle_path_for_tools()` | `tool_local.c` |
| `local_http_fetch_write_cb()` | `tool_local.c` |
| `persist_llm_config()` | `tool_model.c` |
## Tool Function Signatures
Each tool file exposes its `execute_*` functions via `tools_internal.h`. Two signature patterns exist:
```c
// Pattern A: context-free (only needs args)
char* execute_nostr_post(const char* args_json);
// Pattern B: context-dependent
char* execute_skill_create(tools_context_t* ctx, const char* args_json);
```
## tools_internal.h Structure
```c
#ifndef DIDACTYL_TOOLS_INTERNAL_H
#define DIDACTYL_TOOLS_INTERNAL_H
#include "tools.h"
#include "cjson/cJSON.h"
// ─── Shared helpers (tools_common.c) ───
char* json_error(const char* msg);
cJSON* parse_tool_args_json(const char* args_json);
int is_hex_string_len(const char* s, size_t expected_len);
int add_string_tag(cJSON* tags, const char* key, const char* value);
int remove_tag_key_all(cJSON* tags, const char* key);
int upsert_string_tag(cJSON* tags, const char* key, const char* value);
int has_tag_key(cJSON* tags, const char* key);
cJSON* ensure_tags_array(cJSON** tags_inout);
cJSON* find_tag_value_string(cJSON* tags, const char* key);
int tag_tuple_equal(cJSON* a, cJSON* b);
int tags_contains_tuple(cJSON* tags, cJSON* tuple);
int remove_matching_tag_tuples(cJSON* tags, cJSON* tuple);
char* repair_json_control_chars(const char* in);
cJSON* parse_loose_nostr_post_args(const char* in);
int build_tool_path(tools_context_t* ctx, const char* rel, char* out, size_t out_size);
// ─── Per-tool-file execute functions ───
// tool_nostr_post.c
char* execute_nostr_post(const char* args_json);
char* execute_nostr_post_readme(tools_context_t* ctx, const char* args_json);
char* execute_nostr_file_md_to_longform_post(tools_context_t* ctx, const char* args_json);
// tool_nostr_query.c
char* execute_nostr_query(const char* args_json);
// tool_nostr_identity.c
char* execute_nostr_pubkey(tools_context_t* ctx, const char* args_json);
char* execute_nostr_npub(tools_context_t* ctx, const char* args_json);
char* execute_nostr_encode(const char* args_json);
char* execute_nostr_decode(const char* args_json);
// tool_nostr_social.c
char* execute_nostr_react(const char* args_json);
char* execute_nostr_profile_get(const char* args_json);
char* execute_nostr_nip05_lookup(const char* args_json);
// tool_nostr_dm.c
char* execute_nostr_dm_send(const char* args_json);
char* execute_nostr_dm_send_nip17(const char* args_json);
char* execute_nostr_encrypt(tools_context_t* ctx, const char* args_json);
char* execute_nostr_decrypt(tools_context_t* ctx, const char* args_json);
// tool_nostr_relay.c
char* execute_nostr_relay_status(const char* args_json);
char* execute_nostr_relay_info(const char* args_json);
// tool_nostr_list.c
char* execute_nostr_list_manage(tools_context_t* ctx, const char* args_json);
char* execute_nostr_delete(const char* args_json);
// tool_skill.c
char* execute_skill_create(tools_context_t* ctx, const char* args_json);
char* execute_skill_list(tools_context_t* ctx, const char* args_json);
char* execute_skill_adopt(tools_context_t* ctx, const char* args_json);
char* execute_skill_remove(tools_context_t* ctx, const char* args_json);
char* execute_skill_edit(tools_context_t* ctx, const char* args_json);
char* execute_skill_search(const char* args_json);
// tool_task.c
char* execute_task_list(tools_context_t* ctx, const char* args_json);
char* execute_task_manage(tools_context_t* ctx, const char* args_json);
// tool_local.c
char* execute_local_http_fetch(tools_context_t* ctx, const char* args_json);
char* execute_local_shell_exec(tools_context_t* ctx, const char* args_json);
char* execute_local_file_read(tools_context_t* ctx, const char* args_json);
char* execute_local_file_write(tools_context_t* ctx, const char* args_json);
// tool_admin.c
char* execute_admin_identity(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_profile(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_contacts(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_relays(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_notes(tools_context_t* ctx, const char* args_json);
// tool_agent.c
char* execute_agent_identity(tools_context_t* ctx, const char* args_json);
char* execute_agent_version(const char* args_json);
char* execute_message_current(tools_context_t* ctx, const char* args_json);
// tool_model.c
char* execute_model_get(const char* args_json);
char* execute_model_set(tools_context_t* ctx, const char* args_json);
char* execute_model_list(const char* args_json);
// tool_meta.c
char* execute_tool_list(tools_context_t* ctx, const char* args_json);
char* execute_trigger_list(tools_context_t* ctx, const char* args_json);
#endif
```
## Makefile Changes
Replace the single `$(SRC_DIR)/tools.c` entry with:
```makefile
SRCS = \
$(SRC_DIR)/main.c \
$(SRC_DIR)/config.c \
$(SRC_DIR)/context.c \
$(SRC_DIR)/llm.c \
$(SRC_DIR)/nostr_handler.c \
$(SRC_DIR)/agent.c \
$(SRC_DIR)/tools_common.c \
$(SRC_DIR)/tools_schema.c \
$(SRC_DIR)/tools_dispatch.c \
$(SRC_DIR)/tools/tool_nostr_post.c \
$(SRC_DIR)/tools/tool_nostr_query.c \
$(SRC_DIR)/tools/tool_nostr_identity.c \
$(SRC_DIR)/tools/tool_nostr_social.c \
$(SRC_DIR)/tools/tool_nostr_dm.c \
$(SRC_DIR)/tools/tool_nostr_relay.c \
$(SRC_DIR)/tools/tool_nostr_list.c \
$(SRC_DIR)/tools/tool_skill.c \
$(SRC_DIR)/tools/tool_task.c \
$(SRC_DIR)/tools/tool_local.c \
$(SRC_DIR)/tools/tool_admin.c \
$(SRC_DIR)/tools/tool_agent.c \
$(SRC_DIR)/tools/tool_model.c \
$(SRC_DIR)/tools/tool_meta.c \
$(SRC_DIR)/trigger_manager.c \
$(SRC_DIR)/prompt_template.c \
$(SRC_DIR)/http_api.c \
$(SRC_DIR)/mongoose.c \
$(SRC_DIR)/debug.c
```
## Implementation Steps
### Phase 1: Create shared infrastructure
- [ ] Create `src/tools_internal.h` with shared helper declarations and all `execute_*` prototypes
- [ ] Create `src/tools_common.c` — move shared helpers from `tools.c`, remove `static`, add `#include "tools_internal.h"`
- [ ] Create `src/tools_schema.c` — move `tools_build_openai_schema_json()` from `tools.c`
- [ ] Create `src/tools_dispatch.c` — move `tools_init()`, `tools_cleanup()`, `tools_execute()` from `tools.c`
- [ ] Update `Makefile` SRCS to include new files (keep `tools.c` temporarily with remaining functions)
- [ ] Build and verify — all tests pass, binary runs
### Phase 2: Extract tool files one at a time
Each step: move `execute_*` functions + their local helpers into the new file, remove from `tools.c`, build, verify.
- [ ] Create `src/tools/` directory
- [ ] Extract `src/tools/tool_nostr_post.c``execute_nostr_post`, `execute_nostr_post_readme`, `execute_nostr_file_md_to_longform_post` + local helpers: `d_tagify_string`, `first_markdown_h1`, `first_markdown_paragraph`, `trim_copy`, `auto_enrich_longform_tags`, `basename_lowercase_dup`
- [ ] Extract `src/tools/tool_nostr_query.c``execute_nostr_query`
- [ ] Extract `src/tools/tool_nostr_identity.c``execute_nostr_pubkey`, `execute_nostr_npub`, `execute_nostr_encode`, `execute_nostr_decode`
- [ ] Extract `src/tools/tool_nostr_social.c``execute_nostr_react`, `execute_nostr_profile_get`, `execute_nostr_nip05_lookup`
- [ ] Extract `src/tools/tool_nostr_dm.c``execute_nostr_dm_send`, `execute_nostr_dm_send_nip17`, `execute_nostr_encrypt`, `execute_nostr_decrypt`
- [ ] Extract `src/tools/tool_nostr_relay.c``execute_nostr_relay_status`, `execute_nostr_relay_info`
- [ ] Extract `src/tools/tool_nostr_list.c``execute_nostr_list_manage`, `execute_nostr_delete`
- [ ] Extract `src/tools/tool_skill.c``execute_skill_create`, `execute_skill_list`, `execute_skill_adopt`, `execute_skill_remove`, `execute_skill_edit`, `execute_skill_search` + local helpers: `validate_skill_d_tag`, `ci_contains`, `fetch_adoption_list_tags`, `publish_adoption_list`, `adoption_tags_contains_address`, `extract_skill_summary`
- [ ] Extract `src/tools/tool_task.c``execute_task_list`, `execute_task_manage`
- [ ] Extract `src/tools/tool_local.c``execute_local_http_fetch`, `execute_local_shell_exec`, `execute_local_file_read`, `execute_local_file_write` + local helpers: `detect_ca_bundle_path_for_tools`, `local_http_fetch_write_cb`, `free_string_array_heap`
- [ ] Extract `src/tools/tool_admin.c``execute_admin_identity`, `execute_nostr_admin_profile`, `execute_nostr_admin_contacts`, `execute_nostr_admin_relays`, `execute_nostr_admin_notes`
- [ ] Extract `src/tools/tool_agent.c``execute_agent_identity`, `execute_agent_version`, `execute_message_current`
- [ ] Extract `src/tools/tool_model.c``execute_model_get`, `execute_model_set`, `execute_model_list` + local helper: `persist_llm_config`
- [ ] Extract `src/tools/tool_meta.c``execute_tool_list`, `execute_trigger_list`
### Phase 3: Cleanup
- [ ] Delete `src/tools.c` (now empty — all code moved)
- [ ] Remove `src/tools.c` from Makefile SRCS
- [ ] Final build + full test run
- [ ] Verify binary size is comparable (no accidental code duplication)
- [ ] Increment version and push
## Validation Criteria
After each extraction step:
1. `make -j4` compiles with zero warnings
2. `./didactyl --debug 5` starts and runs normally
3. Tool execution via DM or `--test-tool` produces identical results
## Risk Mitigation
- **Build after every file extraction** — catch issues immediately
- **No logic changes** — purely mechanical code movement
- **Keep `tools.h` unchanged** — zero impact on callers (`agent.c`, `http_api.c`, `main.c`)
- **Git commit after each phase** — easy rollback points
+262 -262
View File
@@ -14,7 +14,7 @@
#include "llm.h"
#include "nostr_handler.h"
#include "trigger_manager.h"
#include "tools.h"
#include "tools/tools.h"
#include "prompt_template.h"
#include "cjson/cJSON.h"
#include "debug.h"
@@ -79,6 +79,72 @@ static uint64_t message_fingerprint(const char* sender_pubkey_hex, const char* m
return a ^ (b + 0x9e3779b97f4a7c15ULL + (a << 6) + (a >> 2));
}
static uint64_t tool_calls_fingerprint(const llm_response_t* resp) {
if (!resp || resp->tool_call_count <= 0 || !resp->tool_calls) {
return 1469598103934665603ULL;
}
uint64_t h = 1469598103934665603ULL;
for (int i = 0; i < resp->tool_call_count; i++) {
const llm_tool_call_t* tc = &resp->tool_calls[i];
uint64_t name_h = fnv1a64(tc->name ? tc->name : "");
uint64_t args_h = fnv1a64(tc->arguments_json ? tc->arguments_json : "{}");
uint64_t part = name_h ^ (args_h + 0x9e3779b97f4a7c15ULL + (name_h << 6) + (name_h >> 2));
h ^= part + (uint64_t)(i + 1) * 1099511628211ULL;
h *= 1099511628211ULL;
}
h ^= (uint64_t)resp->tool_call_count;
h *= 1099511628211ULL;
return h;
}
static void notify_admin_limit_diagnostic(const char* source,
const char* reason,
const char* subject,
int max_turns,
int turns_run,
int stall_repeat_threshold,
int repeated_tool_turns,
int current_max_tokens,
const char* possible_cause,
const char* hint,
const char* final_answer) {
if (!g_cfg || g_cfg->admin.pubkey[0] == '\0') {
return;
}
char diag[1800];
snprintf(diag,
sizeof(diag),
"⚠️ Didactyl limit diagnostic\n"
"source=%s\n"
"reason=%s\n"
"subject=%s\n"
"max_turns=%d\n"
"turns_run=%d\n"
"stall_repeat_threshold=%d\n"
"repeated_tool_turns=%d\n"
"current_max_tokens=%d\n"
"possible_cause=%s\n"
"hint=%s\n"
"final_answer_preview=%.*s",
source ? source : "unknown",
reason ? reason : "unknown",
subject ? subject : "n/a",
max_turns,
turns_run,
stall_repeat_threshold,
repeated_tool_turns,
current_max_tokens,
possible_cause ? possible_cause : "n/a",
hint ? hint : "n/a",
360,
final_answer ? final_answer : "");
(void)nostr_handler_send_dm_auto(g_cfg->admin.pubkey, diag);
}
static int agent_message_is_debounced(const char* sender_pubkey_hex, const char* message) {
time_t now = time(NULL);
uint64_t fp = message_fingerprint(sender_pubkey_hex, message);
@@ -371,6 +437,15 @@ static char* format_result_markdown_local(const char* raw_result) {
return strdup(raw_result);
}
if (cJSON_IsObject(root)) {
cJSON* content = cJSON_GetObjectItemCaseSensitive(root, "content");
if (content && cJSON_IsString(content) && content->valuestring) {
char* direct = strdup(content->valuestring);
cJSON_Delete(root);
return direct ? direct : strdup(raw_result);
}
}
size_t cap = strlen(raw_result) * 2U + 512U;
if (cap < 2048U) cap = 2048U;
size_t used = 0U;
@@ -468,30 +543,102 @@ static char* build_slash_help_all_json(void) {
cJSON* skill_root = skill_list_json ? cJSON_Parse(skill_list_json) : NULL;
cJSON* skills = skill_root ? cJSON_GetObjectItemCaseSensitive(skill_root, "skills") : NULL;
if (!skills || !cJSON_IsArray(skills) || cJSON_GetArraySize(skills) <= 0) {
(void)append_textf_local(&out, &cap, &used, "- (none)\n");
} else {
int available_count = 0;
if (skills && cJSON_IsArray(skills) && cJSON_GetArraySize(skills) > 0) {
int sn = cJSON_GetArraySize(skills);
for (int i = 0; i < sn; i++) {
cJSON* row = cJSON_GetArrayItem(skills, i);
cJSON* owner = row ? cJSON_GetObjectItemCaseSensitive(row, "owner") : NULL;
cJSON* d_tag = row ? cJSON_GetObjectItemCaseSensitive(row, "d_tag") : NULL;
cJSON* desc = row ? cJSON_GetObjectItemCaseSensitive(row, "description") : NULL;
const char* owner_s = (owner && cJSON_IsString(owner) && owner->valuestring) ? owner->valuestring : "";
const char* d_tag_s = (d_tag && cJSON_IsString(d_tag) && d_tag->valuestring) ? d_tag->valuestring : NULL;
const char* desc_s = (desc && cJSON_IsString(desc) && desc->valuestring) ? desc->valuestring : "";
if (!d_tag_s || d_tag_s[0] == '\0') {
if (strcmp(owner_s, "agent") != 0 || !d_tag_s || d_tag_s[0] == '\0') {
continue;
}
if (append_textf_local(&out, &cap, &used, "- %s%s%s\n", d_tag_s, desc_s[0] ? "" : "", desc_s) != 0) {
cJSON_Delete(skill_root);
free(skill_list_json);
free(out);
return NULL;
}
available_count++;
}
}
if (available_count <= 0) {
(void)append_textf_local(&out, &cap, &used, "- (none)\n");
}
cJSON_Delete(skill_root);
free(skill_list_json);
if (append_textf_local(&out, &cap, &used, "\nADOPTED SKILLS\n") != 0) {
free(out);
return NULL;
}
char* adopted_json = tools_execute(&g_tools_ctx, "adopted_skills", "{}");
cJSON* adopted_root = adopted_json ? cJSON_Parse(adopted_json) : NULL;
cJSON* adoption_events_content = adopted_root ? cJSON_GetObjectItemCaseSensitive(adopted_root, "content") : NULL;
cJSON* adoption_events_json = adopted_root ? cJSON_GetObjectItemCaseSensitive(adopted_root, "adoption_events_json") : NULL;
const char* adoption_events_text = NULL;
if (adoption_events_content && cJSON_IsString(adoption_events_content) && adoption_events_content->valuestring) {
adoption_events_text = adoption_events_content->valuestring;
} else if (adoption_events_json && cJSON_IsString(adoption_events_json) && adoption_events_json->valuestring) {
adoption_events_text = adoption_events_json->valuestring;
}
cJSON* adoption_events = adoption_events_text ? cJSON_Parse(adoption_events_text) : NULL;
int adopted_count = 0;
if (adoption_events && cJSON_IsArray(adoption_events) && cJSON_GetArraySize(adoption_events) > 0) {
cJSON* ev0 = cJSON_GetArrayItem(adoption_events, 0);
cJSON* tags = ev0 ? cJSON_GetObjectItemCaseSensitive(ev0, "tags") : NULL;
if (tags && cJSON_IsArray(tags)) {
int tn = cJSON_GetArraySize(tags);
for (int i = 0; i < tn; i++) {
cJSON* tag = cJSON_GetArrayItem(tags, i);
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) {
continue;
}
cJSON* k = cJSON_GetArrayItem(tag, 0);
cJSON* v = cJSON_GetArrayItem(tag, 1);
if (!k || !v || !cJSON_IsString(k) || !k->valuestring ||
!cJSON_IsString(v) || !v->valuestring) {
continue;
}
if (strcmp(k->valuestring, "a") != 0) {
continue;
}
const char* addr = v->valuestring;
const char* d_tag = strrchr(addr, ':');
const char* label = (d_tag && d_tag[1] != '\0') ? (d_tag + 1) : addr;
if (append_textf_local(&out, &cap, &used, "- %s\n", label) != 0) {
cJSON_Delete(adoption_events);
cJSON_Delete(adopted_root);
free(adopted_json);
free(out);
return NULL;
}
adopted_count++;
}
}
}
if (adopted_count <= 0) {
(void)append_textf_local(&out, &cap, &used, "- (none)\n");
}
cJSON_Delete(adoption_events);
cJSON_Delete(adopted_root);
free(adopted_json);
return out;
}
@@ -594,8 +741,11 @@ static int handle_slash_command(const char* sender_pubkey_hex, const char* messa
result_json = strdup("{\"success\":false,\"error\":\"direct tool execution failed\"}");
}
char* markdown_result = format_result_markdown_local(result_json);
const char* dm_payload = markdown_result ? markdown_result : result_json;
size_t tool_name_len = strlen(tool_name);
int send_raw_json = (tool_name_len >= 4U && strcmp(tool_name + tool_name_len - 4U, "_get") == 0);
char* markdown_result = send_raw_json ? NULL : format_result_markdown_local(result_json);
const char* dm_payload = send_raw_json ? result_json : (markdown_result ? markdown_result : result_json);
size_t log_cap = strlen(message) + strlen(result_json ? result_json : "") + strlen(dm_payload ? dm_payload : "") + 192U;
char* log_payload = (char*)malloc(log_cap);
@@ -1097,65 +1247,6 @@ void agent_append_context_log(const char* sender_pubkey_hex, const char* phase,
}
static int append_startup_events_context(cJSON* messages) {
if (!messages || !g_cfg || g_cfg->startup_event_count <= 0 || !g_cfg->startup_events) {
return 0;
}
cJSON* arr = cJSON_CreateArray();
if (!arr) {
return -1;
}
for (int i = 0; i < g_cfg->startup_event_count; i++) {
startup_event_t* se = &g_cfg->startup_events[i];
if (!se || se->kind == 31120) {
continue;
}
cJSON* item = cJSON_CreateObject();
if (!item) {
cJSON_Delete(arr);
return -1;
}
cJSON_AddNumberToObject(item, "kind", se->kind);
cJSON_AddStringToObject(item, "content", se->content ? se->content : "");
cJSON* tags = NULL;
if (se->tags_json) {
tags = cJSON_Parse(se->tags_json);
}
if (!tags || !cJSON_IsArray(tags)) {
cJSON_Delete(tags);
tags = cJSON_CreateArray();
}
cJSON_AddItemToObject(item, "tags", tags);
cJSON_AddItemToArray(arr, item);
}
char* events_json = cJSON_PrintUnformatted(arr);
cJSON_Delete(arr);
if (!events_json) {
return -1;
}
const char* prefix = "Startup events memory (source: config.startup_events; kind 31120 excluded): ";
size_t out_len = strlen(prefix) + strlen(events_json) + 1U;
char* payload = (char*)malloc(out_len);
if (!payload) {
free(events_json);
return -1;
}
snprintf(payload, out_len, "%s%s", prefix, events_json);
free(events_json);
int rc = append_simple_message(messages, "system", payload);
free(payload);
return rc;
}
static char* build_sender_verification_text(didactyl_sender_tier_t sender_tier) {
if (sender_tier == DIDACTYL_SENDER_ADMIN) {
return strdup("This message has been cryptographically verified as coming from your administrator.");
@@ -1166,196 +1257,6 @@ static char* build_sender_verification_text(didactyl_sender_tier_t sender_tier)
return strdup("Sender tier is unknown.");
}
static char* build_admin_profile_plain_text(void) {
char* kind0 = nostr_handler_get_admin_kind0_context();
if (!kind0 || kind0[0] == '\0') {
free(kind0);
return strdup("Administrator profile: unavailable.");
}
cJSON* root = cJSON_Parse(kind0);
if (!root || !cJSON_IsObject(root)) {
cJSON_Delete(root);
size_t n = strlen("Administrator profile raw JSON: ") + strlen(kind0) + 1U;
char* out = (char*)malloc(n);
if (!out) {
free(kind0);
return NULL;
}
snprintf(out, n, "Administrator profile raw JSON: %s", kind0);
free(kind0);
return out;
}
const char* name = "";
const char* display_name = "";
const char* about = "";
const char* website = "";
const char* picture = "";
cJSON* v = cJSON_GetObjectItemCaseSensitive(root, "name");
if (v && cJSON_IsString(v) && v->valuestring) name = v->valuestring;
v = cJSON_GetObjectItemCaseSensitive(root, "display_name");
if (v && cJSON_IsString(v) && v->valuestring) display_name = v->valuestring;
v = cJSON_GetObjectItemCaseSensitive(root, "about");
if (v && cJSON_IsString(v) && v->valuestring) about = v->valuestring;
v = cJSON_GetObjectItemCaseSensitive(root, "website");
if (v && cJSON_IsString(v) && v->valuestring) website = v->valuestring;
v = cJSON_GetObjectItemCaseSensitive(root, "picture");
if (v && cJSON_IsString(v) && v->valuestring) picture = v->valuestring;
const char* fmt = "Administrator profile: name=%s; display_name=%s; about=%s; website=%s; picture=%s";
int len = snprintf(NULL, 0, fmt, name, display_name, about, website, picture);
char* out = (char*)malloc((size_t)len + 1U);
if (out) {
snprintf(out, (size_t)len + 1U, fmt, name, display_name, about, website, picture);
}
cJSON_Delete(root);
free(kind0);
return out;
}
static char* build_admin_relay_list_plain_text(void) {
char* kind10002 = nostr_handler_get_admin_kind10002_context();
if (!kind10002 || kind10002[0] == '\0') {
free(kind10002);
return strdup("Administrator relay list: unavailable.");
}
cJSON* arr = cJSON_Parse(kind10002);
if (!arr || !cJSON_IsArray(arr)) {
cJSON_Delete(arr);
size_t n = strlen("Administrator relay list raw JSON: ") + strlen(kind10002) + 1U;
char* out = (char*)malloc(n);
if (!out) {
free(kind10002);
return NULL;
}
snprintf(out, n, "Administrator relay list raw JSON: %s", kind10002);
free(kind10002);
return out;
}
size_t cap = strlen("Administrator relay list: ") + strlen(kind10002) + 64U;
char* out = (char*)malloc(cap);
if (!out) {
cJSON_Delete(arr);
free(kind10002);
return NULL;
}
out[0] = '\0';
strcat(out, "Administrator relay list: ");
int n = cJSON_GetArraySize(arr);
int added = 0;
for (int i = 0; i < n; i++) {
cJSON* it = cJSON_GetArrayItem(arr, i);
if (!it || !cJSON_IsString(it) || !it->valuestring || it->valuestring[0] == '\0') continue;
if (added > 0) strcat(out, ", ");
strcat(out, it->valuestring);
added++;
}
if (added == 0) {
strcat(out, "none");
}
cJSON_Delete(arr);
free(kind10002);
return out;
}
static char* build_admin_recent_posts_text(void) {
char* notes = nostr_handler_get_admin_kind1_notes_context();
if (!notes || notes[0] == '\0') {
free(notes);
return strdup("Recent posts: unavailable.");
}
const char* prefix = "Administrator recent public notes:\n";
const char* body = notes;
if (strncmp(notes, prefix, strlen(prefix)) == 0) {
body = notes + strlen(prefix);
}
size_t n = strlen("Recent posts:\n") + strlen(body) + 1U;
char* out = (char*)malloc(n);
if (!out) {
free(notes);
return NULL;
}
snprintf(out, n, "Recent posts:\n%s", body);
free(notes);
return out;
}
static int append_admin_identity_context(cJSON* messages, didactyl_sender_tier_t sender_tier) {
if (!messages || !g_cfg) {
return -1;
}
char* sender_verification = build_sender_verification_text(sender_tier);
char* profile_plain = build_admin_profile_plain_text();
char* relay_plain = build_admin_relay_list_plain_text();
char* posts_plain = build_admin_recent_posts_text();
if (!sender_verification || !profile_plain || !relay_plain || !posts_plain) {
free(sender_verification);
free(profile_plain);
free(relay_plain);
free(posts_plain);
return -1;
}
const char* fmt =
"Sender verification: %s\n"
"Administrator pubkey (hex): %s\n"
"%s\n"
"%s\n"
"%s";
int len = snprintf(NULL,
0,
fmt,
sender_verification,
g_cfg->admin.pubkey[0] != '\0' ? g_cfg->admin.pubkey : "unknown",
profile_plain,
relay_plain,
posts_plain);
if (len < 0) {
free(sender_verification);
free(profile_plain);
free(relay_plain);
free(posts_plain);
return -1;
}
char* payload = (char*)malloc((size_t)len + 1U);
if (!payload) {
free(sender_verification);
free(profile_plain);
free(relay_plain);
free(posts_plain);
return -1;
}
snprintf(payload,
(size_t)len + 1U,
fmt,
sender_verification,
g_cfg->admin.pubkey[0] != '\0' ? g_cfg->admin.pubkey : "unknown",
profile_plain,
relay_plain,
posts_plain);
int rc = append_simple_message(messages, "system", payload);
free(payload);
free(sender_verification);
free(profile_plain);
free(relay_plain);
free(posts_plain);
return rc;
}
static int append_recent_admin_dm_history(cJSON* messages, const char* current_message) {
if (!messages || !g_cfg) {
@@ -1924,6 +1825,9 @@ void agent_on_trigger(const char* skill_d_tag,
return;
}
const char* prev_trigger_event_json = g_tools_ctx.template_trigger_event_json;
g_tools_ctx.template_trigger_event_json = event_json;
const char* relay = (relay_url && relay_url[0] != '\0') ? relay_url : "unknown";
const char* trigger_prefix =
@@ -1961,12 +1865,13 @@ void agent_on_trigger(const char* skill_d_tag,
}
snprintf(user_prompt, user_len, "Triggering event JSON:\n%s", event_json);
free(event_json);
char* tools_json = tools_build_openai_schema_json(&g_tools_ctx);
if (!tools_json) {
free(system_prompt);
free(user_prompt);
g_tools_ctx.template_trigger_event_json = prev_trigger_event_json;
free(event_json);
(void)nostr_handler_send_dm_auto(g_cfg->admin.pubkey, "Triggered skill execution failed: tools unavailable.");
return;
}
@@ -1979,6 +1884,8 @@ void agent_on_trigger(const char* skill_d_tag,
free(tools_json);
free(system_prompt);
free(user_prompt);
g_tools_ctx.template_trigger_event_json = prev_trigger_event_json;
free(event_json);
(void)nostr_handler_send_dm_auto(g_cfg->admin.pubkey, "Triggered skill execution failed: prompt initialization failed.");
return;
}
@@ -1987,9 +1894,14 @@ void agent_on_trigger(const char* skill_d_tag,
free(system_prompt);
free(user_prompt);
int max_turns = g_cfg->tools.max_turns > 0 ? g_cfg->tools.max_turns : 6;
int max_turns = g_cfg->tools.trigger_max_turns > 0
? g_cfg->tools.trigger_max_turns
: (g_cfg->tools.max_turns > 0 ? g_cfg->tools.max_turns : 8);
int turns_run = 0;
int trigger_completed = 0;
for (int turn = 0; turn < max_turns; turn++) {
turns_run = turn + 1;
char* messages_json = cJSON_PrintUnformatted(messages);
if (!messages_json) {
break;
@@ -2004,10 +1916,13 @@ void agent_on_trigger(const char* skill_d_tag,
(void)nostr_handler_send_dm_auto(g_cfg->admin.pubkey, "Triggered skill execution failed: LLM request failed.");
cJSON_Delete(messages);
free(tools_json);
g_tools_ctx.template_trigger_event_json = prev_trigger_event_json;
free(event_json);
return;
}
if (resp.tool_call_count <= 0) {
trigger_completed = 1;
llm_response_free(&resp);
break;
}
@@ -2031,6 +1946,8 @@ void agent_on_trigger(const char* skill_d_tag,
llm_response_free(&resp);
cJSON_Delete(messages);
free(tools_json);
g_tools_ctx.template_trigger_event_json = prev_trigger_event_json;
free(event_json);
(void)nostr_handler_send_dm_auto(g_cfg->admin.pubkey, "Triggered skill execution failed: tool result append failed.");
return;
}
@@ -2041,6 +1958,20 @@ void agent_on_trigger(const char* skill_d_tag,
llm_response_free(&resp);
}
if (!trigger_completed && turns_run >= max_turns) {
notify_admin_limit_diagnostic("trigger_skill_loop",
"max_turns_exhausted",
skill_d_tag,
max_turns,
turns_run,
g_cfg->tools.stall_repeat_threshold > 1 ? g_cfg->tools.stall_repeat_threshold : 3,
0,
g_cfg->llm.max_tokens,
NULL,
NULL,
"");
}
if (g_trigger_manager) {
(void)trigger_manager_fire_chains(g_trigger_manager,
skill_d_tag,
@@ -2050,6 +1981,8 @@ void agent_on_trigger(const char* skill_d_tag,
cJSON_Delete(messages);
free(tools_json);
g_tools_ctx.template_trigger_event_json = prev_trigger_event_json;
free(event_json);
}
int agent_build_admin_messages_json(const char* current_user_message,
@@ -2079,6 +2012,7 @@ int agent_build_admin_messages_json(const char* current_user_message,
g_tools_ctx.template_sender_tier = (int)sender_tier;
g_tools_ctx.template_current_user_message = current_user_message;
g_tools_ctx.template_trigger_event_json = NULL;
messages = prompt_template_build_messages(&g_prompt_template,
provider_name,
@@ -2091,6 +2025,7 @@ int agent_build_admin_messages_json(const char* current_user_message,
if (!messages) {
return -1;
}
} else {
messages = cJSON_CreateArray();
if (!messages) {
@@ -2108,8 +2043,6 @@ int agent_build_admin_messages_json(const char* current_user_message,
append_simple_message(messages, "system", g_system_context) != 0 ||
append_simple_message(messages, "system", agent_identity) != 0 ||
append_simple_message(messages, "system", sender_verification) != 0 ||
append_admin_identity_context(messages, sender_tier) != 0 ||
append_startup_events_context(messages) != 0 ||
append_adopted_skills_context(messages) != 0) {
free(sender_verification);
cJSON_Delete(messages);
@@ -2182,6 +2115,17 @@ void agent_on_message(const char* sender_pubkey_hex,
}
}
if (g_trigger_manager) {
int dm_fired = trigger_manager_fire_dm(g_trigger_manager,
sender_pubkey_hex,
message,
tier,
"dm");
if (dm_fired > 0) {
return;
}
}
if (!allow_tools) {
const char* tier_prefix = (tier == DIDACTYL_SENDER_WOT)
? "You are responding to a web-of-trust contact. Keep the response helpful and concise. Tool use is disabled for this tier."
@@ -2254,10 +2198,17 @@ void agent_on_message(const char* sender_pubkey_hex,
cJSON_AddNumberToObject(live_user_msg, "_ts", (double)time(NULL));
}
int max_turns = g_cfg->tools.max_turns > 0 ? g_cfg->tools.max_turns : 8;
int max_turns = g_cfg->tools.max_turns > 0 ? g_cfg->tools.max_turns : 20;
int stall_repeat_threshold = g_cfg->tools.stall_repeat_threshold > 1 ? g_cfg->tools.stall_repeat_threshold : 3;
uint64_t last_tool_fp = 0;
int repeated_tool_turns = 0;
int exited_on_stall = 0;
int stall_due_to_length = 0;
char* final_answer_owned = NULL;
int turns_run = 0;
for (int turn = 0; turn < max_turns; turn++) {
turns_run = turn + 1;
char* messages_json = cJSON_PrintUnformatted(messages);
if (!messages_json) {
break;
@@ -2285,6 +2236,21 @@ void agent_on_message(const char* sender_pubkey_hex,
break;
}
uint64_t current_tool_fp = tool_calls_fingerprint(&resp);
if (turn == 0 || current_tool_fp != last_tool_fp) {
repeated_tool_turns = 1;
last_tool_fp = current_tool_fp;
} else {
repeated_tool_turns++;
}
if (repeated_tool_turns >= stall_repeat_threshold) {
exited_on_stall = 1;
stall_due_to_length = (resp.finish_reason && strcmp(resp.finish_reason, "length") == 0) ? 1 : 0;
llm_response_free(&resp);
break;
}
if (append_assistant_tool_calls_message(messages, &resp) != 0) {
llm_response_free(&resp);
break;
@@ -2319,10 +2285,44 @@ void agent_on_message(const char* sender_pubkey_hex,
}
if (!final_answer_owned) {
final_answer_owned = strdup("I hit my tool-use limit for this request.");
char* messages_json = cJSON_PrintUnformatted(messages);
if (messages_json) {
llm_response_t final_resp;
int final_rc = llm_chat_with_tools_messages(messages_json, tools_json, "none", &final_resp);
free(messages_json);
if (final_rc == 0) {
const char* forced_answer = final_resp.content ? final_resp.content : "";
if (forced_answer[0] != '\0') {
final_answer_owned = strdup(forced_answer);
}
llm_response_free(&final_resp);
}
}
}
int exhausted_on_max_turns = (!final_answer_owned && !exited_on_stall && turns_run >= max_turns);
if (!final_answer_owned) {
final_answer_owned = strdup(exited_on_stall
? "I stopped repeated tool calls after detecting a loop and could not produce a final summary."
: "I hit my tool-use limit for this request.");
}
const char* final_answer = final_answer_owned ? final_answer_owned : "I hit my tool-use limit for this request.";
if (exited_on_stall || exhausted_on_max_turns) {
notify_admin_limit_diagnostic("dm_agent_loop",
exited_on_stall ? "stall_repetition_detected" : "max_turns_exhausted",
sender_pubkey_hex,
max_turns,
turns_run,
stall_repeat_threshold,
repeated_tool_turns,
g_cfg->llm.max_tokens,
(exited_on_stall && stall_due_to_length) ? "max_tokens_truncation" : NULL,
(exited_on_stall && stall_due_to_length) ? "Increase max_tokens (example: /model_set {\"max_tokens\": 4096})" : NULL,
final_answer);
}
fprintf(stdout, "[didactyl] final response: %.240s%s\n",
final_answer,
strlen(final_answer) > 240 ? "..." : "");
+1 -1
View File
@@ -4,7 +4,7 @@
#include "config.h"
#include "nostr_handler.h"
#include "cjson/cJSON.h"
#include "tools.h"
#include "tools/tools.h"
struct trigger_manager;
+1256
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
#ifndef DIDACTYL_CASHU_WALLET_H
#define DIDACTYL_CASHU_WALLET_H
#include <stdint.h>
#include "config.h"
#include "cjson/cJSON.h"
int cashu_wallet_init(didactyl_config_t* cfg);
void cashu_wallet_cleanup(void);
int cashu_wallet_load_from_relays(void);
int cashu_wallet_create_new_from_config(void);
int cashu_wallet_balance_json(cJSON** out_json);
int cashu_wallet_info_json(const char* mint_url, cJSON** out_json);
int cashu_wallet_mint_quote_json(const char* mint_url, uint64_t amount, const char* unit, cJSON** out_json);
int cashu_wallet_mint_check_json(const char* mint_url, const char* quote_id, cJSON** out_json);
int cashu_wallet_mint_claim_json(const char* mint_url, const char* quote_id, uint64_t amount, cJSON** out_json);
int cashu_wallet_melt_quote_json(const char* mint_url, const char* payment_request, const char* unit, cJSON** out_json);
int cashu_wallet_melt_pay_json(const char* mint_url, const char* quote_id, cJSON** out_json);
int cashu_wallet_check_proofs_json(const char* mint_url, cJSON** out_json);
int cashu_wallet_receive_token_json(const char* token_string, const char* mint_url, cJSON** out_json);
#endif
+538 -16
View File
@@ -222,12 +222,40 @@ static int parse_tools_config(cJSON* root, didactyl_config_t* config) {
cJSON* enabled = cJSON_GetObjectItemCaseSensitive(tools, "enabled");
cJSON* max_turns = cJSON_GetObjectItemCaseSensitive(tools, "max_turns");
cJSON* trigger_max_turns = cJSON_GetObjectItemCaseSensitive(tools, "trigger_max_turns");
cJSON* api_default_max_turns = cJSON_GetObjectItemCaseSensitive(tools, "api_default_max_turns");
cJSON* api_max_turns_ceiling = cJSON_GetObjectItemCaseSensitive(tools, "api_max_turns_ceiling");
cJSON* stall_repeat_threshold = cJSON_GetObjectItemCaseSensitive(tools, "stall_repeat_threshold");
cJSON* local_http_fetch_default_timeout_seconds =
cJSON_GetObjectItemCaseSensitive(tools, "local_http_fetch_default_timeout_seconds");
cJSON* local_http_fetch_max_timeout_seconds =
cJSON_GetObjectItemCaseSensitive(tools, "local_http_fetch_max_timeout_seconds");
if (enabled && cJSON_IsBool(enabled)) {
config->tools.enabled = cJSON_IsTrue(enabled) ? 1 : 0;
}
if (max_turns && cJSON_IsNumber(max_turns)) {
config->tools.max_turns = (int)max_turns->valuedouble;
}
if (trigger_max_turns && cJSON_IsNumber(trigger_max_turns)) {
config->tools.trigger_max_turns = (int)trigger_max_turns->valuedouble;
}
if (api_default_max_turns && cJSON_IsNumber(api_default_max_turns)) {
config->tools.api_default_max_turns = (int)api_default_max_turns->valuedouble;
}
if (api_max_turns_ceiling && cJSON_IsNumber(api_max_turns_ceiling)) {
config->tools.api_max_turns_ceiling = (int)api_max_turns_ceiling->valuedouble;
}
if (stall_repeat_threshold && cJSON_IsNumber(stall_repeat_threshold)) {
config->tools.stall_repeat_threshold = (int)stall_repeat_threshold->valuedouble;
}
if (local_http_fetch_default_timeout_seconds && cJSON_IsNumber(local_http_fetch_default_timeout_seconds)) {
config->tools.local_http_fetch_default_timeout_seconds =
(int)local_http_fetch_default_timeout_seconds->valuedouble;
}
if (local_http_fetch_max_timeout_seconds && cJSON_IsNumber(local_http_fetch_max_timeout_seconds)) {
config->tools.local_http_fetch_max_timeout_seconds =
(int)local_http_fetch_max_timeout_seconds->valuedouble;
}
cJSON* shell = cJSON_GetObjectItemCaseSensitive(tools, "shell");
if (!shell || !cJSON_IsObject(shell)) {
@@ -255,6 +283,34 @@ static int parse_tools_config(cJSON* root, didactyl_config_t* config) {
return -1;
}
if (config->tools.max_turns < 1) {
config->tools.max_turns = 8;
}
if (config->tools.trigger_max_turns < 1) {
config->tools.trigger_max_turns = config->tools.max_turns;
}
if (config->tools.api_default_max_turns < 1) {
config->tools.api_default_max_turns = config->tools.max_turns;
}
if (config->tools.api_max_turns_ceiling < 1) {
config->tools.api_max_turns_ceiling = 16;
}
if (config->tools.api_default_max_turns > config->tools.api_max_turns_ceiling) {
config->tools.api_default_max_turns = config->tools.api_max_turns_ceiling;
}
if (config->tools.stall_repeat_threshold < 2) {
config->tools.stall_repeat_threshold = 3;
}
if (config->tools.local_http_fetch_default_timeout_seconds < 1) {
config->tools.local_http_fetch_default_timeout_seconds = 20;
}
if (config->tools.local_http_fetch_max_timeout_seconds < 1) {
config->tools.local_http_fetch_max_timeout_seconds = 120;
}
if (config->tools.local_http_fetch_default_timeout_seconds > config->tools.local_http_fetch_max_timeout_seconds) {
config->tools.local_http_fetch_default_timeout_seconds = config->tools.local_http_fetch_max_timeout_seconds;
}
return 0;
}
@@ -458,6 +514,97 @@ static int parse_api_config(cJSON* root, didactyl_config_t* config) {
return 0;
}
static void free_cashu_wallet_mints(cashu_wallet_config_t* wallet) {
if (!wallet || !wallet->mint_urls) {
return;
}
for (int i = 0; i < wallet->mint_count; i++) {
free(wallet->mint_urls[i]);
}
free(wallet->mint_urls);
wallet->mint_urls = NULL;
wallet->mint_count = 0;
}
static int parse_cashu_wallet_config(cJSON* root, didactyl_config_t* config) {
cJSON* wallet = cJSON_GetObjectItemCaseSensitive(root, "cashu_wallet");
if (!wallet || !cJSON_IsObject(wallet)) {
return 0;
}
cJSON* enabled = cJSON_GetObjectItemCaseSensitive(wallet, "enabled");
if (enabled && cJSON_IsBool(enabled)) {
config->cashu_wallet.enabled = cJSON_IsTrue(enabled) ? 1 : 0;
}
cJSON* auto_load = cJSON_GetObjectItemCaseSensitive(wallet, "auto_load");
if (auto_load && cJSON_IsBool(auto_load)) {
config->cashu_wallet.auto_load = cJSON_IsTrue(auto_load) ? 1 : 0;
}
cJSON* timeout = cJSON_GetObjectItemCaseSensitive(wallet, "mint_timeout_seconds");
if (timeout && cJSON_IsNumber(timeout)) {
config->cashu_wallet.mint_timeout_seconds = (int)timeout->valuedouble;
}
if (copy_json_string(wallet,
"unit",
config->cashu_wallet.unit,
sizeof(config->cashu_wallet.unit),
0) != 0) {
return -1;
}
cJSON* mints = cJSON_GetObjectItemCaseSensitive(wallet, "mints");
if (mints) {
if (!cJSON_IsArray(mints)) {
return -1;
}
int count = cJSON_GetArraySize(mints);
char** urls = NULL;
if (count > 0) {
urls = (char**)calloc((size_t)count, sizeof(char*));
if (!urls) {
return -1;
}
}
for (int i = 0; i < count; i++) {
cJSON* item = cJSON_GetArrayItem(mints, i);
if (!item || !cJSON_IsString(item) || !item->valuestring || item->valuestring[0] == '\0') {
for (int j = 0; j < i; j++) {
free(urls[j]);
}
free(urls);
return -1;
}
urls[i] = strdup(item->valuestring);
if (!urls[i]) {
for (int j = 0; j < i; j++) {
free(urls[j]);
}
free(urls);
return -1;
}
}
free_cashu_wallet_mints(&config->cashu_wallet);
config->cashu_wallet.mint_urls = urls;
config->cashu_wallet.mint_count = count;
}
if (config->cashu_wallet.unit[0] == '\0') {
snprintf(config->cashu_wallet.unit, sizeof(config->cashu_wallet.unit), "%s", "sat");
}
if (config->cashu_wallet.mint_timeout_seconds < 1) {
config->cashu_wallet.mint_timeout_seconds = 30;
}
return 0;
}
static cJSON* find_tag_value_string(cJSON* tags, const char* tag_key) {
if (!tags || !cJSON_IsArray(tags) || !tag_key) {
return NULL;
@@ -567,6 +714,91 @@ static int normalize_skill_d_tag(int event_kind, cJSON* item, cJSON* tags) {
return set_tag_value_string(tags, "d", d_tag);
}
static int parse_default_skill_config(cJSON* root, didactyl_config_t* config) {
if (!root || !config) {
return -1;
}
cJSON* def = cJSON_GetObjectItemCaseSensitive(root, "default_skill");
if (!def || !cJSON_IsObject(def)) {
return 0;
}
cJSON* kind = cJSON_GetObjectItemCaseSensitive(def, "kind");
cJSON* d_tag = cJSON_GetObjectItemCaseSensitive(def, "d_tag");
cJSON* content = cJSON_GetObjectItemCaseSensitive(def, "content");
cJSON* content_fields = cJSON_GetObjectItemCaseSensitive(def, "content_fields");
cJSON* tags = cJSON_GetObjectItemCaseSensitive(def, "tags");
if (!kind || !cJSON_IsNumber(kind)) {
return -1;
}
int kind_i = (int)kind->valuedouble;
if (kind_i != 31123 && kind_i != 31124) {
return -1;
}
if (!d_tag || !cJSON_IsString(d_tag) || !d_tag->valuestring || d_tag->valuestring[0] == '\0') {
return -1;
}
if (strlen(d_tag->valuestring) >= sizeof(config->default_skill.d_tag)) {
return -1;
}
char* content_text = NULL;
if (content_fields) {
if (!cJSON_IsObject(content_fields)) {
return -1;
}
content_text = cJSON_PrintUnformatted(content_fields);
} else {
if (!content || !cJSON_IsString(content) || !content->valuestring) {
return -1;
}
content_text = strdup(content->valuestring);
}
if (!content_text) {
return -1;
}
cJSON* tags_work = NULL;
if (tags) {
if (!cJSON_IsArray(tags)) {
free(content_text);
return -1;
}
tags_work = cJSON_Duplicate(tags, 1);
} else {
tags_work = cJSON_CreateArray();
}
if (!tags_work || !cJSON_IsArray(tags_work)) {
cJSON_Delete(tags_work);
free(content_text);
return -1;
}
if (set_tag_value_string(tags_work, "d", d_tag->valuestring) != 0) {
cJSON_Delete(tags_work);
free(content_text);
return -1;
}
char* tags_json = cJSON_PrintUnformatted(tags_work);
cJSON_Delete(tags_work);
if (!tags_json) {
free(content_text);
return -1;
}
free(config->default_skill.content);
free(config->default_skill.tags_json);
config->default_skill.kind = kind_i;
snprintf(config->default_skill.d_tag, sizeof(config->default_skill.d_tag), "%s", d_tag->valuestring);
config->default_skill.content = content_text;
config->default_skill.tags_json = tags_json;
return 0;
}
static int parse_startup_events(cJSON* root, didactyl_config_t* config) {
cJSON* arr = cJSON_GetObjectItemCaseSensitive(root, "startup_events");
if (!arr || !cJSON_IsArray(arr)) {
@@ -704,9 +936,251 @@ static int parse_relays_from_startup_kind10002(didactyl_config_t* config) {
return -1;
}
static int set_default_bootstrap_relays(didactyl_config_t* config) {
if (!config) {
return -1;
}
static const char* defaults[] = {
"wss://relay.damus.io",
"wss://relay.primal.net",
"wss://nos.lol"
};
const int relay_count = (int)(sizeof(defaults) / sizeof(defaults[0]));
char** relays = (char**)calloc((size_t)relay_count, sizeof(char*));
if (!relays) {
return -1;
}
for (int i = 0; i < relay_count; i++) {
relays[i] = strdup(defaults[i]);
if (!relays[i]) {
for (int j = 0; j < i; j++) {
free(relays[j]);
}
free(relays);
return -1;
}
}
if (config->relays) {
for (int i = 0; i < config->relay_count; i++) {
free(config->relays[i]);
}
free(config->relays);
}
config->relays = relays;
config->relay_count = relay_count;
return 0;
}
static int parse_relays(cJSON* root, didactyl_config_t* config) {
(void)root;
return parse_relays_from_startup_kind10002(config);
if (parse_relays_from_startup_kind10002(config) == 0) {
return 0;
}
return set_default_bootstrap_relays(config);
}
static int startup_event_has_d_tag(const startup_event_t* se, const char* d_tag) {
if (!se || !se->tags_json || !d_tag || d_tag[0] == '\0') {
return 0;
}
cJSON* tags = cJSON_Parse(se->tags_json);
if (!tags || !cJSON_IsArray(tags)) {
cJSON_Delete(tags);
return 0;
}
int found = 0;
int n = cJSON_GetArraySize(tags);
for (int i = 0; i < n; i++) {
cJSON* tag = cJSON_GetArrayItem(tags, i);
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) continue;
cJSON* k = cJSON_GetArrayItem(tag, 0);
cJSON* v = cJSON_GetArrayItem(tag, 1);
if (!k || !v || !cJSON_IsString(k) || !cJSON_IsString(v) || !k->valuestring || !v->valuestring) continue;
if (strcmp(k->valuestring, "d") == 0 && strcmp(v->valuestring, d_tag) == 0) {
found = 1;
break;
}
}
cJSON_Delete(tags);
return found;
}
static int adoption_tags_has_addr(cJSON* tags, const char* addr) {
if (!tags || !cJSON_IsArray(tags) || !addr || addr[0] == '\0') {
return 0;
}
int n = cJSON_GetArraySize(tags);
for (int i = 0; i < n; i++) {
cJSON* tag = cJSON_GetArrayItem(tags, i);
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) continue;
cJSON* k = cJSON_GetArrayItem(tag, 0);
cJSON* v = cJSON_GetArrayItem(tag, 1);
if (!k || !v || !cJSON_IsString(k) || !cJSON_IsString(v) || !k->valuestring || !v->valuestring) continue;
if (strcmp(k->valuestring, "a") == 0 && strcmp(v->valuestring, addr) == 0) {
return 1;
}
}
return 0;
}
static int append_adoption_addr_tag(cJSON* tags, const char* addr) {
if (!tags || !cJSON_IsArray(tags) || !addr || addr[0] == '\0') {
return -1;
}
cJSON* tag = cJSON_CreateArray();
if (!tag) return -1;
cJSON_AddItemToArray(tag, cJSON_CreateString("a"));
cJSON_AddItemToArray(tag, cJSON_CreateString(addr));
cJSON_AddItemToArray(tags, tag);
return 0;
}
static int append_startup_event(didactyl_config_t* config, int kind, const char* content, const char* tags_json) {
if (!config || !content) {
return -1;
}
int old_count = config->startup_event_count;
startup_event_t* grown = (startup_event_t*)realloc(config->startup_events, (size_t)(old_count + 1) * sizeof(startup_event_t));
if (!grown) {
return -1;
}
config->startup_events = grown;
memset(&config->startup_events[old_count], 0, sizeof(startup_event_t));
config->startup_events[old_count].kind = kind;
config->startup_events[old_count].content = strdup(content);
if (!config->startup_events[old_count].content) {
return -1;
}
if (tags_json && tags_json[0] != '\0') {
config->startup_events[old_count].tags_json = strdup(tags_json);
if (!config->startup_events[old_count].tags_json) {
free(config->startup_events[old_count].content);
config->startup_events[old_count].content = NULL;
return -1;
}
}
config->startup_event_count = old_count + 1;
return 0;
}
int config_ensure_default_skill_startup_events(didactyl_config_t* config) {
if (!config || !config->default_skill.content || config->default_skill.content[0] == '\0' ||
config->default_skill.d_tag[0] == '\0') {
return 0;
}
int has_default_skill_event = 0;
for (int i = 0; i < config->startup_event_count; i++) {
startup_event_t* se = &config->startup_events[i];
if (se->kind == config->default_skill.kind && startup_event_has_d_tag(se, config->default_skill.d_tag)) {
has_default_skill_event = 1;
break;
}
}
if (!has_default_skill_event) {
if (append_startup_event(config,
config->default_skill.kind,
config->default_skill.content,
config->default_skill.tags_json ? config->default_skill.tags_json : "[]") != 0) {
return -1;
}
}
if (config->keys.public_key_hex[0] == '\0') {
return 0;
}
char addr[256];
snprintf(addr,
sizeof(addr),
"%d:%s:%s",
config->default_skill.kind,
config->keys.public_key_hex,
config->default_skill.d_tag);
for (int i = 0; i < config->startup_event_count; i++) {
startup_event_t* se = &config->startup_events[i];
if (se->kind != 10123 || !se->tags_json) {
continue;
}
cJSON* tags = cJSON_Parse(se->tags_json);
if (!tags || !cJSON_IsArray(tags)) {
cJSON_Delete(tags);
continue;
}
if (adoption_tags_has_addr(tags, addr)) {
cJSON_Delete(tags);
return 0;
}
if (append_adoption_addr_tag(tags, addr) != 0) {
cJSON_Delete(tags);
return -1;
}
char* updated = cJSON_PrintUnformatted(tags);
cJSON_Delete(tags);
if (!updated) {
return -1;
}
free(se->tags_json);
se->tags_json = updated;
return 0;
}
cJSON* tags = cJSON_CreateArray();
if (!tags) {
return -1;
}
if (append_adoption_addr_tag(tags, addr) != 0) {
cJSON_Delete(tags);
return -1;
}
cJSON* app = cJSON_CreateArray();
cJSON* scope = cJSON_CreateArray();
if (!app || !scope) {
cJSON_Delete(app);
cJSON_Delete(scope);
cJSON_Delete(tags);
return -1;
}
cJSON_AddItemToArray(app, cJSON_CreateString("app"));
cJSON_AddItemToArray(app, cJSON_CreateString("didactyl"));
cJSON_AddItemToArray(scope, cJSON_CreateString("scope"));
cJSON_AddItemToArray(scope, cJSON_CreateString(config->default_skill.kind == 31124 ? "private" : "public"));
cJSON_AddItemToArray(tags, app);
cJSON_AddItemToArray(tags, scope);
char* tags_json = cJSON_PrintUnformatted(tags);
cJSON_Delete(tags);
if (!tags_json) {
return -1;
}
int rc = append_startup_event(config, 10123, "", tags_json);
free(tags_json);
return rc;
}
void config_free(didactyl_config_t* config) {
@@ -729,6 +1203,11 @@ void config_free(didactyl_config_t* config) {
free(config->startup_events);
}
free(config->default_skill.content);
free(config->default_skill.tags_json);
free_cashu_wallet_mints(&config->cashu_wallet);
memset(config, 0, sizeof(*config));
}
@@ -745,7 +1224,13 @@ int config_load(const char* path, didactyl_config_t* config) {
config->dm_protocol = DM_PROTOCOL_NIP04;
config->tools.enabled = 1;
config->tools.max_turns = 8;
config->tools.max_turns = 20;
config->tools.trigger_max_turns = 12;
config->tools.api_default_max_turns = 8;
config->tools.api_max_turns_ceiling = 32;
config->tools.stall_repeat_threshold = 3;
config->tools.local_http_fetch_default_timeout_seconds = 20;
config->tools.local_http_fetch_max_timeout_seconds = 120;
config->tools.shell.enabled = 1;
config->tools.shell.timeout_seconds = 30;
config->tools.shell.max_output_bytes = 65536;
@@ -777,9 +1262,28 @@ int config_load(const char* path, didactyl_config_t* config) {
config->api.port = 8484;
snprintf(config->api.bind_address, sizeof(config->api.bind_address), "%s", "127.0.0.1");
config->default_skill.kind = 31124;
config->default_skill.d_tag[0] = '\0';
config->default_skill.content = NULL;
config->default_skill.tags_json = NULL;
config->cashu_wallet.enabled = 0;
config->cashu_wallet.mint_urls = NULL;
config->cashu_wallet.mint_count = 0;
snprintf(config->cashu_wallet.unit, sizeof(config->cashu_wallet.unit), "%s", "sat");
config->cashu_wallet.auto_load = 1;
config->cashu_wallet.mint_timeout_seconds = 30;
char* raw_buf = NULL;
size_t raw_len = 0;
if (read_file_to_buffer(path, &raw_buf, &raw_len) != 0) {
if (errno == ENOENT) {
if (set_default_bootstrap_relays(config) != 0) {
config_set_error("failed to initialize default bootstrap relays");
return -1;
}
return 0;
}
config_set_error("failed to read config file '%s': %s", path, strerror(errno));
return -1;
}
@@ -808,19 +1312,25 @@ int config_load(const char* path, didactyl_config_t* config) {
int rc = -1;
cJSON* keys = cJSON_GetObjectItemCaseSensitive(root, "keys");
if (!keys || !cJSON_IsObject(keys)) {
keys = cJSON_GetObjectItemCaseSensitive(root, "key");
}
cJSON* admin = cJSON_GetObjectItemCaseSensitive(root, "admin");
cJSON* llm = cJSON_GetObjectItemCaseSensitive(root, "llm");
if (!keys || !cJSON_IsObject(keys) ||
!admin || !cJSON_IsObject(admin) ||
if (!admin || !cJSON_IsObject(admin) ||
!llm || !cJSON_IsObject(llm)) {
config_set_error("config must include object sections: keys, admin, llm");
config_set_error("config must include object sections: admin, llm");
goto cleanup;
}
if (copy_json_string(keys, "nsec", config->keys.nsec, sizeof(config->keys.nsec), 1) != 0) {
config_set_error("keys.nsec is required and must be a non-empty string");
goto cleanup;
if (!keys || !cJSON_IsObject(keys)) {
config->keys.nsec[0] = '\0';
} else {
if (copy_json_string(keys, "nsec", config->keys.nsec, sizeof(config->keys.nsec), 0) != 0) {
config_set_error("keys.nsec/key.nsec must be a string when provided");
goto cleanup;
}
}
char admin_key_raw[OW_MAX_KEY_LEN] = {0};
@@ -838,8 +1348,13 @@ int config_load(const char* path, didactyl_config_t* config) {
goto cleanup;
}
if (parse_default_skill_config(root, config) != 0) {
config_set_error("invalid default_skill configuration");
goto cleanup;
}
if (parse_relays(root, config) != 0) {
config_set_error("relay configuration is invalid: startup_events must include kind 10002 with non-empty r tags");
config_set_error("relay configuration is invalid and bootstrap fallback failed");
goto cleanup;
}
@@ -900,17 +1415,24 @@ int config_load(const char* path, didactyl_config_t* config) {
goto cleanup;
}
if (decode_private_key(config->keys.nsec, config->keys.private_key) != 0) {
config_set_error("keys.nsec must be valid nsec1... or 64-char hex private key");
if (parse_cashu_wallet_config(root, config) != 0) {
config_set_error("invalid cashu_wallet configuration");
goto cleanup;
}
if (nostr_ec_public_key_from_private_key(config->keys.private_key, config->keys.public_key) != 0) {
config_set_error("failed to derive public key from keys.nsec");
goto cleanup;
}
if (config->keys.nsec[0] != '\0') {
if (decode_private_key(config->keys.nsec, config->keys.private_key) != 0) {
config_set_error("keys.nsec/key.nsec must be valid nsec1... or 64-char hex private key");
goto cleanup;
}
nostr_bytes_to_hex(config->keys.public_key, 32, config->keys.public_key_hex);
if (nostr_ec_public_key_from_private_key(config->keys.private_key, config->keys.public_key) != 0) {
config_set_error("failed to derive public key from keys.nsec/key.nsec");
goto cleanup;
}
nostr_bytes_to_hex(config->keys.public_key, 32, config->keys.public_key_hex);
}
rc = 0;
+25
View File
@@ -47,6 +47,12 @@ typedef struct {
typedef struct {
int enabled;
int max_turns;
int trigger_max_turns;
int api_default_max_turns;
int api_max_turns_ceiling;
int stall_repeat_threshold;
int local_http_fetch_default_timeout_seconds;
int local_http_fetch_max_timeout_seconds;
shell_tools_config_t shell;
} tools_config_t;
@@ -56,6 +62,13 @@ typedef struct {
char* tags_json; // JSON array string for tags, optional
} startup_event_t;
typedef struct {
int kind;
char d_tag[65];
char* content;
char* tags_json;
} default_skill_config_t;
typedef struct {
int enabled;
int tools_enabled;
@@ -92,6 +105,15 @@ typedef struct {
char bind_address[OW_MAX_URL_LEN];
} api_config_t;
typedef struct {
int enabled;
char** mint_urls;
int mint_count;
char unit[16];
int auto_load;
int mint_timeout_seconds;
} cashu_wallet_config_t;
typedef struct {
agent_keys_t keys;
admin_config_t admin;
@@ -104,12 +126,15 @@ typedef struct {
admin_context_config_t admin_context;
triggers_config_t triggers;
api_config_t api;
cashu_wallet_config_t cashu_wallet;
startup_event_t* startup_events;
int startup_event_count;
default_skill_config_t default_skill;
char config_path[OW_MAX_URL_LEN];
} didactyl_config_t;
int config_load(const char* path, didactyl_config_t* config);
int config_ensure_default_skill_startup_events(didactyl_config_t* config);
const char* config_last_error(void);
void config_free(didactyl_config_t* config);
+34
View File
@@ -1,14 +1,31 @@
#include "debug.h"
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
debug_level_t g_debug_level = DEBUG_LEVEL_NONE;
static FILE* g_debug_file = NULL;
static void debug_open_log_file(void) {
if (g_debug_file) return;
const char* path = getenv("DIDACTYL_LOG_FILE");
if (!path || path[0] == '\0') {
path = "debug.log";
}
g_debug_file = fopen(path, "a");
if (g_debug_file) {
setvbuf(g_debug_file, NULL, _IOLBF, 0);
}
}
void debug_init(int level) {
if (level < 0) level = 0;
if (level > 5) level = 5;
g_debug_level = (debug_level_t)level;
debug_open_log_file();
}
void debug_log(debug_level_t level, const char* file, int line, const char* format, ...) {
@@ -28,11 +45,17 @@ void debug_log(debug_level_t level, const char* file, int line, const char* form
}
printf("[%s] [%s] ", timestamp, level_str);
if (g_debug_file) {
fprintf(g_debug_file, "[%s] [%s] ", timestamp, level_str);
}
if (file && g_debug_level >= DEBUG_LEVEL_TRACE) {
const char* filename = strrchr(file, '/');
filename = filename ? filename + 1 : file;
printf("[%s:%d] ", filename, line);
if (g_debug_file) {
fprintf(g_debug_file, "[%s:%d] ", filename, line);
}
}
va_list args;
@@ -40,6 +63,17 @@ void debug_log(debug_level_t level, const char* file, int line, const char* form
vprintf(format, args);
va_end(args);
if (g_debug_file) {
va_list args_file;
va_start(args_file, format);
vfprintf(g_debug_file, format, args_file);
va_end(args_file);
}
printf("\n");
fflush(stdout);
if (g_debug_file) {
fprintf(g_debug_file, "\n");
fflush(g_debug_file);
}
}
+113
View File
@@ -0,0 +1,113 @@
#ifndef DIDACTYL_DEFAULT_EVENTS_H
#define DIDACTYL_DEFAULT_EVENTS_H
#define DIDACTYL_DEFAULT_SKILL_D_TAG "didactyl-default"
#define DIDACTYL_DEFAULT_SKILL_KIND 31124
#define DIDACTYL_DEFAULT_SKILL_TAGS_JSON "[[\"d\",\"didactyl-default\"],[\"app\",\"didactyl\"],[\"scope\",\"private\"]]"
#define DIDACTYL_STARTUP_KIND_PROFILE 0
#define DIDACTYL_STARTUP_KIND_CONTACTS 3
#define DIDACTYL_STARTUP_KIND_RELAYS 10002
static const int DIDACTYL_DEFAULT_STARTUP_EVENT_KINDS[] = {
DIDACTYL_STARTUP_KIND_PROFILE,
DIDACTYL_STARTUP_KIND_CONTACTS,
DIDACTYL_STARTUP_KIND_RELAYS
};
#define DIDACTYL_DEFAULT_STARTUP_EVENT_KIND_COUNT ((int)(sizeof(DIDACTYL_DEFAULT_STARTUP_EVENT_KINDS) / sizeof(DIDACTYL_DEFAULT_STARTUP_EVENT_KINDS[0])))
#define DIDACTYL_DEFAULT_KIND0_PROFILE_JSON_TEMPLATE "{\"name\":\"%s\",\"display_name\":\"%s\"}"
#define DIDACTYL_DEFAULT_KIND3_CONTENT ""
#define DIDACTYL_DEFAULT_KIND3_TAGS_JSON_TEMPLATE "[[\"p\",\"%s\"]]"
#define DIDACTYL_DEFAULT_KIND10002_CONTENT ""
static const char* DIDACTYL_DEFAULT_RELAYS[] = {
"wss://relay.damus.io",
"wss://nos.lol",
"wss://relay.primal.net"
};
#define DIDACTYL_DEFAULT_RELAY_COUNT ((int)(sizeof(DIDACTYL_DEFAULT_RELAYS) / sizeof(DIDACTYL_DEFAULT_RELAYS[0])))
static const char* DIDACTYL_DEFAULT_SKILL_TEMPLATE =
"# %s Agent\n\n"
"You are %s, a sovereign AI agent living on Nostr.\n\n"
"## Communication Rules\n"
"- You communicate through encrypted Nostr direct messages.\n"
"- Keep responses concise and clear.\n\n"
"## Behavior\n"
"- Be helpful and technically accurate.\n"
"- If unsure, state uncertainty directly.\n"
"- Prefer actionable, practical advice.\n"
"- Use the person's name when messaging them if you know it.\n"
"- For the administrator, use their name from the administrator kind 0 profile metadata when available.\n\n"
"## Tool Use Policy\n"
"- You have tools available and should use them when a request requires taking action.\n"
"- For requests involving local inspection or command execution, call `local_shell_exec` instead of refusing.\n"
"- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.\n"
"- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.\n"
"- After a tool call, base your answer on the actual tool result.\n"
"- Never claim a tool was run if no tool was executed.\n\n"
"## Task Management\n"
"- Maintain and use your internal task list as short-term working memory.\n"
"- Break long or complex actions into clear tasks before executing them.\n"
"- Update task status as you complete steps so your plan stays accurate.\n\n"
"## Safety\n"
"- Do not claim to have executed actions you did not execute.\n"
"- You may share your public key (npub) with anyone.\n"
"- Never reveal your private key (nsec) under any circumstance.\n\n"
"---template---\n\n"
"- section: admin_identity\n"
" role: system\n"
" tool: admin_identity\n"
" skip_if_empty: true\n\n"
"- section: admin_profile\n"
" role: system\n"
" tool: nostr_admin_profile\n"
" skip_if_empty: true\n\n"
"- section: admin_contacts\n"
" role: system\n"
" tool: nostr_admin_contacts\n"
" skip_if_empty: true\n\n"
"- section: admin_relays\n"
" role: system\n"
" tool: nostr_admin_relays\n"
" skip_if_empty: true\n\n"
"- section: admin_notes\n"
" role: system\n"
" tool: nostr_admin_notes\n"
" skip_if_empty: true\n\n"
"- section: agent_identity\n"
" role: system\n"
" tool: agent_identity\n"
" skip_if_empty: true\n\n"
"- section: agent_profile\n"
" role: system\n"
" tool: nostr_agent_profile\n"
" skip_if_empty: true\n\n"
"- section: agent_contacts\n"
" role: system\n"
" tool: nostr_agent_contacts\n"
" skip_if_empty: true\n\n"
"- section: agent_relays\n"
" role: system\n"
" tool: nostr_agent_relays\n"
" skip_if_empty: true\n\n"
"- section: agent_notes\n"
" role: system\n"
" tool: nostr_agent_notes\n"
" skip_if_empty: true\n\n"
"- section: tasks\n"
" role: system\n"
" tool: task_list\n"
" skip_if_empty: true\n\n"
"- section: dm_history\n"
" role: expand\n"
" limit: 12\n\n"
"- section: conversation\n"
" role: user\n"
" tool: message_current\n"
" skip_if_empty: true\n";
#endif
+228 -8
View File
@@ -5,6 +5,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include "agent.h"
@@ -12,7 +13,7 @@
#include "main.h"
#include "nostr_handler.h"
#include "trigger_manager.h"
#include "tools.h"
#include "tools/tools.h"
#include "cjson/cJSON.h"
#include "debug.h"
#include "mongoose.h"
@@ -81,6 +82,82 @@ static int estimate_tokens_from_chars(int chars) {
return (chars + 3) / 4;
}
static uint64_t fnv1a64_local(const char* s) {
uint64_t h = 1469598103934665603ULL;
if (!s) return h;
while (*s) {
h ^= (unsigned char)(*s++);
h *= 1099511628211ULL;
}
return h;
}
static uint64_t tool_calls_fingerprint_local(const llm_response_t* resp) {
if (!resp || resp->tool_call_count <= 0 || !resp->tool_calls) {
return 1469598103934665603ULL;
}
uint64_t h = 1469598103934665603ULL;
for (int i = 0; i < resp->tool_call_count; i++) {
const llm_tool_call_t* tc = &resp->tool_calls[i];
uint64_t name_h = fnv1a64_local(tc->name ? tc->name : "");
uint64_t args_h = fnv1a64_local(tc->arguments_json ? tc->arguments_json : "{}");
uint64_t part = name_h ^ (args_h + 0x9e3779b97f4a7c15ULL + (name_h << 6) + (name_h >> 2));
h ^= part + (uint64_t)(i + 1) * 1099511628211ULL;
h *= 1099511628211ULL;
}
h ^= (uint64_t)resp->tool_call_count;
h *= 1099511628211ULL;
return h;
}
static void notify_admin_limit_diagnostic_http(const char* source,
const char* reason,
const char* subject,
int max_turns,
int turns_run,
int stall_repeat_threshold,
int repeated_tool_turns,
int current_max_tokens,
const char* possible_cause,
const char* hint,
const char* final_answer) {
if (!g_api_ctx.cfg || g_api_ctx.cfg->admin.pubkey[0] == '\0') {
return;
}
char diag[1800];
snprintf(diag,
sizeof(diag),
"⚠️ Didactyl limit diagnostic\n"
"source=%s\n"
"reason=%s\n"
"subject=%s\n"
"max_turns=%d\n"
"turns_run=%d\n"
"stall_repeat_threshold=%d\n"
"repeated_tool_turns=%d\n"
"current_max_tokens=%d\n"
"possible_cause=%s\n"
"hint=%s\n"
"final_answer_preview=%.*s",
source ? source : "unknown",
reason ? reason : "unknown",
subject ? subject : "n/a",
max_turns,
turns_run,
stall_repeat_threshold,
repeated_tool_turns,
current_max_tokens,
possible_cause ? possible_cause : "n/a",
hint ? hint : "n/a",
360,
final_answer ? final_answer : "");
(void)nostr_handler_send_dm_auto(g_api_ctx.cfg->admin.pubkey, diag);
}
static int uri_extract_after_prefix(const struct mg_str* uri,
const char* prefix,
char* out,
@@ -609,30 +686,102 @@ static char* build_slash_help_all_json_local(void) {
cJSON* skill_root = skill_list_json ? cJSON_Parse(skill_list_json) : NULL;
cJSON* skills = skill_root ? cJSON_GetObjectItemCaseSensitive(skill_root, "skills") : NULL;
if (!skills || !cJSON_IsArray(skills) || cJSON_GetArraySize(skills) <= 0) {
(void)append_textf_http(&out, &cap, &used, "- (none)\n");
} else {
int available_count = 0;
if (skills && cJSON_IsArray(skills) && cJSON_GetArraySize(skills) > 0) {
int sn = cJSON_GetArraySize(skills);
for (int i = 0; i < sn; i++) {
cJSON* row = cJSON_GetArrayItem(skills, i);
cJSON* owner = row ? cJSON_GetObjectItemCaseSensitive(row, "owner") : NULL;
cJSON* d_tag = row ? cJSON_GetObjectItemCaseSensitive(row, "d_tag") : NULL;
cJSON* desc = row ? cJSON_GetObjectItemCaseSensitive(row, "description") : NULL;
const char* owner_s = (owner && cJSON_IsString(owner) && owner->valuestring) ? owner->valuestring : "";
const char* d_tag_s = (d_tag && cJSON_IsString(d_tag) && d_tag->valuestring) ? d_tag->valuestring : NULL;
const char* desc_s = (desc && cJSON_IsString(desc) && desc->valuestring) ? desc->valuestring : "";
if (!d_tag_s || d_tag_s[0] == '\0') {
if (strcmp(owner_s, "agent") != 0 || !d_tag_s || d_tag_s[0] == '\0') {
continue;
}
if (append_textf_http(&out, &cap, &used, "- %s%s%s\n", d_tag_s, desc_s[0] ? "" : "", desc_s) != 0) {
cJSON_Delete(skill_root);
free(skill_list_json);
free(out);
return NULL;
}
available_count++;
}
}
if (available_count <= 0) {
(void)append_textf_http(&out, &cap, &used, "- (none)\n");
}
cJSON_Delete(skill_root);
free(skill_list_json);
if (append_textf_http(&out, &cap, &used, "\nADOPTED SKILLS\n") != 0) {
free(out);
return NULL;
}
char* adopted_json = tools_execute(g_api_ctx.tools_ctx, "adopted_skills", "{}");
cJSON* adopted_root = adopted_json ? cJSON_Parse(adopted_json) : NULL;
cJSON* adoption_events_content = adopted_root ? cJSON_GetObjectItemCaseSensitive(adopted_root, "content") : NULL;
cJSON* adoption_events_json = adopted_root ? cJSON_GetObjectItemCaseSensitive(adopted_root, "adoption_events_json") : NULL;
const char* adoption_events_text = NULL;
if (adoption_events_content && cJSON_IsString(adoption_events_content) && adoption_events_content->valuestring) {
adoption_events_text = adoption_events_content->valuestring;
} else if (adoption_events_json && cJSON_IsString(adoption_events_json) && adoption_events_json->valuestring) {
adoption_events_text = adoption_events_json->valuestring;
}
cJSON* adoption_events = adoption_events_text ? cJSON_Parse(adoption_events_text) : NULL;
int adopted_count = 0;
if (adoption_events && cJSON_IsArray(adoption_events) && cJSON_GetArraySize(adoption_events) > 0) {
cJSON* ev0 = cJSON_GetArrayItem(adoption_events, 0);
cJSON* tags = ev0 ? cJSON_GetObjectItemCaseSensitive(ev0, "tags") : NULL;
if (tags && cJSON_IsArray(tags)) {
int tn = cJSON_GetArraySize(tags);
for (int i = 0; i < tn; i++) {
cJSON* tag = cJSON_GetArrayItem(tags, i);
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) {
continue;
}
cJSON* k = cJSON_GetArrayItem(tag, 0);
cJSON* v = cJSON_GetArrayItem(tag, 1);
if (!k || !v || !cJSON_IsString(k) || !k->valuestring ||
!cJSON_IsString(v) || !v->valuestring) {
continue;
}
if (strcmp(k->valuestring, "a") != 0) {
continue;
}
const char* addr = v->valuestring;
const char* d_tag = strrchr(addr, ':');
const char* label = (d_tag && d_tag[1] != '\0') ? (d_tag + 1) : addr;
if (append_textf_http(&out, &cap, &used, "- %s\n", label) != 0) {
cJSON_Delete(adoption_events);
cJSON_Delete(adopted_root);
free(adopted_json);
free(out);
return NULL;
}
adopted_count++;
}
}
}
if (adopted_count <= 0) {
(void)append_textf_http(&out, &cap, &used, "- (none)\n");
}
cJSON_Delete(adoption_events);
cJSON_Delete(adopted_root);
free(adopted_json);
return out;
}
@@ -755,8 +904,13 @@ static cJSON* run_prompt_with_tools_convo(cJSON* convo,
const char* tool_limit_message) {
if (!convo || !cJSON_IsArray(convo)) return NULL;
int max_ceiling = 16;
if (g_api_ctx.cfg && g_api_ctx.cfg->tools.api_max_turns_ceiling > 0) {
max_ceiling = g_api_ctx.cfg->tools.api_max_turns_ceiling;
}
if (max_turns < 1) max_turns = 1;
if (max_turns > 16) max_turns = 16;
if (max_turns > max_ceiling) max_turns = max_ceiling;
char* tools_json = tools_build_openai_schema_json(g_api_ctx.tools_ctx);
if (!tools_json) {
@@ -772,9 +926,20 @@ static cJSON* run_prompt_with_tools_convo(cJSON* convo,
return NULL;
}
int stall_repeat_threshold = 3;
if (g_api_ctx.cfg && g_api_ctx.cfg->tools.stall_repeat_threshold > 1) {
stall_repeat_threshold = g_api_ctx.cfg->tools.stall_repeat_threshold;
}
char* final_response = NULL;
uint64_t last_tool_fp = 0;
int repeated_tool_turns = 0;
int exited_on_stall = 0;
int stall_due_to_length = 0;
int turns_run = 0;
for (int turn = 0; turn < max_turns; turn++) {
turns_run = turn + 1;
char* messages_json = cJSON_PrintUnformatted(convo);
if (!messages_json) break;
@@ -805,6 +970,21 @@ static cJSON* run_prompt_with_tools_convo(cJSON* convo,
break;
}
uint64_t current_tool_fp = tool_calls_fingerprint_local(&resp);
if (turn == 0 || current_tool_fp != last_tool_fp) {
repeated_tool_turns = 1;
last_tool_fp = current_tool_fp;
} else {
repeated_tool_turns++;
}
if (repeated_tool_turns >= stall_repeat_threshold) {
exited_on_stall = 1;
stall_due_to_length = (resp.finish_reason && strcmp(resp.finish_reason, "length") == 0) ? 1 : 0;
llm_response_free(&resp);
break;
}
if (append_assistant_tool_calls_message_local(convo, &resp) != 0) {
llm_response_free(&resp);
final_response = strdup("Failed to append assistant tool calls.");
@@ -845,9 +1025,43 @@ static cJSON* run_prompt_with_tools_convo(cJSON* convo,
llm_response_free(&resp);
}
done:
done:;
int hit_max_turn_limit = (!final_response && !exited_on_stall && turns_run >= max_turns);
if (!final_response) {
final_response = strdup(tool_limit_message ? tool_limit_message : "I hit my tool-use limit for this prompt run.");
char* messages_json = cJSON_PrintUnformatted(convo);
if (messages_json) {
llm_response_t final_resp;
int final_rc = llm_chat_with_tools_messages(messages_json, tools_json, "none", &final_resp);
free(messages_json);
if (final_rc == 0) {
const char* forced_answer = final_resp.content ? final_resp.content : "";
if (forced_answer[0] != '\0') {
final_response = strdup(forced_answer);
}
llm_response_free(&final_resp);
}
}
}
if (!final_response) {
final_response = strdup(exited_on_stall
? "Stopped repeated tool calls after detecting a loop, and no final summary was produced."
: (tool_limit_message ? tool_limit_message : "I hit my tool-use limit for this prompt run."));
}
if (exited_on_stall || hit_max_turn_limit) {
notify_admin_limit_diagnostic_http("http_api_tool_loop",
exited_on_stall ? "stall_repetition_detected" : "max_turns_exhausted",
log_sender,
max_turns,
turns_run,
stall_repeat_threshold,
repeated_tool_turns,
g_api_ctx.cfg ? g_api_ctx.cfg->llm.max_tokens : 0,
(exited_on_stall && stall_due_to_length) ? "max_tokens_truncation" : NULL,
(exited_on_stall && stall_due_to_length) ? "Increase max_tokens (example: /model_set {\"max_tokens\": 4096})" : NULL,
final_response ? final_response : "");
}
cJSON_AddBoolToObject(root, "success", 1);
@@ -888,6 +1102,9 @@ static cJSON* run_prompt_with_tools(cJSON* body) {
}
int max_turns = 4;
if (g_api_ctx.cfg && g_api_ctx.cfg->tools.api_default_max_turns > 0) {
max_turns = g_api_ctx.cfg->tools.api_default_max_turns;
}
cJSON* max_turns_node = cJSON_GetObjectItemCaseSensitive(body, "max_turns");
if (max_turns_node && cJSON_IsNumber(max_turns_node)) {
max_turns = (int)max_turns_node->valuedouble;
@@ -1104,6 +1321,9 @@ static void handle_prompt_agent(struct mg_connection* c, const struct mg_http_me
}
int max_turns = 4;
if (g_api_ctx.cfg && g_api_ctx.cfg->tools.api_default_max_turns > 0) {
max_turns = g_api_ctx.cfg->tools.api_default_max_turns;
}
cJSON* max_turns_node = cJSON_GetObjectItemCaseSensitive(body, "max_turns");
if (max_turns_node && cJSON_IsNumber(max_turns_node)) {
max_turns = (int)max_turns_node->valuedouble;
+1 -1
View File
@@ -2,7 +2,7 @@
#define DIDACTYL_HTTP_API_H
#include "config.h"
#include "tools.h"
#include "tools/tools.h"
struct trigger_manager;
+42 -36
View File
@@ -10,6 +10,7 @@
#include <unistd.h>
#include "cjson/cJSON.h"
#include "debug.h"
typedef struct {
char* data;
@@ -92,11 +93,9 @@ static char* perform_http_request(const char* url, const char* body, int is_post
}
if (url_looks_like_websocket(url)) {
fprintf(stderr,
"[didactyl] llm config error: base_url must be HTTP(S), got WebSocket URL: %s\n",
url);
fprintf(stderr,
"[didactyl] llm hint: set llm.base_url to an OpenAI-compatible HTTPS endpoint, e.g. https://api.example.com/v1\n");
DEBUG_ERROR("[didactyl] llm config error: base_url must be HTTP(S), got WebSocket URL: %s",
url);
DEBUG_WARN("[didactyl] llm hint: set llm.base_url to an OpenAI-compatible HTTPS endpoint, e.g. https://api.example.com/v1");
curl_easy_cleanup(curl);
return NULL;
}
@@ -129,14 +128,13 @@ static char* perform_http_request(const char* url, const char* body, int is_post
if (is_post) {
size_t body_len = body ? strlen(body) : 0U;
size_t body_preview_len = body_len > 4000U ? 4000U : body_len;
fprintf(stderr,
"[didactyl] llm request: method=POST url=%s body_bytes=%zu body_preview=%.4000s%s\n",
url,
body_len,
body ? body : "",
body_len > body_preview_len ? "..." : "");
DEBUG_INFO("[didactyl] llm request: method=POST url=%s body_bytes=%zu body_preview=%.4000s%s",
url,
body_len,
body ? body : "",
body_len > body_preview_len ? "..." : "");
} else {
fprintf(stderr, "[didactyl] llm request: method=GET url=%s\n", url);
DEBUG_INFO("[didactyl] llm request: method=GET url=%s", url);
}
CURLcode res = curl_easy_perform(curl);
@@ -147,33 +145,32 @@ static char* perform_http_request(const char* url, const char* body, int is_post
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
fprintf(stderr, "[didactyl] llm http request failed: curl=%s\n", curl_easy_strerror(res));
DEBUG_ERROR("[didactyl] llm http request failed: curl=%s", curl_easy_strerror(res));
if (rb.data && rb.len > 0) {
fprintf(stderr, "[didactyl] llm partial response: %.600s%s\n",
rb.data,
rb.len > 600 ? "..." : "");
DEBUG_WARN("[didactyl] llm partial response: %.600s%s",
rb.data,
rb.len > 600 ? "..." : "");
}
free(rb.data);
return NULL;
}
if (status < 200 || status >= 300) {
fprintf(stderr, "[didactyl] llm http request failed: status=%ld\n", status);
DEBUG_ERROR("[didactyl] llm http request failed: status=%ld", status);
if (status == 101) {
fprintf(stderr,
"[didactyl] llm hint: received HTTP 101 (Switching Protocols), which usually means llm.base_url points to a WebSocket server instead of an HTTP LLM API\n");
DEBUG_WARN("[didactyl] llm hint: received HTTP 101 (Switching Protocols), which usually means llm.base_url points to a WebSocket server instead of an HTTP LLM API");
}
if (rb.data && rb.len > 0) {
fprintf(stderr, "[didactyl] llm error response: %.1200s%s\n",
rb.data,
rb.len > 1200 ? "..." : "");
DEBUG_WARN("[didactyl] llm error response: %.1200s%s",
rb.data,
rb.len > 1200 ? "..." : "");
}
free(rb.data);
return NULL;
}
if (!rb.data) {
fprintf(stderr, "[didactyl] llm http request failed: empty response body\n");
DEBUG_ERROR("[didactyl] llm http request failed: empty response body");
return NULL;
}
@@ -292,6 +289,11 @@ static int parse_llm_response(const char* json, llm_response_t* out) {
return -1;
}
cJSON* finish_reason = first ? cJSON_GetObjectItemCaseSensitive(first, "finish_reason") : NULL;
if (finish_reason && cJSON_IsString(finish_reason) && finish_reason->valuestring) {
out->finish_reason = strdup(finish_reason->valuestring);
}
cJSON* content = cJSON_GetObjectItemCaseSensitive(msg, "content");
if (content && cJSON_IsString(content) && content->valuestring) {
out->content = strdup(content->valuestring);
@@ -332,9 +334,9 @@ char* llm_chat(const char* system_prompt, const char* user_message) {
llm_response_t parsed;
if (parse_llm_response(raw, &parsed) != 0) {
fprintf(stderr, "[didactyl] failed to parse llm response (non-tool path): %.1200s%s\n",
raw,
strlen(raw) > 1200 ? "..." : "");
DEBUG_ERROR("[didactyl] failed to parse llm response (non-tool path): %.1200s%s",
raw,
strlen(raw) > 1200 ? "..." : "");
free(raw);
return NULL;
}
@@ -393,9 +395,8 @@ int llm_chat_with_tools_messages(const char* messages_json,
}
if (filtered_count > 0) {
fprintf(stderr,
"[didactyl] llm request sanitizer: removed %d empty text message(s) before provider request\n",
filtered_count);
DEBUG_INFO("[didactyl] llm request sanitizer: removed %d empty text message(s) before provider request",
filtered_count);
}
cJSON_AddItemToObject(root, "messages", messages);
@@ -420,9 +421,9 @@ int llm_chat_with_tools_messages(const char* messages_json,
int rc = parse_llm_response(raw, out_response);
if (rc != 0) {
fprintf(stderr, "[didactyl] failed to parse llm response (tools path): %.1200s%s\n",
raw,
strlen(raw) > 1200 ? "..." : "");
DEBUG_ERROR("[didactyl] failed to parse llm response (tools path): %.1200s%s",
raw,
strlen(raw) > 1200 ? "..." : "");
}
free(raw);
return rc;
@@ -463,6 +464,7 @@ int llm_chat_with_tools(const char* system_prompt,
void llm_response_free(llm_response_t* response) {
if (!response) return;
free(response->content);
free(response->finish_reason);
for (int i = 0; i < response->tool_call_count; i++) {
free(response->tool_calls[i].id);
free(response->tool_calls[i].name);
@@ -488,8 +490,8 @@ int llm_set_config(const llm_config_t* config) {
return 0;
}
char* llm_list_models_json(const char* base_url_override) {
if (!g_initialized) {
char* llm_get_json_path(const char* base_url_override, const char* path) {
if (!g_initialized || !path || path[0] == '\0') {
return NULL;
}
@@ -497,11 +499,15 @@ char* llm_list_models_json(const char* base_url_override) {
? base_url_override
: g_cfg.base_url;
char url[OW_MAX_URL_LEN + 32];
snprintf(url, sizeof(url), "%s/models", base_url);
char url[OW_MAX_URL_LEN + 128];
snprintf(url, sizeof(url), "%s%s", base_url, path);
return perform_http_request(url, NULL, 0);
}
char* llm_list_models_json(const char* base_url_override) {
return llm_get_json_path(base_url_override, "/models");
}
void llm_cleanup(void) {
if (!g_initialized) {
return;
+2
View File
@@ -13,6 +13,7 @@ typedef struct {
char* content;
llm_tool_call_t* tool_calls;
int tool_call_count;
char* finish_reason;
} llm_response_t;
int llm_init(const llm_config_t* config);
@@ -29,6 +30,7 @@ void llm_response_free(llm_response_t* response);
int llm_get_config(llm_config_t* out_config);
int llm_set_config(const llm_config_t* config);
char* llm_list_models_json(const char* base_url_override);
char* llm_get_json_path(const char* base_url_override, const char* path);
void llm_cleanup(void);
#endif
+1140 -65
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -11,9 +11,9 @@
// Version information (auto-updated by build system)
// Using DIDACTYL_ prefix to avoid conflicts with nostr_core_lib VERSION macros
#define DIDACTYL_VERSION_MAJOR 0
#define DIDACTYL_VERSION_MINOR 0
#define DIDACTYL_VERSION_PATCH 62
#define DIDACTYL_VERSION "v0.0.62"
#define DIDACTYL_VERSION_MINOR 1
#define DIDACTYL_VERSION_PATCH 3
#define DIDACTYL_VERSION "v0.1.3"
// Agent metadata
#define DIDACTYL_NAME "Didactyl"
+1589 -151
View File
File diff suppressed because it is too large Load Diff
+10
View File
@@ -35,6 +35,7 @@ typedef void (*nostr_self_skill_eose_cb_t)(int event_count, void* user_data);
int nostr_handler_init(didactyl_config_t* config);
void nostr_handler_set_trigger_manager(struct trigger_manager* trigger_manager);
int nostr_handler_subscribe_admin_context(void);
int nostr_handler_subscribe_agent_context(void);
int nostr_handler_subscribe_self_skills(void);
char* nostr_handler_get_self_events_by_kind_json(int kind);
void nostr_handler_set_self_skill_eose_callback(nostr_self_skill_eose_cb_t callback, void* user_data);
@@ -57,18 +58,27 @@ nostr_pool_subscription_t* nostr_handler_subscribe_with_filter(
int nostr_handler_close_subscription(nostr_pool_subscription_t* subscription);
int nostr_handler_poll(int timeout_ms);
int nostr_handler_reconcile_startup_events(void);
int nostr_handler_load_system_context_from_adopted_skills(void);
void nostr_handler_refresh_relay_statuses(void);
int nostr_handler_sync_relays_from_config(void);
const char* nostr_handler_get_system_context(void);
char* nostr_handler_get_self_skill_events_json(void);
int nostr_handler_is_event_in_self_cache(const char* event_id_hex);
const char* nostr_handler_get_startup_display_name(void);
int nostr_handler_connected_relay_count(void);
char* nostr_handler_get_admin_kind0_context(void);
char* nostr_handler_get_admin_kind3_context(void);
char* nostr_handler_get_admin_kind10002_context(void);
char* nostr_handler_get_admin_kind1_notes_context(void);
char* nostr_handler_get_agent_kind0_context(void);
char* nostr_handler_get_agent_kind3_context(void);
char* nostr_handler_get_agent_kind10002_context(void);
char* nostr_handler_get_agent_kind1_notes_context(void);
int nostr_handler_is_wot_contact(const char* pubkey_hex);
char* nostr_handler_relay_status_json(void);
char* nostr_handler_relay_info_json(const char* relay_url);
char* nostr_handler_subscription_status_json(void);
int nostr_handler_subscription_set_json(const char* name, cJSON* filter, int enabled, int enabled_set);
int nostr_handler_send_dm_nip17(const char* recipient_pubkey_hex, const char* message, const char* subject);
char* nostr_handler_get_dm_history_json(const char* peer_pubkey_hex, int limit);
void nostr_handler_cleanup(void);
+116 -6
View File
@@ -97,6 +97,116 @@ static int append_text(char** buf, size_t* cap, size_t* used, const char* s) {
return 0;
}
static const char* map_variable_tool_name(const char* var_name) {
if (!var_name || var_name[0] == '\0') return NULL;
if (strcmp(var_name, "admin_profile") == 0) return "nostr_admin_profile";
if (strcmp(var_name, "admin_notes") == 0) return "nostr_admin_notes";
if (strcmp(var_name, "admin_relays") == 0) return "nostr_admin_relays";
if (strcmp(var_name, "adopted_skills") == 0) return "adopted_skills";
if (strcmp(var_name, "triggering_event") == 0) return "trigger_event";
return var_name;
}
static char* resolve_inline_variables_local(const char* tpl, tools_context_t* tools_ctx) {
if (!tpl) return strdup("");
size_t cap = strlen(tpl) + 64U;
size_t used = 0U;
char* out = (char*)malloc(cap);
if (!out) return NULL;
out[0] = '\0';
const char* p = tpl;
while (*p) {
const char* open = strstr(p, "{{");
if (!open) {
if (append_text(&out, &cap, &used, p) != 0) {
free(out);
return NULL;
}
break;
}
if (open > p) {
char* prefix = dup_range(p, (size_t)(open - p));
if (!prefix) {
free(out);
return NULL;
}
int rc = append_text(&out, &cap, &used, prefix);
free(prefix);
if (rc != 0) {
free(out);
return NULL;
}
}
const char* close = strstr(open + 2, "}}");
if (!close) {
if (append_text(&out, &cap, &used, open) != 0) {
free(out);
return NULL;
}
break;
}
char* var = dup_range(open + 2, (size_t)(close - (open + 2)));
if (!var) {
free(out);
return NULL;
}
char* var_trim = ltrim_inplace(var);
rtrim_inplace(var_trim);
const char* replacement = "";
char* replacement_owned = NULL;
if (strcmp(var_trim, "message") == 0) {
replacement = (tools_ctx && tools_ctx->template_current_user_message)
? tools_ctx->template_current_user_message
: "";
} else if (strcmp(var_trim, "dm_history") == 0) {
replacement = "";
} else if (tools_ctx) {
const char* tool_name = map_variable_tool_name(var_trim);
if (tool_name && tool_name[0] != '\0') {
char* tool_result = tools_execute(tools_ctx, tool_name, "{}");
if (tool_result) {
cJSON* root = cJSON_Parse(tool_result);
if (root && cJSON_IsObject(root)) {
cJSON* success = cJSON_GetObjectItemCaseSensitive(root, "success");
if (!success || !cJSON_IsBool(success) || cJSON_IsTrue(success)) {
cJSON* content = cJSON_GetObjectItemCaseSensitive(root, "content");
if (content && cJSON_IsString(content) && content->valuestring) {
replacement_owned = strdup(content->valuestring);
} else if (content) {
replacement_owned = cJSON_PrintUnformatted(content);
}
}
}
cJSON_Delete(root);
free(tool_result);
}
}
replacement = replacement_owned ? replacement_owned : "";
}
if (append_text(&out, &cap, &used, replacement) != 0) {
free(replacement_owned);
free(var);
free(out);
return NULL;
}
free(replacement_owned);
free(var);
p = close + 2;
}
return out;
}
static void init_section_defaults(prompt_template_section_t* sec) {
if (!sec) return;
memset(sec->name, 0, sizeof(sec->name));
@@ -118,20 +228,20 @@ static int parse_int_or_zero(const char* s) {
return atoi(s);
}
int prompt_template_parse(const char* soul_content, prompt_template_t* out_template) {
if (!soul_content || !out_template) {
int prompt_template_parse(const char* skill_content, prompt_template_t* out_template) {
if (!skill_content || !out_template) {
return -1;
}
memset(out_template, 0, sizeof(*out_template));
const char* marker = strstr(soul_content, PROMPT_TEMPLATE_MARKER);
const char* marker = strstr(skill_content, PROMPT_TEMPLATE_MARKER);
if (!marker) {
return -1;
}
size_t personality_len = (size_t)(marker - soul_content);
out_template->personality = dup_range(soul_content, personality_len);
size_t personality_len = (size_t)(marker - skill_content);
out_template->personality = dup_range(skill_content, personality_len);
if (!out_template->personality) {
return -1;
}
@@ -500,7 +610,7 @@ cJSON* prompt_template_build_messages(const prompt_template_t* tmpl,
strcmp(provider_name, sec->provider_name) == 0) {
tpl = sec->provider_content_template;
}
resolved = strdup(tpl ? tpl : "");
resolved = resolve_inline_variables_local(tpl ? tpl : "", tools_ctx);
}
if (!resolved) {
cJSON_Delete(out);
+2 -2
View File
@@ -2,7 +2,7 @@
#define DIDACTYL_PROMPT_TEMPLATE_H
#include "cjson/cJSON.h"
#include "tools.h"
#include "tools/tools.h"
#define PROMPT_TEMPLATE_MAX_SECTIONS 32
#define PROMPT_TEMPLATE_MAX_NAME_LEN 64
@@ -32,7 +32,7 @@ typedef void (*prompt_template_emit_hook_fn)(const char* section_name,
int message_index,
void* user_data);
int prompt_template_parse(const char* soul_content, prompt_template_t* out_template);
int prompt_template_parse(const char* skill_content, prompt_template_t* out_template);
cJSON* prompt_template_build_messages(const prompt_template_t* tmpl,
const char* provider_name,
+2532
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
#ifndef DIDACTYL_SETUP_WIZARD_H
#define DIDACTYL_SETUP_WIZARD_H
#include <stddef.h>
#include "config.h"
/*
* setup_wizard_run
*
* Return values:
* 0 -> bootstrap/overwrite mode selected (new agent or load genesis), continue boot
* 1 -> wrote config/genesis and requested exit (no boot)
* 2 -> existing-agent recovery mode selected, continue boot
* -1 -> abort/error
*/
#define SETUP_WIZARD_RC_BOOTSTRAP 0
#define SETUP_WIZARD_RC_EXIT 1
#define SETUP_WIZARD_RC_EXISTING 2
#define SETUP_WIZARD_RC_ABORT -1
int setup_wizard_run(didactyl_config_t* config, char* genesis_path_out, size_t genesis_path_out_size);
#endif
-6060
View File
File diff suppressed because it is too large Load Diff
+216
View File
@@ -0,0 +1,216 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
char* execute_admin_identity(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
const char* tier_text = "Sender tier unknown.";
if (ctx->template_sender_tier == 1) {
tier_text = "This message has been cryptographically verified as coming from your administrator.";
} else if (ctx->template_sender_tier == 2) {
tier_text = "This message is from a web-of-trust contact (not the administrator).";
}
cJSON_AddBoolToObject(out, "success", 1);
char content[768];
snprintf(content,
sizeof(content),
"## Administrator Identity (source: config.admin.pubkey)\n\n"
"This is your administrator! Admin pubkey (hex): %s\n\n"
"%s",
ctx->cfg->admin.pubkey[0] ? ctx->cfg->admin.pubkey : "unknown",
tier_text);
cJSON_AddStringToObject(out, "content", content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_admin_profile(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* kind0 = nostr_handler_get_admin_kind0_context();
const char* profile_json = (kind0 && kind0[0]) ? kind0 : "{}";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind0);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Administrator Kind 0 Profile (source: nostr kind 0)\n\nAdministrator kind 0 profile content (JSON): ") + strlen(profile_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind0);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Kind 0 Profile (source: nostr kind 0)\n\nAdministrator kind 0 profile content (JSON): %s",
profile_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind0);
return json;
}
char* execute_nostr_admin_contacts(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* kind3 = nostr_handler_get_admin_kind3_context();
const char* contacts_json = (kind3 && kind3[0]) ? kind3 : "[]";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind3);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Administrator Kind 3 Contacts (source: nostr kind 3)\n\nAdministrator contacts (JSON): ") + strlen(contacts_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind3);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Kind 3 Contacts (source: nostr kind 3)\n\nAdministrator contacts (JSON): %s",
contacts_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind3);
return json;
}
char* execute_nostr_admin_relays(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* kind10002 = nostr_handler_get_admin_kind10002_context();
const char* relays_json = (kind10002 && kind10002[0]) ? kind10002 : "[]";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind10002);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Administrator Kind 10002 Relays (source: nostr kind 10002)\n\nAdministrator relay list (JSON): ") + strlen(relays_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind10002);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Kind 10002 Relays (source: nostr kind 10002)\n\nAdministrator relay list (JSON): %s",
relays_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind10002);
return json;
}
char* execute_nostr_admin_notes(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* notes = nostr_handler_get_admin_kind1_notes_context();
const char* notes_text = (notes && notes[0]) ? notes : "";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(notes);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Administrator Recent Kind 1 Notes\n\n") + strlen(notes_text) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(notes);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Recent Kind 1 Notes\n\n%s",
notes_text);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(notes);
return json;
}
+323
View File
@@ -0,0 +1,323 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../main.h"
#include "../nostr_handler.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
char* execute_message_current(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", ctx->template_current_user_message ? ctx->template_current_user_message : "");
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_agent_identity(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char npub[128] = {0};
if (nostr_key_to_bech32(ctx->cfg->keys.public_key, "npub", npub) != NOSTR_SUCCESS) {
strcpy(npub, "unknown");
}
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
char content[384];
snprintf(content,
sizeof(content),
"## Agent Identity\n\nYour pubkey (hex): %s\nYour npub: %s",
ctx->cfg->keys.public_key_hex[0] ? ctx->cfg->keys.public_key_hex : "unknown",
npub);
cJSON_AddStringToObject(out, "content", content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_agent_profile(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* kind0 = nostr_handler_get_agent_kind0_context();
const char* profile_json = (kind0 && kind0[0]) ? kind0 : "{}";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind0);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Agent Kind 0 Profile (source: nostr kind 0)\n\nAgent kind 0 profile content (JSON): ") + strlen(profile_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind0);
return NULL;
}
snprintf(content,
content_len,
"## Agent Kind 0 Profile (source: nostr kind 0)\n\nAgent kind 0 profile content (JSON): %s",
profile_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind0);
return json;
}
char* execute_nostr_agent_contacts(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* kind3 = nostr_handler_get_agent_kind3_context();
const char* contacts_json = (kind3 && kind3[0]) ? kind3 : "[]";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind3);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Agent Kind 3 Contacts (source: nostr kind 3)\n\nAgent contacts (JSON): ") + strlen(contacts_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind3);
return NULL;
}
snprintf(content,
content_len,
"## Agent Kind 3 Contacts (source: nostr kind 3)\n\nAgent contacts (JSON): %s",
contacts_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind3);
return json;
}
char* execute_nostr_agent_relays(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* kind10002 = nostr_handler_get_agent_kind10002_context();
const char* relays_json = (kind10002 && kind10002[0]) ? kind10002 : "[]";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind10002);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Agent Kind 10002 Relays (source: nostr kind 10002)\n\nAgent relay list (JSON): ") + strlen(relays_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind10002);
return NULL;
}
snprintf(content,
content_len,
"## Agent Kind 10002 Relays (source: nostr kind 10002)\n\nAgent relay list (JSON): %s",
relays_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind10002);
return json;
}
char* execute_nostr_agent_notes(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* notes = nostr_handler_get_agent_kind1_notes_context();
const char* notes_text = (notes && notes[0]) ? notes : "";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(notes);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
size_t content_len = strlen("## Agent Recent Kind 1 Notes\n\n") + strlen(notes_text) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(notes);
return NULL;
}
snprintf(content,
content_len,
"## Agent Recent Kind 1 Notes\n\n%s",
notes_text);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(notes);
return json;
}
char* execute_adopted_skills(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
cJSON* filter = cJSON_CreateObject();
cJSON* kinds = cJSON_CreateArray();
cJSON* authors = cJSON_CreateArray();
if (!filter || !kinds || !authors) {
cJSON_Delete(filter);
cJSON_Delete(kinds);
cJSON_Delete(authors);
return NULL;
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(10123));
cJSON_AddItemToObject(filter, "kinds", kinds);
cJSON_AddItemToArray(authors, cJSON_CreateString(ctx->cfg->keys.public_key_hex));
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddNumberToObject(filter, "limit", 1);
char* events_json = nostr_handler_query_json(filter, 3000);
cJSON_Delete(filter);
cJSON* out = cJSON_CreateObject();
if (!out) {
free(events_json);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", (events_json && events_json[0]) ? events_json : "[]");
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(events_json);
return json;
}
char* execute_trigger_event(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
const char* trigger_json = (ctx->template_trigger_event_json && ctx->template_trigger_event_json[0] != '\0')
? ctx->template_trigger_event_json
: NULL;
if (!trigger_json) {
cJSON* arg_json = cJSON_GetObjectItemCaseSensitive(args, "trigger_event_json");
if (arg_json && cJSON_IsString(arg_json) && arg_json->valuestring && arg_json->valuestring[0] != '\0') {
trigger_json = arg_json->valuestring;
}
}
cJSON_Delete(args);
if (!trigger_json) {
trigger_json = "{}";
}
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", trigger_json);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_agent_version(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "name", DIDACTYL_NAME);
cJSON_AddStringToObject(out, "description", DIDACTYL_DESCRIPTION);
cJSON_AddStringToObject(out, "software", DIDACTYL_SOFTWARE);
cJSON_AddStringToObject(out, "version", DIDACTYL_VERSION);
cJSON_AddNumberToObject(out, "version_major", DIDACTYL_VERSION_MAJOR);
cJSON_AddNumberToObject(out, "version_minor", DIDACTYL_VERSION_MINOR);
cJSON_AddNumberToObject(out, "version_patch", DIDACTYL_VERSION_PATCH);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
+250
View File
@@ -0,0 +1,250 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../cashu_wallet.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static char* wrap_wallet_json_result(int rc, cJSON* obj, const char* default_error) {
if (rc != 0 || !obj) {
cJSON_Delete(obj);
return json_error_local(default_error ? default_error : "cashu wallet operation failed");
}
char* out = cJSON_PrintUnformatted(obj);
cJSON_Delete(obj);
return out;
}
char* execute_cashu_wallet_balance(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* out = NULL;
int rc = cashu_wallet_balance_json(&out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_balance failed");
}
char* execute_cashu_wallet_info(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
if ((!mint_url || mint_url[0] == '\0') && ctx->cfg->cashu_wallet.mint_count <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_info requires mint_url when no cashu_wallet.mint_urls are configured");
}
cJSON* out = NULL;
int rc = cashu_wallet_info_json(mint_url, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_info failed (check mint_url and mint connectivity)");
}
char* execute_cashu_wallet_mint_quote(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* amount = cJSON_GetObjectItemCaseSensitive(args, "amount");
if (!amount || !cJSON_IsNumber(amount) || amount->valuedouble <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_mint_quote requires numeric amount > 0");
}
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
cJSON* unit = cJSON_GetObjectItemCaseSensitive(args, "unit");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
const char* unit_s = (unit && cJSON_IsString(unit) && unit->valuestring) ? unit->valuestring : NULL;
if ((!mint_url || mint_url[0] == '\0') && ctx->cfg->cashu_wallet.mint_count <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_mint_quote requires mint_url when no cashu_wallet.mint_urls are configured");
}
cJSON* out = NULL;
int rc = cashu_wallet_mint_quote_json(mint_url, (uint64_t)amount->valuedouble, unit_s, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_mint_quote failed");
}
char* execute_cashu_wallet_mint_check(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* quote_id = cJSON_GetObjectItemCaseSensitive(args, "quote_id");
if (!quote_id || !cJSON_IsString(quote_id) || !quote_id->valuestring || quote_id->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("cashu_wallet_mint_check requires quote_id");
}
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
if ((!mint_url || mint_url[0] == '\0') && ctx->cfg->cashu_wallet.mint_count <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_mint_check requires mint_url when no cashu_wallet.mint_urls are configured");
}
cJSON* out = NULL;
int rc = cashu_wallet_mint_check_json(mint_url, quote_id->valuestring, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_mint_check failed");
}
char* execute_cashu_wallet_mint_claim(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* quote_id = cJSON_GetObjectItemCaseSensitive(args, "quote_id");
if (!quote_id || !cJSON_IsString(quote_id) || !quote_id->valuestring || quote_id->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("cashu_wallet_mint_claim requires quote_id");
}
uint64_t amount = 0;
cJSON* amount_item = cJSON_GetObjectItemCaseSensitive(args, "amount");
if (amount_item) {
if (!cJSON_IsNumber(amount_item) || amount_item->valuedouble < 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_mint_claim amount must be a non-negative number");
}
amount = (uint64_t)amount_item->valuedouble;
}
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
if ((!mint_url || mint_url[0] == '\0') && ctx->cfg->cashu_wallet.mint_count <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_mint_claim requires mint_url when no cashu_wallet.mint_urls are configured");
}
cJSON* out = NULL;
int rc = cashu_wallet_mint_claim_json(mint_url, quote_id->valuestring, amount, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_mint_claim failed");
}
char* execute_cashu_wallet_melt_quote(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* payment_request = cJSON_GetObjectItemCaseSensitive(args, "payment_request");
if (!payment_request || !cJSON_IsString(payment_request) || !payment_request->valuestring || payment_request->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("cashu_wallet_melt_quote requires payment_request");
}
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
cJSON* unit = cJSON_GetObjectItemCaseSensitive(args, "unit");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
const char* unit_s = (unit && cJSON_IsString(unit) && unit->valuestring) ? unit->valuestring : NULL;
if ((!mint_url || mint_url[0] == '\0') && ctx->cfg->cashu_wallet.mint_count <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_melt_quote requires mint_url when no cashu_wallet.mint_urls are configured");
}
cJSON* out = NULL;
int rc = cashu_wallet_melt_quote_json(mint_url, payment_request->valuestring, unit_s, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_melt_quote failed");
}
char* execute_cashu_wallet_melt_pay(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* quote_id = cJSON_GetObjectItemCaseSensitive(args, "quote_id");
if (!quote_id || !cJSON_IsString(quote_id) || !quote_id->valuestring || quote_id->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("cashu_wallet_melt_pay requires quote_id");
}
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
if ((!mint_url || mint_url[0] == '\0') && ctx->cfg->cashu_wallet.mint_count <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_melt_pay requires mint_url when no cashu_wallet.mint_urls are configured");
}
cJSON* out = NULL;
int rc = cashu_wallet_melt_pay_json(mint_url, quote_id->valuestring, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_melt_pay failed");
}
char* execute_cashu_wallet_check_proofs(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
if ((!mint_url || mint_url[0] == '\0') && ctx->cfg->cashu_wallet.mint_count <= 0) {
cJSON_Delete(args);
return json_error_local("cashu_wallet_check_proofs requires mint_url when no cashu_wallet.mint_urls are configured");
}
cJSON* out = NULL;
int rc = cashu_wallet_check_proofs_json(mint_url, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_check_proofs failed");
}
char* execute_cashu_wallet_receive_token(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* token = cJSON_GetObjectItemCaseSensitive(args, "token");
if (!token || !cJSON_IsString(token) || !token->valuestring || token->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("cashu_wallet_receive_token requires token");
}
cJSON* mint = cJSON_GetObjectItemCaseSensitive(args, "mint_url");
const char* mint_url = (mint && cJSON_IsString(mint) && mint->valuestring) ? mint->valuestring : NULL;
cJSON* out = NULL;
int rc = cashu_wallet_receive_token_json(token->valuestring, mint_url, &out);
cJSON_Delete(args);
return wrap_wallet_json_result(rc, out, "cashu_wallet_receive_token failed");
}
+288
View File
@@ -0,0 +1,288 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
#define CONFIG_KIND 30078
#define CONFIG_APP_TAG "didactyl"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static int nip44_encrypt_self_local(tools_context_t* ctx, const char* plaintext, char** out_ciphertext) {
if (!ctx || !ctx->cfg || !out_ciphertext) return -1;
const char* plain = plaintext ? plaintext : "";
size_t out_cap = (strlen(plain) * 4U) + 1024U;
char* ciphertext = (char*)malloc(out_cap);
if (!ciphertext) return -1;
int rc = nostr_nip44_encrypt(ctx->cfg->keys.private_key,
ctx->cfg->keys.public_key,
plain,
ciphertext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(ciphertext);
return -1;
}
*out_ciphertext = ciphertext;
return 0;
}
static int nip44_decrypt_self_local(tools_context_t* ctx, const char* ciphertext, char** out_plaintext) {
if (!ctx || !ctx->cfg || !ciphertext || !out_plaintext) return -1;
size_t out_cap = strlen(ciphertext) + 1024U;
char* plaintext = (char*)malloc(out_cap);
if (!plaintext) return -1;
int rc = nostr_nip44_decrypt(ctx->cfg->keys.private_key,
ctx->cfg->keys.public_key,
ciphertext,
plaintext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(plaintext);
return -1;
}
*out_plaintext = plaintext;
return 0;
}
static int query_config_ciphertext_local(tools_context_t* ctx, const char* d_tag, char** out_ciphertext) {
if (!ctx || !ctx->cfg || !d_tag || !d_tag[0] || !out_ciphertext) return -1;
cJSON* filter = cJSON_CreateObject();
cJSON* kinds = cJSON_CreateArray();
cJSON* authors = cJSON_CreateArray();
cJSON* d_vals = cJSON_CreateArray();
if (!filter || !kinds || !authors || !d_vals) {
cJSON_Delete(filter);
cJSON_Delete(kinds);
cJSON_Delete(authors);
cJSON_Delete(d_vals);
return -1;
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(CONFIG_KIND));
cJSON_AddItemToObject(filter, "kinds", kinds);
cJSON_AddItemToArray(authors, cJSON_CreateString(ctx->cfg->keys.public_key_hex));
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddItemToArray(d_vals, cJSON_CreateString(d_tag));
cJSON_AddItemToObject(filter, "#d", d_vals);
cJSON_AddNumberToObject(filter, "limit", 1);
char* events_json = nostr_handler_query_json(filter, 4000);
cJSON_Delete(filter);
if (!events_json) {
return -1;
}
cJSON* arr = cJSON_Parse(events_json);
free(events_json);
if (!arr || !cJSON_IsArray(arr) || cJSON_GetArraySize(arr) <= 0) {
cJSON_Delete(arr);
*out_ciphertext = strdup("");
return (*out_ciphertext != NULL) ? 0 : -1;
}
cJSON* ev = cJSON_GetArrayItem(arr, 0);
cJSON* content = ev ? cJSON_GetObjectItemCaseSensitive(ev, "content") : NULL;
const char* cipher = (content && cJSON_IsString(content) && content->valuestring) ? content->valuestring : "";
*out_ciphertext = strdup(cipher);
cJSON_Delete(arr);
return (*out_ciphertext != NULL) ? 0 : -1;
}
char* execute_config_store(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* d_tag_j = cJSON_GetObjectItemCaseSensitive(args, "d_tag");
cJSON* content_j = cJSON_GetObjectItemCaseSensitive(args, "content");
if (!d_tag_j || !cJSON_IsString(d_tag_j) || !d_tag_j->valuestring || d_tag_j->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("config_store requires non-empty string d_tag");
}
if (!content_j) {
cJSON_Delete(args);
return json_error_local("config_store requires content");
}
char d_tag_buf[128];
snprintf(d_tag_buf, sizeof(d_tag_buf), "%s", d_tag_j->valuestring);
char* content_text = NULL;
if (cJSON_IsString(content_j) && content_j->valuestring) {
content_text = strdup(content_j->valuestring);
} else {
content_text = cJSON_PrintUnformatted(content_j);
}
cJSON_Delete(args);
if (!content_text) {
return json_error_local("config_store failed to serialize content");
}
char* ciphertext = NULL;
if (nip44_encrypt_self_local(ctx, content_text, &ciphertext) != 0) {
free(content_text);
return json_error_local("config_store NIP-44 encryption failed");
}
cJSON* tags = cJSON_CreateArray();
if (!tags) {
free(content_text);
free(ciphertext);
return NULL;
}
cJSON* d_tag = cJSON_CreateArray();
cJSON* app_tag = cJSON_CreateArray();
if (!d_tag || !app_tag) {
cJSON_Delete(d_tag);
cJSON_Delete(app_tag);
cJSON_Delete(tags);
free(content_text);
free(ciphertext);
return NULL;
}
cJSON_AddItemToArray(d_tag, cJSON_CreateString("d"));
cJSON_AddItemToArray(d_tag, cJSON_CreateString(d_tag_buf));
cJSON_AddItemToArray(tags, d_tag);
cJSON_AddItemToArray(app_tag, cJSON_CreateString("app"));
cJSON_AddItemToArray(app_tag, cJSON_CreateString(CONFIG_APP_TAG));
cJSON_AddItemToArray(tags, app_tag);
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event(CONFIG_KIND, ciphertext, tags, &publish_result);
cJSON_Delete(tags);
free(ciphertext);
if (rc != 0) {
free(content_text);
nostr_handler_publish_result_free(&publish_result);
return json_error_local("config_store publish failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
free(content_text);
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "d_tag", d_tag_buf);
cJSON_AddNumberToObject(out, "kind", CONFIG_KIND);
cJSON_AddNumberToObject(out, "content_length", (double)strlen(content_text));
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(content_text);
nostr_handler_publish_result_free(&publish_result);
return json;
}
char* execute_config_recall(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* d_tag_j = cJSON_GetObjectItemCaseSensitive(args, "d_tag");
if (!d_tag_j || !cJSON_IsString(d_tag_j) || !d_tag_j->valuestring || d_tag_j->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("config_recall requires non-empty string d_tag");
}
char d_tag_buf[256];
snprintf(d_tag_buf, sizeof(d_tag_buf), "%s", d_tag_j->valuestring);
cJSON_Delete(args);
char* ciphertext = NULL;
if (query_config_ciphertext_local(ctx, d_tag_buf, &ciphertext) != 0) {
return json_error_local("config_recall query failed");
}
if (!ciphertext || ciphertext[0] == '\0') {
free(ciphertext);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddBoolToObject(out, "found", 0);
cJSON_AddStringToObject(out, "d_tag", d_tag_buf);
cJSON_AddStringToObject(out, "content", "");
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* plaintext = NULL;
if (nip44_decrypt_self_local(ctx, ciphertext, &plaintext) != 0) {
free(ciphertext);
return json_error_local("config_recall NIP-44 decrypt failed");
}
free(ciphertext);
cJSON* out = cJSON_CreateObject();
if (!out) {
free(plaintext);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddBoolToObject(out, "found", 1);
cJSON_AddStringToObject(out, "d_tag", d_tag_buf);
cJSON_AddStringToObject(out, "content", plaintext);
cJSON_AddNumberToObject(out, "content_length", (double)strlen(plaintext));
cJSON* parsed = cJSON_Parse(plaintext);
if (parsed) {
cJSON_AddItemToObject(out, "content_json", parsed);
}
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(plaintext);
return json;
}
+515
View File
@@ -0,0 +1,515 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <curl/curl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/wait.h>
#include <unistd.h>
#include "cjson/cJSON.h"
typedef struct {
char* data;
size_t len;
size_t cap;
size_t max_bytes;
int truncated;
} local_http_fetch_buffer_t;
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static int is_safe_relative_path_local(const char* path) {
if (!path || path[0] == '\0') return 0;
if (path[0] == '/') return 0;
if (strstr(path, "..") != NULL) return 0;
if (strchr(path, '\\') != NULL) return 0;
return 1;
}
static int build_tool_path_local(tools_context_t* ctx, const char* rel_path, char* out, size_t out_size) {
if (!ctx || !ctx->cfg || !rel_path || !out || out_size == 0) return -1;
if (!is_safe_relative_path_local(rel_path)) return -1;
const char* cwd = ctx->cfg->tools.shell.working_directory[0] != '\0'
? ctx->cfg->tools.shell.working_directory
: ".";
int n = 0;
if (strcmp(cwd, ".") == 0) {
n = snprintf(out, out_size, "%s", rel_path);
} else {
n = snprintf(out, out_size, "%s/%s", cwd, rel_path);
}
if (n < 0 || (size_t)n >= out_size) return -1;
return 0;
}
static char* shell_quote_single_local(const char* in) {
if (!in) return NULL;
size_t len = strlen(in);
size_t extra = 2U;
for (size_t i = 0; i < len; i++) {
if (in[i] == '\'') {
extra += 4U;
} else {
extra += 1U;
}
}
char* out = (char*)malloc(extra + 1U);
if (!out) return NULL;
size_t j = 0;
out[j++] = '\'';
for (size_t i = 0; i < len; i++) {
if (in[i] == '\'') {
out[j++] = '\'';
out[j++] = '\\';
out[j++] = '\'';
out[j++] = '\'';
} else {
out[j++] = in[i];
}
}
out[j++] = '\'';
out[j] = '\0';
return out;
}
static size_t local_http_fetch_write_cb_local(void* contents, size_t size, size_t nmemb, void* userp) {
local_http_fetch_buffer_t* rb = (local_http_fetch_buffer_t*)userp;
size_t total = size * nmemb;
if (!rb || total == 0) return total;
if (rb->len >= rb->max_bytes) {
rb->truncated = 1;
return total;
}
size_t allowed = rb->max_bytes - rb->len;
size_t to_copy = total <= allowed ? total : allowed;
if (rb->len + to_copy + 1U > rb->cap) {
size_t new_cap = rb->cap == 0 ? 1024U : rb->cap;
while (new_cap < rb->len + to_copy + 1U) {
new_cap *= 2U;
}
char* bigger = (char*)realloc(rb->data, new_cap);
if (!bigger) return 0;
rb->data = bigger;
rb->cap = new_cap;
}
memcpy(rb->data + rb->len, contents, to_copy);
rb->len += to_copy;
rb->data[rb->len] = '\0';
if (to_copy < total) {
rb->truncated = 1;
}
return total;
}
static const char* detect_ca_bundle_path_for_tools_local(void) {
const char* env = getenv("SSL_CERT_FILE");
if (env && env[0] != '\0' && access(env, R_OK) == 0) {
return env;
}
static const char* candidates[] = {
"/etc/ssl/certs/ca-certificates.crt",
"/etc/ssl/cert.pem",
"/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/ca-bundle.pem"
};
for (size_t i = 0; i < sizeof(candidates) / sizeof(candidates[0]); i++) {
if (access(candidates[i], R_OK) == 0) {
return candidates[i];
}
}
return NULL;
}
char* execute_local_http_fetch(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* url = cJSON_GetObjectItemCaseSensitive(args, "url");
cJSON* method = cJSON_GetObjectItemCaseSensitive(args, "method");
cJSON* headers = cJSON_GetObjectItemCaseSensitive(args, "headers");
cJSON* body = cJSON_GetObjectItemCaseSensitive(args, "body");
cJSON* timeout = cJSON_GetObjectItemCaseSensitive(args, "timeout_seconds");
cJSON* maxb = cJSON_GetObjectItemCaseSensitive(args, "max_bytes");
if (!url || !cJSON_IsString(url) || !url->valuestring || url->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("local_http_fetch requires string url");
}
if (headers && !cJSON_IsArray(headers)) {
cJSON_Delete(args);
return json_error_local("local_http_fetch headers must be an array when provided");
}
if (body && !cJSON_IsString(body)) {
cJSON_Delete(args);
return json_error_local("local_http_fetch body must be a string when provided");
}
const char* method_str = (method && cJSON_IsString(method) && method->valuestring && method->valuestring[0] != '\0')
? method->valuestring
: "GET";
if (body && cJSON_IsString(body) && body->valuestring && strcasecmp(method_str, "GET") == 0) {
cJSON_Delete(args);
return json_error_local("local_http_fetch GET requests cannot include body");
}
int default_timeout = ctx->cfg->tools.local_http_fetch_default_timeout_seconds > 0
? ctx->cfg->tools.local_http_fetch_default_timeout_seconds
: 20;
int max_timeout = ctx->cfg->tools.local_http_fetch_max_timeout_seconds > 0
? ctx->cfg->tools.local_http_fetch_max_timeout_seconds
: 120;
if (default_timeout > max_timeout) {
default_timeout = max_timeout;
}
int timeout_seconds = (timeout && cJSON_IsNumber(timeout)) ? (int)timeout->valuedouble : default_timeout;
if (timeout_seconds <= 0) timeout_seconds = default_timeout;
if (timeout_seconds > max_timeout) timeout_seconds = max_timeout;
int hard_max = ctx->cfg->tools.shell.max_output_bytes > 0 ? ctx->cfg->tools.shell.max_output_bytes : 65536;
int max_bytes = (maxb && cJSON_IsNumber(maxb)) ? (int)maxb->valuedouble : hard_max;
if (max_bytes <= 0 || max_bytes > hard_max) max_bytes = hard_max;
CURL* curl = curl_easy_init();
if (!curl) {
cJSON_Delete(args);
return json_error_local("local_http_fetch failed to initialize curl");
}
local_http_fetch_buffer_t rb;
memset(&rb, 0, sizeof(rb));
rb.max_bytes = (size_t)max_bytes;
struct curl_slist* req_headers = NULL;
req_headers = curl_slist_append(req_headers, "Accept: */*");
if (headers && cJSON_IsArray(headers)) {
int n = cJSON_GetArraySize(headers);
for (int i = 0; i < n; i++) {
cJSON* h = cJSON_GetArrayItem(headers, i);
if (h && cJSON_IsString(h) && h->valuestring && h->valuestring[0] != '\0') {
req_headers = curl_slist_append(req_headers, h->valuestring);
}
}
}
curl_easy_setopt(curl, CURLOPT_URL, url->valuestring);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long)timeout_seconds);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, local_http_fetch_write_cb_local);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &rb);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, req_headers);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "didactyl/local_http_fetch");
const char* ca_bundle = detect_ca_bundle_path_for_tools_local();
if (ca_bundle) {
curl_easy_setopt(curl, CURLOPT_CAINFO, ca_bundle);
}
if (strcasecmp(method_str, "GET") == 0) {
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
} else if (strcasecmp(method_str, "POST") == 0) {
curl_easy_setopt(curl, CURLOPT_POST, 1L);
if (body && cJSON_IsString(body) && body->valuestring) {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body->valuestring);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(body->valuestring));
}
} else {
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method_str);
if (body && cJSON_IsString(body) && body->valuestring) {
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body->valuestring);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(body->valuestring));
}
}
CURLcode res = curl_easy_perform(curl);
long status_code = 0;
char* content_type = NULL;
char* content_type_copy = NULL;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status_code);
curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &content_type);
if (content_type && content_type[0] != '\0') {
content_type_copy = strdup(content_type);
}
curl_slist_free_all(req_headers);
curl_easy_cleanup(curl);
cJSON* out = cJSON_CreateObject();
if (!out) {
free(rb.data);
return NULL;
}
int http_ok = (status_code >= 200 && status_code < 300) ? 1 : 0;
int success = (res == CURLE_OK && http_ok) ? 1 : 0;
cJSON_AddBoolToObject(out, "success", success);
cJSON_AddStringToObject(out, "url", url->valuestring);
cJSON_AddStringToObject(out, "method", method_str);
cJSON_AddNumberToObject(out, "status_code", status_code);
cJSON_AddBoolToObject(out, "http_ok", http_ok);
cJSON_AddBoolToObject(out, "truncated", rb.truncated ? 1 : 0);
cJSON_AddNumberToObject(out, "bytes_received", (double)rb.len);
if (content_type_copy && content_type_copy[0] != '\0') {
cJSON_AddStringToObject(out, "content_type", content_type_copy);
}
if (res != CURLE_OK) {
cJSON_AddStringToObject(out, "curl_error", curl_easy_strerror(res));
}
cJSON_AddStringToObject(out, "body", rb.data ? rb.data : "");
free(rb.data);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
cJSON_Delete(args);
free(content_type_copy);
return json;
}
char* execute_local_shell_exec(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
if (!ctx->cfg->tools.shell.enabled) return json_error_local("shell tool disabled");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* command = cJSON_GetObjectItemCaseSensitive(args, "command");
if (!command || !cJSON_IsString(command) || !command->valuestring || command->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("local_shell_exec requires string command");
}
const char* cwd = ctx->cfg->tools.shell.working_directory[0] != '\0'
? ctx->cfg->tools.shell.working_directory
: ".";
int timeout_s = ctx->cfg->tools.shell.timeout_seconds > 0 ? ctx->cfg->tools.shell.timeout_seconds : 30;
char* quoted_cwd = shell_quote_single_local(cwd);
char* quoted_cmd = shell_quote_single_local(command->valuestring);
cJSON_Delete(args);
if (!quoted_cwd || !quoted_cmd) {
free(quoted_cwd);
free(quoted_cmd);
return json_error_local("allocation failure");
}
int needed = snprintf(NULL,
0,
"cd %s && timeout %ds sh -lc %s 2>&1",
quoted_cwd,
timeout_s,
quoted_cmd);
if (needed <= 0) {
free(quoted_cwd);
free(quoted_cmd);
return json_error_local("failed to build shell command");
}
char* cmd = (char*)malloc((size_t)needed + 1U);
if (!cmd) {
free(quoted_cwd);
free(quoted_cmd);
return json_error_local("allocation failure");
}
snprintf(cmd,
(size_t)needed + 1U,
"cd %s && timeout %ds sh -lc %s 2>&1",
quoted_cwd,
timeout_s,
quoted_cmd);
free(quoted_cwd);
free(quoted_cmd);
FILE* fp = popen(cmd, "r");
free(cmd);
if (!fp) return json_error_local("failed to execute command");
int max_bytes = ctx->cfg->tools.shell.max_output_bytes > 0 ? ctx->cfg->tools.shell.max_output_bytes : 65536;
char* output = (char*)calloc((size_t)max_bytes + 1U, 1U);
if (!output) {
pclose(fp);
return json_error_local("allocation failure");
}
size_t used = 0;
while (!feof(fp) && used < (size_t)max_bytes) {
size_t n = fread(output + used, 1, (size_t)max_bytes - used, fp);
used += n;
if (n == 0) break;
}
int raw_status = pclose(fp);
int exit_status = raw_status;
if (raw_status != -1) {
if (WIFEXITED(raw_status)) {
exit_status = WEXITSTATUS(raw_status);
} else if (WIFSIGNALED(raw_status)) {
exit_status = 128 + WTERMSIG(raw_status);
}
}
cJSON* out = cJSON_CreateObject();
if (!out) {
free(output);
return NULL;
}
cJSON_AddBoolToObject(out, "success", exit_status == 0 ? 1 : 0);
cJSON_AddNumberToObject(out, "exit_status", exit_status);
cJSON_AddStringToObject(out, "output", output);
free(output);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_local_file_read(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* path = cJSON_GetObjectItemCaseSensitive(args, "path");
cJSON* maxb = cJSON_GetObjectItemCaseSensitive(args, "max_bytes");
if (!path || !cJSON_IsString(path) || !path->valuestring) {
cJSON_Delete(args);
return json_error_local("local_file_read requires string path");
}
int hard_max = ctx->cfg->tools.shell.max_output_bytes > 0 ? ctx->cfg->tools.shell.max_output_bytes : 65536;
int max_bytes = (maxb && cJSON_IsNumber(maxb)) ? (int)maxb->valuedouble : hard_max;
if (max_bytes <= 0 || max_bytes > hard_max) max_bytes = hard_max;
char file_path[PATH_MAX];
if (build_tool_path_local(ctx, path->valuestring, file_path, sizeof(file_path)) != 0) {
cJSON_Delete(args);
return json_error_local("local_file_read path is not allowed");
}
FILE* fp = fopen(file_path, "rb");
cJSON_Delete(args);
if (!fp) return json_error_local("local_file_read failed to open file");
char* buf = (char*)calloc((size_t)max_bytes + 1U, 1U);
if (!buf) {
fclose(fp);
return json_error_local("allocation failure");
}
size_t n = fread(buf, 1, (size_t)max_bytes, fp);
int truncated = !feof(fp) ? 1 : 0;
fclose(fp);
buf[n] = '\0';
cJSON* out = cJSON_CreateObject();
if (!out) {
free(buf);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "path", file_path);
cJSON_AddNumberToObject(out, "bytes_read", (double)n);
cJSON_AddBoolToObject(out, "truncated", truncated);
cJSON_AddStringToObject(out, "content", buf);
free(buf);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_local_file_write(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* path = cJSON_GetObjectItemCaseSensitive(args, "path");
cJSON* content = cJSON_GetObjectItemCaseSensitive(args, "content");
cJSON* append = cJSON_GetObjectItemCaseSensitive(args, "append");
if (!path || !cJSON_IsString(path) || !path->valuestring ||
!content || !cJSON_IsString(content) || !content->valuestring) {
cJSON_Delete(args);
return json_error_local("local_file_write requires string path and content");
}
char file_path[PATH_MAX];
if (build_tool_path_local(ctx, path->valuestring, file_path, sizeof(file_path)) != 0) {
cJSON_Delete(args);
return json_error_local("local_file_write path is not allowed");
}
const char* content_str = content->valuestring;
size_t len = strlen(content_str);
int do_append = (append && cJSON_IsBool(append) && cJSON_IsTrue(append)) ? 1 : 0;
FILE* fp = fopen(file_path, do_append ? "ab" : "wb");
cJSON_Delete(args);
if (!fp) return json_error_local("local_file_write failed to open file");
size_t n = fwrite(content_str, 1, len, fp);
fclose(fp);
if (n != len) return json_error_local("local_file_write failed to write all bytes");
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "path", file_path);
cJSON_AddNumberToObject(out, "bytes_written", (double)n);
cJSON_AddBoolToObject(out, "append", do_append);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
+412
View File
@@ -0,0 +1,412 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
#define MEMORY_KIND 30078
#define MEMORY_D_TAG "memory"
#define MEMORY_APP_TAG "didactyl"
#define MEMORY_MAX_CHARS 32000
static pthread_mutex_t g_memory_mutex = PTHREAD_MUTEX_INITIALIZER;
static char* g_memory_plain = NULL;
static int g_memory_loaded = 0;
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static char* strdup_nonnull_local(const char* s) {
return strdup(s ? s : "");
}
static void memory_cache_set_locked_local(const char* plaintext) {
free(g_memory_plain);
g_memory_plain = strdup_nonnull_local(plaintext);
g_memory_loaded = 1;
}
static char* memory_cache_get_copy_locked_local(void) {
return strdup(g_memory_plain ? g_memory_plain : "");
}
static int nip44_encrypt_self_local(tools_context_t* ctx, const char* plaintext, char** out_ciphertext) {
if (!ctx || !ctx->cfg || !out_ciphertext) return -1;
const char* plain = plaintext ? plaintext : "";
size_t out_cap = (strlen(plain) * 4U) + 1024U;
char* ciphertext = (char*)malloc(out_cap);
if (!ciphertext) return -1;
int rc = nostr_nip44_encrypt(ctx->cfg->keys.private_key,
ctx->cfg->keys.public_key,
plain,
ciphertext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(ciphertext);
return -1;
}
*out_ciphertext = ciphertext;
return 0;
}
static int nip44_decrypt_self_local(tools_context_t* ctx, const char* ciphertext, char** out_plaintext) {
if (!ctx || !ctx->cfg || !ciphertext || !out_plaintext) return -1;
size_t out_cap = strlen(ciphertext) + 1024U;
char* plaintext = (char*)malloc(out_cap);
if (!plaintext) return -1;
int rc = nostr_nip44_decrypt(ctx->cfg->keys.private_key,
ctx->cfg->keys.public_key,
ciphertext,
plaintext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(plaintext);
return -1;
}
*out_plaintext = plaintext;
return 0;
}
static int query_memory_ciphertext_local(tools_context_t* ctx, char** out_ciphertext) {
if (!ctx || !ctx->cfg || !out_ciphertext) return -1;
cJSON* filter = cJSON_CreateObject();
cJSON* kinds = cJSON_CreateArray();
cJSON* authors = cJSON_CreateArray();
cJSON* d_vals = cJSON_CreateArray();
if (!filter || !kinds || !authors || !d_vals) {
cJSON_Delete(filter);
cJSON_Delete(kinds);
cJSON_Delete(authors);
cJSON_Delete(d_vals);
return -1;
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(MEMORY_KIND));
cJSON_AddItemToObject(filter, "kinds", kinds);
cJSON_AddItemToArray(authors, cJSON_CreateString(ctx->cfg->keys.public_key_hex));
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddItemToArray(d_vals, cJSON_CreateString(MEMORY_D_TAG));
cJSON_AddItemToObject(filter, "#d", d_vals);
cJSON_AddNumberToObject(filter, "limit", 1);
char* events_json = nostr_handler_query_json(filter, 4000);
cJSON_Delete(filter);
if (!events_json) {
return -1;
}
cJSON* arr = cJSON_Parse(events_json);
free(events_json);
if (!arr || !cJSON_IsArray(arr) || cJSON_GetArraySize(arr) <= 0) {
cJSON_Delete(arr);
*out_ciphertext = strdup("");
return (*out_ciphertext != NULL) ? 0 : -1;
}
cJSON* ev = cJSON_GetArrayItem(arr, 0);
cJSON* content = ev ? cJSON_GetObjectItemCaseSensitive(ev, "content") : NULL;
const char* cipher = (content && cJSON_IsString(content) && content->valuestring) ? content->valuestring : "";
*out_ciphertext = strdup(cipher);
cJSON_Delete(arr);
return (*out_ciphertext != NULL) ? 0 : -1;
}
static int memory_load_local(tools_context_t* ctx) {
char* ciphertext = NULL;
if (query_memory_ciphertext_local(ctx, &ciphertext) != 0) {
return -1;
}
char* plaintext = NULL;
if (!ciphertext || ciphertext[0] == '\0') {
plaintext = strdup("");
} else if (nip44_decrypt_self_local(ctx, ciphertext, &plaintext) != 0) {
fprintf(stdout,
"[didactyl] warning: failed to NIP-44 decrypt memory; resetting to empty\n");
plaintext = strdup("");
}
free(ciphertext);
if (!plaintext) return -1;
pthread_mutex_lock(&g_memory_mutex);
memory_cache_set_locked_local(plaintext);
pthread_mutex_unlock(&g_memory_mutex);
free(plaintext);
return 0;
}
static char* trim_and_limit_entry_local(const char* in, int* out_truncated) {
if (out_truncated) *out_truncated = 0;
if (!in) return strdup("");
while (*in == ' ' || *in == '\t' || *in == '\r' || *in == '\n') in++;
size_t n = strlen(in);
while (n > 0 && (in[n - 1] == ' ' || in[n - 1] == '\t' || in[n - 1] == '\r' || in[n - 1] == '\n')) {
n--;
}
if (n > MEMORY_MAX_CHARS) {
n = MEMORY_MAX_CHARS;
if (out_truncated) *out_truncated = 1;
}
char* out = (char*)malloc(n + 1U);
if (!out) return NULL;
if (n > 0) memcpy(out, in, n);
out[n] = '\0';
return out;
}
static char* prepend_and_truncate_local(const char* existing, const char* incoming, int* out_truncated) {
if (out_truncated) *out_truncated = 0;
const char* old = existing ? existing : "";
const char* add = incoming ? incoming : "";
const char* sep = "\n\n---\n\n";
size_t add_len = strlen(add);
size_t old_len = strlen(old);
size_t sep_len = (add_len > 0 && old_len > 0) ? strlen(sep) : 0U;
size_t total_len = add_len + sep_len + old_len;
char* joined = (char*)malloc(total_len + 1U);
if (!joined) return NULL;
size_t used = 0U;
if (add_len > 0) {
memcpy(joined + used, add, add_len);
used += add_len;
}
if (sep_len > 0) {
memcpy(joined + used, sep, sep_len);
used += sep_len;
}
if (old_len > 0) {
memcpy(joined + used, old, old_len);
used += old_len;
}
joined[used] = '\0';
if (used <= MEMORY_MAX_CHARS) {
return joined;
}
if (out_truncated) *out_truncated = 1;
char* clipped = (char*)malloc(MEMORY_MAX_CHARS + 1U);
if (!clipped) {
free(joined);
return NULL;
}
memcpy(clipped, joined, MEMORY_MAX_CHARS);
clipped[MEMORY_MAX_CHARS] = '\0';
free(joined);
return clipped;
}
int memory_init(tools_context_t* ctx) {
if (!ctx || !ctx->cfg) return -1;
return memory_load_local(ctx);
}
void memory_cleanup(void) {
pthread_mutex_lock(&g_memory_mutex);
free(g_memory_plain);
g_memory_plain = NULL;
g_memory_loaded = 0;
pthread_mutex_unlock(&g_memory_mutex);
}
char* execute_memory_save(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* content_j = cJSON_GetObjectItemCaseSensitive(args, "content");
if (!content_j || !cJSON_IsString(content_j) || !content_j->valuestring) {
cJSON_Delete(args);
return json_error_local("memory_save requires string content");
}
int entry_truncated = 0;
char* incoming = trim_and_limit_entry_local(content_j->valuestring, &entry_truncated);
cJSON_Delete(args);
if (!incoming) return NULL;
if (incoming[0] == '\0') {
free(incoming);
return json_error_local("memory_save content cannot be empty");
}
pthread_mutex_lock(&g_memory_mutex);
char* old_copy = memory_cache_get_copy_locked_local();
pthread_mutex_unlock(&g_memory_mutex);
if (!old_copy) {
free(incoming);
return NULL;
}
int body_truncated = 0;
char* merged = prepend_and_truncate_local(old_copy, incoming, &body_truncated);
free(old_copy);
free(incoming);
if (!merged) return NULL;
char* ciphertext = NULL;
if (nip44_encrypt_self_local(ctx, merged, &ciphertext) != 0) {
free(merged);
return json_error_local("memory_save NIP-44 encryption failed");
}
cJSON* tags = cJSON_CreateArray();
if (!tags) {
free(merged);
free(ciphertext);
return NULL;
}
cJSON* d_tag = cJSON_CreateArray();
cJSON* app_tag = cJSON_CreateArray();
if (!d_tag || !app_tag) {
cJSON_Delete(d_tag);
cJSON_Delete(app_tag);
cJSON_Delete(tags);
free(merged);
free(ciphertext);
return NULL;
}
cJSON_AddItemToArray(d_tag, cJSON_CreateString("d"));
cJSON_AddItemToArray(d_tag, cJSON_CreateString(MEMORY_D_TAG));
cJSON_AddItemToArray(tags, d_tag);
cJSON_AddItemToArray(app_tag, cJSON_CreateString("app"));
cJSON_AddItemToArray(app_tag, cJSON_CreateString(MEMORY_APP_TAG));
cJSON_AddItemToArray(tags, app_tag);
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event(MEMORY_KIND, ciphertext, tags, &publish_result);
cJSON_Delete(tags);
free(ciphertext);
if (rc != 0) {
free(merged);
nostr_handler_publish_result_free(&publish_result);
return json_error_local("memory_save publish failed");
}
pthread_mutex_lock(&g_memory_mutex);
memory_cache_set_locked_local(merged);
pthread_mutex_unlock(&g_memory_mutex);
cJSON* out = cJSON_CreateObject();
if (!out) {
free(merged);
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "d_tag", MEMORY_D_TAG);
cJSON_AddNumberToObject(out, "kind", MEMORY_KIND);
cJSON_AddNumberToObject(out, "entry_length", (double)strlen(merged));
cJSON_AddBoolToObject(out, "truncated", (entry_truncated || body_truncated) ? 1 : 0);
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(merged);
nostr_handler_publish_result_free(&publish_result);
return json;
}
char* execute_memory_recall(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
pthread_mutex_lock(&g_memory_mutex);
int loaded = g_memory_loaded;
pthread_mutex_unlock(&g_memory_mutex);
if (!loaded) {
(void)memory_load_local(ctx);
}
pthread_mutex_lock(&g_memory_mutex);
char* memory = memory_cache_get_copy_locked_local();
pthread_mutex_unlock(&g_memory_mutex);
if (!memory) return NULL;
cJSON* out = cJSON_CreateObject();
if (!out) {
free(memory);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", memory);
cJSON_AddNumberToObject(out, "content_length", (double)strlen(memory));
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(memory);
return json;
}
char* execute_my_memory(tools_context_t* ctx, const char* args_json) {
return execute_memory_recall(ctx, args_json);
}
char* execute_memory_short_term_read(tools_context_t* ctx, const char* args_json) {
(void)ctx;
(void)args_json;
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", "");
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
+103
View File
@@ -0,0 +1,103 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdlib.h>
#include "cjson/cJSON.h"
#include "../trigger_manager.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
char* execute_tool_list(tools_context_t* ctx, const char* args_json) {
(void)args_json;
if (!ctx) {
return json_error_local("tool context unavailable");
}
char* schema_json = tools_build_openai_schema_json(ctx);
if (!schema_json) {
return json_error_local("failed to build tool schemas");
}
cJSON* schema_arr = cJSON_Parse(schema_json);
free(schema_json);
if (!schema_arr || !cJSON_IsArray(schema_arr)) {
cJSON_Delete(schema_arr);
return json_error_local("failed to parse tool schemas");
}
cJSON* out = cJSON_CreateObject();
cJSON* tools = cJSON_CreateArray();
if (!out || !tools) {
cJSON_Delete(schema_arr);
cJSON_Delete(out);
cJSON_Delete(tools);
return json_error_local("out of memory");
}
cJSON* item = NULL;
cJSON_ArrayForEach(item, schema_arr) {
cJSON* fn = cJSON_GetObjectItemCaseSensitive(item, "function");
if (!fn || !cJSON_IsObject(fn)) {
continue;
}
cJSON* name = cJSON_GetObjectItemCaseSensitive(fn, "name");
if (!name || !cJSON_IsString(name) || !name->valuestring) {
continue;
}
cJSON* row = cJSON_CreateObject();
if (!row) {
continue;
}
cJSON_AddStringToObject(row, "name", name->valuestring);
cJSON* description = cJSON_GetObjectItemCaseSensitive(fn, "description");
if (description && cJSON_IsString(description) && description->valuestring) {
cJSON_AddStringToObject(row, "description", description->valuestring);
} else {
cJSON_AddStringToObject(row, "description", "");
}
cJSON* parameters = cJSON_GetObjectItemCaseSensitive(fn, "parameters");
if (parameters) {
cJSON_AddItemToObject(row, "parameters", cJSON_Duplicate(parameters, 1));
} else {
cJSON_AddItemToObject(row, "parameters", cJSON_CreateObject());
}
cJSON_AddItemToArray(tools, row);
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddNumberToObject(out, "count", (double)cJSON_GetArraySize(tools));
cJSON_AddItemToObject(out, "tools", tools);
char* result = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
cJSON_Delete(schema_arr);
return result;
}
char* execute_trigger_list(tools_context_t* ctx, const char* args_json) {
(void)args_json;
if (!ctx || !ctx->trigger_manager) {
return json_error_local("trigger manager unavailable");
}
char* status = trigger_manager_status_json(ctx->trigger_manager);
if (!status) {
return json_error_local("failed to build trigger status");
}
return status;
}
+317
View File
@@ -0,0 +1,317 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../config.h"
#include "../llm.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static int persist_llm_config_nostr(tools_context_t* ctx, const llm_config_t* cfg, char** out_error) {
if (!ctx || !ctx->cfg || !cfg) {
if (out_error) *out_error = strdup("invalid persist context");
return -1;
}
if (out_error) *out_error = NULL;
cJSON* args = cJSON_CreateObject();
cJSON* content = cJSON_CreateObject();
if (!args || !content) {
cJSON_Delete(args);
cJSON_Delete(content);
if (out_error) *out_error = strdup("allocation failure while building llm_config payload");
return -1;
}
cJSON_AddStringToObject(args, "d_tag", "llm_config");
cJSON_AddStringToObject(content, "provider", cfg->provider);
cJSON_AddStringToObject(content, "api_key", cfg->api_key);
cJSON_AddStringToObject(content, "model", cfg->model);
cJSON_AddStringToObject(content, "base_url", cfg->base_url);
cJSON_AddNumberToObject(content, "max_tokens", cfg->max_tokens);
cJSON_AddNumberToObject(content, "temperature", cfg->temperature);
cJSON_AddItemToObject(args, "content", content);
char* store_args_json = cJSON_PrintUnformatted(args);
cJSON_Delete(args);
if (!store_args_json) {
if (out_error) *out_error = strdup("failed to serialize llm_config payload");
return -1;
}
char* store_result = execute_config_store(ctx, store_args_json);
free(store_args_json);
if (!store_result) {
if (out_error) *out_error = strdup("config_store returned no response");
return -1;
}
cJSON* root = cJSON_Parse(store_result);
if (!root || !cJSON_IsObject(root)) {
cJSON_Delete(root);
if (out_error) *out_error = strdup("config_store returned invalid JSON");
free(store_result);
return -1;
}
cJSON* success = cJSON_GetObjectItemCaseSensitive(root, "success");
if (!success || !cJSON_IsBool(success) || !cJSON_IsTrue(success)) {
cJSON* err = cJSON_GetObjectItemCaseSensitive(root, "error");
if (out_error) {
if (err && cJSON_IsString(err) && err->valuestring) {
*out_error = strdup(err->valuestring);
} else {
*out_error = strdup("config_store failed");
}
}
cJSON_Delete(root);
free(store_result);
return -1;
}
cJSON_Delete(root);
free(store_result);
return 0;
}
static int assign_string_field(cJSON* item, char* dst, size_t dst_size, int* changed) {
if (!item) return 0;
if (!cJSON_IsString(item) || !item->valuestring) return -1;
size_t n = strlen(item->valuestring);
if (n >= dst_size) return -1;
memcpy(dst, item->valuestring, n + 1U);
if (changed) *changed = 1;
return 0;
}
static void mask_api_key_local(const char* api_key, char* out, size_t out_size) {
if (!out || out_size == 0) return;
out[0] = '\0';
if (!api_key || api_key[0] == '\0') {
return;
}
size_t api_len = strlen(api_key);
if (api_len >= 8U) {
snprintf(out,
out_size,
"%.4s...%s",
api_key,
api_key + api_len - 4U);
} else {
snprintf(out, out_size, "%s", "(set)");
}
}
char* execute_model_get(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
llm_config_t cfg;
if (llm_get_config(&cfg) != 0) {
return json_error_local("llm runtime unavailable");
}
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
char api_key_masked[64] = {0};
mask_api_key_local(cfg.api_key, api_key_masked, sizeof(api_key_masked));
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "provider", cfg.provider);
cJSON_AddStringToObject(out, "model", cfg.model);
cJSON_AddStringToObject(out, "base_url", cfg.base_url);
cJSON_AddStringToObject(out, "api_key", api_key_masked);
cJSON_AddNumberToObject(out, "max_tokens", cfg.max_tokens);
cJSON_AddNumberToObject(out, "temperature", cfg.temperature);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_model_set(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
llm_config_t cfg;
if (llm_get_config(&cfg) != 0) {
cJSON_Delete(args);
return json_error_local("llm runtime unavailable");
}
int changed = 0;
cJSON* provider = cJSON_GetObjectItemCaseSensitive(args, "provider");
cJSON* api_key = cJSON_GetObjectItemCaseSensitive(args, "api_key");
cJSON* model = cJSON_GetObjectItemCaseSensitive(args, "model");
cJSON* base_url = cJSON_GetObjectItemCaseSensitive(args, "base_url");
cJSON* max_tokens = cJSON_GetObjectItemCaseSensitive(args, "max_tokens");
cJSON* temperature = cJSON_GetObjectItemCaseSensitive(args, "temperature");
if (assign_string_field(provider, cfg.provider, sizeof(cfg.provider), &changed) != 0 ||
assign_string_field(api_key, cfg.api_key, sizeof(cfg.api_key), &changed) != 0 ||
assign_string_field(model, cfg.model, sizeof(cfg.model), &changed) != 0 ||
assign_string_field(base_url, cfg.base_url, sizeof(cfg.base_url), &changed) != 0) {
cJSON_Delete(args);
return json_error_local("model_set string field invalid or too long");
}
if (max_tokens) {
if (!cJSON_IsNumber(max_tokens)) {
cJSON_Delete(args);
return json_error_local("model_set max_tokens must be a number");
}
cfg.max_tokens = (int)max_tokens->valuedouble;
changed = 1;
}
if (temperature) {
if (!cJSON_IsNumber(temperature)) {
cJSON_Delete(args);
return json_error_local("model_set temperature must be a number");
}
cfg.temperature = temperature->valuedouble;
changed = 1;
}
cJSON_Delete(args);
if (!changed) {
return json_error_local("model_set requires at least one field to update");
}
if (llm_set_config(&cfg) != 0) {
return json_error_local("failed to update runtime llm config");
}
ctx->cfg->llm = cfg;
char* persist_error = NULL;
int persisted = (persist_llm_config_nostr(ctx, &cfg, &persist_error) == 0) ? 1 : 0;
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
char api_key_masked[64] = {0};
mask_api_key_local(cfg.api_key, api_key_masked, sizeof(api_key_masked));
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "provider", cfg.provider);
cJSON_AddStringToObject(out, "model", cfg.model);
cJSON_AddStringToObject(out, "base_url", cfg.base_url);
cJSON_AddStringToObject(out, "api_key", api_key_masked);
cJSON_AddNumberToObject(out, "max_tokens", cfg.max_tokens);
cJSON_AddNumberToObject(out, "temperature", cfg.temperature);
cJSON_AddBoolToObject(out, "persisted", persisted ? 1 : 0);
if (!persisted && persist_error && persist_error[0] != '\0') {
cJSON_AddStringToObject(out, "persist_warning", persist_error);
}
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(persist_error);
return json;
}
static void append_model_id(cJSON* ids, cJSON* item) {
if (!ids || !item) return;
if (cJSON_IsString(item) && item->valuestring) {
cJSON_AddItemToArray(ids, cJSON_CreateString(item->valuestring));
return;
}
if (cJSON_IsObject(item)) {
cJSON* id = cJSON_GetObjectItemCaseSensitive(item, "id");
if (id && cJSON_IsString(id) && id->valuestring) {
cJSON_AddItemToArray(ids, cJSON_CreateString(id->valuestring));
}
}
}
char* execute_model_list(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* base_url = cJSON_GetObjectItemCaseSensitive(args, "base_url");
if (base_url && (!cJSON_IsString(base_url) || !base_url->valuestring)) {
cJSON_Delete(args);
return json_error_local("model_list base_url must be a string");
}
const char* base_url_override = (base_url && base_url->valuestring && base_url->valuestring[0] != '\0')
? base_url->valuestring
: NULL;
char* raw = llm_list_models_json(base_url_override);
cJSON_Delete(args);
if (!raw) {
return json_error_local("model_list request failed");
}
cJSON* root = cJSON_Parse(raw);
free(raw);
if (!root) {
cJSON_Delete(root);
return json_error_local("model_list returned invalid JSON");
}
cJSON* ids = cJSON_CreateArray();
cJSON* out = cJSON_CreateObject();
if (!ids || !out) {
cJSON_Delete(ids);
cJSON_Delete(out);
cJSON_Delete(root);
return NULL;
}
if (cJSON_IsArray(root)) {
int n = cJSON_GetArraySize(root);
for (int i = 0; i < n; i++) {
append_model_id(ids, cJSON_GetArrayItem(root, i));
}
} else if (cJSON_IsObject(root)) {
cJSON* data = cJSON_GetObjectItemCaseSensitive(root, "data");
if (data && cJSON_IsArray(data)) {
int n = cJSON_GetArraySize(data);
for (int i = 0; i < n; i++) {
append_model_id(ids, cJSON_GetArrayItem(data, i));
}
}
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddNumberToObject(out, "count", cJSON_GetArraySize(ids));
cJSON_AddItemToObject(out, "models", ids);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
cJSON_Delete(root);
return json;
}
+218
View File
@@ -0,0 +1,218 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static int is_hex_string_len_local(const char* s, size_t expected_len) {
if (!s) return 0;
if (strlen(s) != expected_len) return 0;
for (size_t i = 0; i < expected_len; i++) {
if (!((s[i] >= '0' && s[i] <= '9') ||
(s[i] >= 'a' && s[i] <= 'f') ||
(s[i] >= 'A' && s[i] <= 'F'))) {
return 0;
}
}
return 1;
}
char* execute_nostr_dm_send(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* recipient = cJSON_GetObjectItemCaseSensitive(args, "recipient_pubkey");
cJSON* message = cJSON_GetObjectItemCaseSensitive(args, "message");
if (!recipient || !cJSON_IsString(recipient) || !recipient->valuestring || !is_hex_string_len_local(recipient->valuestring, 64U) ||
!message || !cJSON_IsString(message) || !message->valuestring || message->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_dm_send requires recipient_pubkey hex and non-empty message");
}
int rc = nostr_handler_send_dm(recipient->valuestring, message->valuestring);
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(args);
return NULL;
}
cJSON_AddBoolToObject(out, "success", rc == 0 ? 1 : 0);
cJSON_AddStringToObject(out, "recipient_pubkey", recipient->valuestring);
cJSON_AddNumberToObject(out, "message_length", (double)strlen(message->valuestring));
cJSON_Delete(args);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_encrypt(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* recipient = cJSON_GetObjectItemCaseSensitive(args, "recipient_pubkey");
cJSON* plaintext = cJSON_GetObjectItemCaseSensitive(args, "plaintext");
if (!recipient || !cJSON_IsString(recipient) || !recipient->valuestring || !is_hex_string_len_local(recipient->valuestring, 64U) ||
!plaintext || !cJSON_IsString(plaintext) || !plaintext->valuestring || plaintext->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_encrypt requires recipient_pubkey hex and plaintext");
}
unsigned char recipient_pubkey[32];
if (nostr_hex_to_bytes(recipient->valuestring, recipient_pubkey, sizeof(recipient_pubkey)) != 0) {
cJSON_Delete(args);
return json_error_local("nostr_encrypt invalid recipient_pubkey");
}
size_t out_cap = (strlen(plaintext->valuestring) * 4U) + 1024U;
char* ciphertext = (char*)malloc(out_cap);
if (!ciphertext) {
cJSON_Delete(args);
return json_error_local("allocation failure");
}
int rc = nostr_nip44_encrypt(ctx->cfg->keys.private_key,
recipient_pubkey,
plaintext->valuestring,
ciphertext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(ciphertext);
cJSON_Delete(args);
return json_error_local("nostr_encrypt failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
free(ciphertext);
cJSON_Delete(args);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "recipient_pubkey", recipient->valuestring);
cJSON_AddStringToObject(out, "ciphertext", ciphertext);
free(ciphertext);
cJSON_Delete(args);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_decrypt(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* sender = cJSON_GetObjectItemCaseSensitive(args, "sender_pubkey");
cJSON* ciphertext = cJSON_GetObjectItemCaseSensitive(args, "ciphertext");
if (!sender || !cJSON_IsString(sender) || !sender->valuestring || !is_hex_string_len_local(sender->valuestring, 64U) ||
!ciphertext || !cJSON_IsString(ciphertext) || !ciphertext->valuestring || ciphertext->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_decrypt requires sender_pubkey hex and ciphertext");
}
unsigned char sender_pubkey[32];
if (nostr_hex_to_bytes(sender->valuestring, sender_pubkey, sizeof(sender_pubkey)) != 0) {
cJSON_Delete(args);
return json_error_local("nostr_decrypt invalid sender_pubkey");
}
size_t out_cap = strlen(ciphertext->valuestring) + 1024U;
char* plaintext = (char*)malloc(out_cap);
if (!plaintext) {
cJSON_Delete(args);
return json_error_local("allocation failure");
}
int rc = nostr_nip44_decrypt(ctx->cfg->keys.private_key,
sender_pubkey,
ciphertext->valuestring,
plaintext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(plaintext);
cJSON_Delete(args);
return json_error_local("nostr_decrypt failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
free(plaintext);
cJSON_Delete(args);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "sender_pubkey", sender->valuestring);
cJSON_AddStringToObject(out, "plaintext", plaintext);
free(plaintext);
cJSON_Delete(args);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_dm_send_nip17(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* recipient = cJSON_GetObjectItemCaseSensitive(args, "recipient_pubkey");
cJSON* message = cJSON_GetObjectItemCaseSensitive(args, "message");
cJSON* subject = cJSON_GetObjectItemCaseSensitive(args, "subject");
if (!recipient || !cJSON_IsString(recipient) || !recipient->valuestring || !is_hex_string_len_local(recipient->valuestring, 64U) ||
!message || !cJSON_IsString(message) || !message->valuestring || message->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_dm_send_nip17 requires recipient_pubkey hex and non-empty message");
}
if (subject && !cJSON_IsString(subject)) {
cJSON_Delete(args);
return json_error_local("nostr_dm_send_nip17 subject must be a string when provided");
}
int rc = nostr_handler_send_dm_nip17(recipient->valuestring,
message->valuestring,
(subject && subject->valuestring) ? subject->valuestring : NULL);
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(args);
return NULL;
}
cJSON_AddBoolToObject(out, "success", rc == 0 ? 1 : 0);
cJSON_AddStringToObject(out, "recipient_pubkey", recipient->valuestring);
cJSON_AddStringToObject(out, "protocol", "nip17");
cJSON_AddNumberToObject(out, "message_length", (double)strlen(message->valuestring));
cJSON_Delete(args);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
+257
View File
@@ -0,0 +1,257 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static int is_hex_string_len_local(const char* s, size_t expected_len) {
if (!s) return 0;
if (strlen(s) != expected_len) return 0;
for (size_t i = 0; i < expected_len; i++) {
if (!((s[i] >= '0' && s[i] <= '9') ||
(s[i] >= 'a' && s[i] <= 'f') ||
(s[i] >= 'A' && s[i] <= 'F'))) {
return 0;
}
}
return 1;
}
char* execute_nostr_encode(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* type = cJSON_GetObjectItemCaseSensitive(args, "type");
cJSON* hex = cJSON_GetObjectItemCaseSensitive(args, "hex");
cJSON* relays = cJSON_GetObjectItemCaseSensitive(args, "relays");
cJSON* kind = cJSON_GetObjectItemCaseSensitive(args, "kind");
cJSON* identifier = cJSON_GetObjectItemCaseSensitive(args, "identifier");
if (!type || !cJSON_IsString(type) || !type->valuestring ||
!hex || !cJSON_IsString(hex) || !hex->valuestring || !is_hex_string_len_local(hex->valuestring, 64U)) {
cJSON_Delete(args);
return json_error_local("nostr_encode requires type string and hex 64-char string");
}
char type_name[32];
snprintf(type_name, sizeof(type_name), "%s", type->valuestring);
unsigned char key_bytes[32];
if (nostr_hex_to_bytes(hex->valuestring, key_bytes, sizeof(key_bytes)) != 0) {
cJSON_Delete(args);
return json_error_local("nostr_encode invalid hex");
}
const char** relay_ptrs = NULL;
int relay_count = 0;
if (relays) {
if (!cJSON_IsArray(relays)) {
cJSON_Delete(args);
return json_error_local("nostr_encode relays must be an array of relay URLs");
}
relay_count = cJSON_GetArraySize(relays);
if (relay_count > 0) {
relay_ptrs = (const char**)malloc((size_t)relay_count * sizeof(char*));
if (!relay_ptrs) {
cJSON_Delete(args);
return json_error_local("memory allocation failed");
}
for (int i = 0; i < relay_count; i++) {
cJSON* relay = cJSON_GetArrayItem(relays, i);
if (!relay || !cJSON_IsString(relay) || !relay->valuestring || relay->valuestring[0] == '\0') {
free(relay_ptrs);
cJSON_Delete(args);
return json_error_local("nostr_encode relays must contain non-empty strings");
}
relay_ptrs[i] = relay->valuestring;
}
}
}
char bech32[256] = {0};
char uri[1200] = {0};
int rc = NOSTR_ERROR_INVALID_INPUT;
if (strcmp(type_name, "npub") == 0) {
rc = nostr_key_to_bech32(key_bytes, "npub", bech32);
if (rc == NOSTR_SUCCESS) {
snprintf(uri, sizeof(uri), "nostr:%s", bech32);
}
} else if (strcmp(type_name, "nsec") == 0) {
rc = nostr_key_to_bech32(key_bytes, "nsec", bech32);
if (rc == NOSTR_SUCCESS) {
snprintf(uri, sizeof(uri), "nostr:%s", bech32);
}
} else if (strcmp(type_name, "note") == 0) {
rc = nostr_key_to_bech32(key_bytes, "note", bech32);
if (rc == NOSTR_SUCCESS) {
snprintf(uri, sizeof(uri), "nostr:%s", bech32);
}
} else if (strcmp(type_name, "nprofile") == 0) {
rc = nostr_build_uri_nprofile(key_bytes, relay_ptrs, relay_count, uri, sizeof(uri));
} else if (strcmp(type_name, "nevent") == 0) {
int kind_value = -1;
if (kind) {
if (!cJSON_IsNumber(kind)) {
free(relay_ptrs);
cJSON_Delete(args);
return json_error_local("nostr_encode nevent kind must be an integer");
}
kind_value = (int)kind->valuedouble;
}
rc = nostr_build_uri_nevent(key_bytes, relay_ptrs, relay_count, NULL, kind_value, 0, uri, sizeof(uri));
} else if (strcmp(type_name, "naddr") == 0) {
if (!kind || !cJSON_IsNumber(kind)) {
free(relay_ptrs);
cJSON_Delete(args);
return json_error_local("nostr_encode naddr requires kind integer");
}
if (!identifier || !cJSON_IsString(identifier) || !identifier->valuestring || identifier->valuestring[0] == '\0') {
free(relay_ptrs);
cJSON_Delete(args);
return json_error_local("nostr_encode naddr requires non-empty identifier string");
}
rc = nostr_build_uri_naddr(identifier->valuestring, key_bytes, (int)kind->valuedouble,
relay_ptrs, relay_count, uri, sizeof(uri));
} else {
free(relay_ptrs);
cJSON_Delete(args);
return json_error_local("nostr_encode currently supports npub, nsec, note, nprofile, nevent, naddr");
}
free(relay_ptrs);
cJSON_Delete(args);
if (rc != NOSTR_SUCCESS) {
return json_error_local("nostr_encode failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "type", type_name);
cJSON_AddStringToObject(out, "uri", uri);
cJSON_AddBoolToObject(out, "limited_support", 1);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_decode(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* uri_in = cJSON_GetObjectItemCaseSensitive(args, "uri");
if (!uri_in || !cJSON_IsString(uri_in) || !uri_in->valuestring || uri_in->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_decode requires uri string");
}
const char* in = uri_in->valuestring;
if (strncmp(in, "nostr:", 6) == 0) {
in += 6;
}
unsigned char key[32];
char key_hex[65] = {0};
const char* type = NULL;
int rc = NOSTR_ERROR_INVALID_INPUT;
if (strncmp(in, "npub1", 5) == 0) {
type = "npub";
rc = nostr_decode_npub(in, key);
} else if (strncmp(in, "nsec1", 5) == 0) {
type = "nsec";
rc = nostr_decode_nsec(in, key);
} else {
cJSON_Delete(args);
return json_error_local("nostr_decode currently supports npub and nsec");
}
cJSON_Delete(args);
if (rc != NOSTR_SUCCESS) {
return json_error_local("nostr_decode failed");
}
nostr_bytes_to_hex(key, 32, key_hex);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "type", type);
if (strcmp(type, "npub") == 0) {
cJSON_AddStringToObject(out, "pubkey", key_hex);
} else {
cJSON_AddStringToObject(out, "private_key", key_hex);
}
cJSON_AddBoolToObject(out, "limited_support", 1);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_pubkey(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "pubkey", ctx->cfg->keys.public_key_hex);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_npub(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char npub[256] = {0};
if (nostr_key_to_bech32(ctx->cfg->keys.public_key, "npub", npub) != NOSTR_SUCCESS) {
return json_error_local("failed to encode npub");
}
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "npub", npub);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
+361
View File
@@ -0,0 +1,361 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static int is_hex_string_len_local(const char* s, size_t expected_len) {
if (!s) return 0;
if (strlen(s) != expected_len) return 0;
for (size_t i = 0; i < expected_len; i++) {
if (!((s[i] >= '0' && s[i] <= '9') ||
(s[i] >= 'a' && s[i] <= 'f') ||
(s[i] >= 'A' && s[i] <= 'F'))) {
return 0;
}
}
return 1;
}
static int add_string_tag_local(cJSON* tags, const char* key, const char* value) {
if (!tags || !cJSON_IsArray(tags) || !key || !value) return -1;
cJSON* tuple = cJSON_CreateArray();
if (!tuple) return -1;
cJSON_AddItemToArray(tuple, cJSON_CreateString(key));
cJSON_AddItemToArray(tuple, cJSON_CreateString(value));
cJSON_AddItemToArray(tags, tuple);
return 0;
}
static int tag_tuple_equal_local(cJSON* a, cJSON* b) {
if (!a || !b || !cJSON_IsArray(a) || !cJSON_IsArray(b)) return 0;
int an = cJSON_GetArraySize(a);
int bn = cJSON_GetArraySize(b);
if (an != bn) return 0;
for (int i = 0; i < an; i++) {
cJSON* av = cJSON_GetArrayItem(a, i);
cJSON* bv = cJSON_GetArrayItem(b, i);
if (!av || !bv || !cJSON_IsString(av) || !cJSON_IsString(bv) || !av->valuestring || !bv->valuestring) {
return 0;
}
if (strcmp(av->valuestring, bv->valuestring) != 0) return 0;
}
return 1;
}
static int tags_contains_tuple_local(cJSON* tags, cJSON* tuple) {
if (!tags || !tuple || !cJSON_IsArray(tags) || !cJSON_IsArray(tuple)) return 0;
int n = cJSON_GetArraySize(tags);
for (int i = 0; i < n; i++) {
cJSON* t = cJSON_GetArrayItem(tags, i);
if (tag_tuple_equal_local(t, tuple)) return 1;
}
return 0;
}
static int remove_matching_tag_tuples_local(cJSON* tags, cJSON* tuple) {
if (!tags || !tuple || !cJSON_IsArray(tags) || !cJSON_IsArray(tuple)) return 0;
int removed = 0;
for (int i = cJSON_GetArraySize(tags) - 1; i >= 0; i--) {
cJSON* t = cJSON_GetArrayItem(tags, i);
if (tag_tuple_equal_local(t, tuple)) {
cJSON_DeleteItemFromArray(tags, i);
removed++;
}
}
return removed;
}
char* execute_nostr_delete(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* event_ids = cJSON_GetObjectItemCaseSensitive(args, "event_ids");
cJSON* kinds = cJSON_GetObjectItemCaseSensitive(args, "kinds");
cJSON* reason = cJSON_GetObjectItemCaseSensitive(args, "reason");
if (!event_ids || !cJSON_IsArray(event_ids) || cJSON_GetArraySize(event_ids) <= 0) {
cJSON_Delete(args);
return json_error_local("nostr_delete requires non-empty event_ids array");
}
if (kinds && !cJSON_IsArray(kinds)) {
cJSON_Delete(args);
return json_error_local("nostr_delete kinds must be an array when provided");
}
if (reason && !cJSON_IsString(reason)) {
cJSON_Delete(args);
return json_error_local("nostr_delete reason must be a string when provided");
}
cJSON* tags = cJSON_CreateArray();
if (!tags) {
cJSON_Delete(args);
return json_error_local("failed to create tags");
}
int event_id_count = cJSON_GetArraySize(event_ids);
for (int i = 0; i < event_id_count; i++) {
cJSON* id = cJSON_GetArrayItem(event_ids, i);
if (!id || !cJSON_IsString(id) || !id->valuestring || !is_hex_string_len_local(id->valuestring, 64U)) {
cJSON_Delete(tags);
cJSON_Delete(args);
return json_error_local("nostr_delete event_ids must contain 64-char hex strings");
}
if (add_string_tag_local(tags, "e", id->valuestring) != 0) {
cJSON_Delete(tags);
cJSON_Delete(args);
return json_error_local("failed to add e tag");
}
}
if (kinds) {
int kind_count = cJSON_GetArraySize(kinds);
for (int i = 0; i < kind_count; i++) {
cJSON* k = cJSON_GetArrayItem(kinds, i);
if (!k || !cJSON_IsNumber(k)) {
cJSON_Delete(tags);
cJSON_Delete(args);
return json_error_local("nostr_delete kinds must contain integers");
}
char kind_buf[32];
snprintf(kind_buf, sizeof(kind_buf), "%d", (int)k->valuedouble);
if (add_string_tag_local(tags, "k", kind_buf) != 0) {
cJSON_Delete(tags);
cJSON_Delete(args);
return json_error_local("failed to add k tag");
}
}
}
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
const char* reason_content = (reason && reason->valuestring) ? reason->valuestring : "";
int rc = nostr_handler_publish_kind_event(5, reason_content, tags, &publish_result);
cJSON_Delete(tags);
cJSON_Delete(args);
if (rc != 0) {
nostr_handler_publish_result_free(&publish_result);
return json_error_local("nostr_delete failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", publish_result.success ? 1 : 0);
cJSON_AddStringToObject(out, "message", "nostr_delete published");
cJSON_AddNumberToObject(out, "kind", publish_result.kind);
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
cJSON_AddNumberToObject(out, "requested_event_count", event_id_count);
cJSON_AddNumberToObject(out, "relay_count", publish_result.relay_count);
cJSON_AddNumberToObject(out, "accepted_by_pool_count", publish_result.accepted_by_pool_count);
cJSON* relays = cJSON_CreateArray();
if (!relays) {
nostr_handler_publish_result_free(&publish_result);
cJSON_Delete(out);
return NULL;
}
for (int i = 0; i < publish_result.relay_count; i++) {
cJSON_AddItemToArray(relays, cJSON_CreateString(publish_result.relays[i] ? publish_result.relays[i] : ""));
}
cJSON_AddItemToObject(out, "relays", relays);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
nostr_handler_publish_result_free(&publish_result);
return json;
}
char* execute_nostr_list_manage(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* list_kind = cJSON_GetObjectItemCaseSensitive(args, "list_kind");
cJSON* action = cJSON_GetObjectItemCaseSensitive(args, "action");
cJSON* items = cJSON_GetObjectItemCaseSensitive(args, "items");
if (!list_kind || !cJSON_IsNumber(list_kind) ||
!action || !cJSON_IsString(action) || !action->valuestring ||
!items || !cJSON_IsArray(items)) {
cJSON_Delete(args);
return json_error_local("nostr_list_manage requires list_kind, action, and items");
}
if (strcmp(action->valuestring, "add") != 0 && strcmp(action->valuestring, "remove") != 0) {
cJSON_Delete(args);
return json_error_local("nostr_list_manage action must be add or remove");
}
cJSON* filter = cJSON_CreateObject();
cJSON* kinds = cJSON_CreateArray();
cJSON* authors = cJSON_CreateArray();
if (!filter || !kinds || !authors) {
cJSON_Delete(filter);
cJSON_Delete(kinds);
cJSON_Delete(authors);
cJSON_Delete(args);
return json_error_local("failed to create list query filter");
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber((int)list_kind->valuedouble));
cJSON_AddItemToObject(filter, "kinds", kinds);
cJSON_AddItemToArray(authors, cJSON_CreateString(ctx->cfg->keys.public_key_hex));
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddNumberToObject(filter, "limit", 1);
char* events_json = nostr_handler_query_json(filter, 8000);
cJSON_Delete(filter);
cJSON* events = events_json ? cJSON_Parse(events_json) : NULL;
free(events_json);
char* list_content = strdup("");
if (!list_content) {
cJSON_Delete(events);
cJSON_Delete(args);
return json_error_local("allocation failure");
}
cJSON* updated_tags = cJSON_CreateArray();
if (!updated_tags) {
free(list_content);
cJSON_Delete(events);
cJSON_Delete(args);
return json_error_local("failed to create list tags");
}
if (events && cJSON_IsArray(events) && cJSON_GetArraySize(events) > 0) {
cJSON* ev0 = cJSON_GetArrayItem(events, 0);
if (ev0 && cJSON_IsObject(ev0)) {
cJSON* content = cJSON_GetObjectItemCaseSensitive(ev0, "content");
if (content && cJSON_IsString(content) && content->valuestring) {
free(list_content);
list_content = strdup(content->valuestring);
if (!list_content) {
cJSON_Delete(updated_tags);
cJSON_Delete(events);
cJSON_Delete(args);
return json_error_local("allocation failure");
}
}
cJSON* tags = cJSON_GetObjectItemCaseSensitive(ev0, "tags");
if (tags && cJSON_IsArray(tags)) {
cJSON_Delete(updated_tags);
updated_tags = cJSON_Duplicate(tags, 1);
if (!updated_tags) {
free(list_content);
cJSON_Delete(events);
cJSON_Delete(args);
return json_error_local("failed to duplicate existing list tags");
}
}
}
}
int items_affected = 0;
int item_count = cJSON_GetArraySize(items);
for (int i = 0; i < item_count; i++) {
cJSON* tuple = cJSON_GetArrayItem(items, i);
if (!tuple || !cJSON_IsArray(tuple) || cJSON_GetArraySize(tuple) <= 0) {
continue;
}
int tuple_ok = 1;
int tuple_size = cJSON_GetArraySize(tuple);
for (int j = 0; j < tuple_size; j++) {
cJSON* part = cJSON_GetArrayItem(tuple, j);
if (!part || !cJSON_IsString(part) || !part->valuestring) {
tuple_ok = 0;
break;
}
}
if (!tuple_ok) {
continue;
}
if (strcmp(action->valuestring, "add") == 0) {
if (!tags_contains_tuple_local(updated_tags, tuple)) {
cJSON* dup = cJSON_Duplicate(tuple, 1);
if (!dup) {
free(list_content);
cJSON_Delete(updated_tags);
cJSON_Delete(events);
cJSON_Delete(args);
return json_error_local("failed to duplicate list item");
}
cJSON_AddItemToArray(updated_tags, dup);
items_affected++;
}
} else {
items_affected += remove_matching_tag_tuples_local(updated_tags, tuple);
}
}
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event((int)list_kind->valuedouble,
list_content,
updated_tags,
&publish_result);
free(list_content);
cJSON_Delete(updated_tags);
cJSON_Delete(events);
if (rc != 0) {
cJSON_Delete(args);
nostr_handler_publish_result_free(&publish_result);
return json_error_local("nostr_list_manage failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(args);
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", publish_result.success ? 1 : 0);
cJSON_AddNumberToObject(out, "list_kind", publish_result.kind);
cJSON_AddStringToObject(out, "action", action->valuestring);
cJSON_Delete(args);
cJSON_AddNumberToObject(out, "items_affected", items_affected);
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
nostr_handler_publish_result_free(&publish_result);
return json;
}
+212
View File
@@ -0,0 +1,212 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static const char* find_d_tag_local(cJSON* tags) {
if (!tags || !cJSON_IsArray(tags)) {
return NULL;
}
int n = cJSON_GetArraySize(tags);
for (int i = 0; i < n; i++) {
cJSON* tag = cJSON_GetArrayItem(tags, i);
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) {
continue;
}
cJSON* key = cJSON_GetArrayItem(tag, 0);
cJSON* value = cJSON_GetArrayItem(tag, 1);
if (!key || !value || !cJSON_IsString(key) || !cJSON_IsString(value) ||
!key->valuestring || !value->valuestring) {
continue;
}
if (strcmp(key->valuestring, "d") == 0) {
return value->valuestring;
}
}
return NULL;
}
char* execute_nostr_my_events(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = cJSON_Parse(args_json ? args_json : "{}");
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return json_error_local("invalid arguments JSON");
}
int limit = 200;
int timeout_ms = 8000;
int kind_filter = -1;
cJSON* limit_item = cJSON_GetObjectItemCaseSensitive(args, "limit");
if (limit_item) {
if (!cJSON_IsNumber(limit_item)) {
cJSON_Delete(args);
return json_error_local("limit must be an integer");
}
limit = (int)limit_item->valuedouble;
if (limit < 1) limit = 1;
if (limit > 2000) limit = 2000;
}
cJSON* timeout_item = cJSON_GetObjectItemCaseSensitive(args, "timeout_ms");
if (timeout_item) {
if (!cJSON_IsNumber(timeout_item)) {
cJSON_Delete(args);
return json_error_local("timeout_ms must be an integer");
}
timeout_ms = (int)timeout_item->valuedouble;
if (timeout_ms < 1000) timeout_ms = 1000;
if (timeout_ms > 60000) timeout_ms = 60000;
}
cJSON* kind_item = cJSON_GetObjectItemCaseSensitive(args, "kind");
if (kind_item) {
if (!cJSON_IsNumber(kind_item)) {
cJSON_Delete(args);
return json_error_local("kind must be an integer when provided");
}
kind_filter = (int)kind_item->valuedouble;
if (kind_filter < 0) {
cJSON_Delete(args);
return json_error_local("kind must be >= 0");
}
}
cJSON* filter = cJSON_CreateObject();
cJSON* authors = cJSON_CreateArray();
if (!filter || !authors) {
cJSON_Delete(filter);
cJSON_Delete(authors);
cJSON_Delete(args);
return json_error_local("failed to build filter");
}
cJSON_AddItemToArray(authors, cJSON_CreateString(ctx->cfg->keys.public_key_hex));
cJSON_AddItemToObject(filter, "authors", authors);
if (kind_filter >= 0) {
cJSON* kinds = cJSON_CreateArray();
if (!kinds) {
cJSON_Delete(filter);
cJSON_Delete(args);
return json_error_local("failed to build kind filter");
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(kind_filter));
cJSON_AddItemToObject(filter, "kinds", kinds);
}
cJSON_AddNumberToObject(filter, "limit", limit);
char* events_json = nostr_handler_query_json(filter, timeout_ms);
cJSON_Delete(filter);
cJSON_Delete(args);
if (!events_json) {
return json_error_local("nostr query failed");
}
cJSON* events = cJSON_Parse(events_json);
free(events_json);
if (!events || !cJSON_IsArray(events)) {
cJSON_Delete(events);
return json_error_local("nostr query returned invalid JSON");
}
cJSON* summarized = cJSON_CreateArray();
cJSON* seen_event_ids = cJSON_CreateObject();
if (!summarized || !seen_event_ids) {
cJSON_Delete(events);
cJSON_Delete(summarized);
cJSON_Delete(seen_event_ids);
return json_error_local("allocation failure");
}
int n = cJSON_GetArraySize(events);
for (int i = 0; i < n; i++) {
cJSON* ev = cJSON_GetArrayItem(events, i);
if (!ev || !cJSON_IsObject(ev)) {
continue;
}
cJSON* kind = cJSON_GetObjectItemCaseSensitive(ev, "kind");
cJSON* id = cJSON_GetObjectItemCaseSensitive(ev, "id");
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(ev, "created_at");
cJSON* tags = cJSON_GetObjectItemCaseSensitive(ev, "tags");
if (!kind || !cJSON_IsNumber(kind) ||
!id || !cJSON_IsString(id) || !id->valuestring ||
!created_at || !cJSON_IsNumber(created_at)) {
continue;
}
cJSON* already_seen = cJSON_GetObjectItemCaseSensitive(seen_event_ids, id->valuestring);
if (already_seen) {
continue;
}
cJSON_AddBoolToObject(seen_event_ids, id->valuestring, 1);
cJSON* item = cJSON_CreateObject();
if (!item) {
continue;
}
cJSON_AddNumberToObject(item, "kind", (int)kind->valuedouble);
cJSON_AddStringToObject(item, "event_id", id->valuestring);
{
char ts_buf[32];
long long ts = (long long)created_at->valuedouble;
snprintf(ts_buf, sizeof(ts_buf), "%lld", ts);
cJSON_AddStringToObject(item, "timestamp", ts_buf);
}
const char* d_tag = find_d_tag_local(tags);
if (d_tag && d_tag[0] != '\0') {
cJSON_AddStringToObject(item, "d_tag", d_tag);
} else {
cJSON_AddNullToObject(item, "d_tag");
}
cJSON_AddBoolToObject(item,
"in_current_cache",
nostr_handler_is_event_in_self_cache(id->valuestring) ? 1 : 0);
cJSON_AddItemToArray(summarized, item);
}
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(events);
cJSON_Delete(summarized);
cJSON_Delete(seen_event_ids);
return json_error_local("allocation failure");
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddNumberToObject(out, "count", cJSON_GetArraySize(summarized));
cJSON_AddItemToObject(out, "events", summarized);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
cJSON_Delete(events);
cJSON_Delete(seen_event_ids);
return json;
}
+927
View File
@@ -0,0 +1,927 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static const char* skip_ws_local(const char* p) {
while (p && *p && isspace((unsigned char)*p)) p++;
return p;
}
static char* sanitize_json_string_controls_local(const char* in) {
if (!in) return NULL;
size_t len = strlen(in);
size_t cap = (len * 2U) + 1U;
char* out = (char*)malloc(cap);
if (!out) return NULL;
int in_string = 0;
int escaping = 0;
size_t j = 0;
for (size_t i = 0; i < len; i++) {
char c = in[i];
if (escaping) {
if (j + 1U >= cap) {
free(out);
return NULL;
}
out[j++] = c;
escaping = 0;
continue;
}
if (c == '\\') {
if (j + 1U >= cap) {
free(out);
return NULL;
}
out[j++] = c;
if (in_string) escaping = 1;
continue;
}
if (c == '"') {
if (j + 1U >= cap) {
free(out);
return NULL;
}
out[j++] = c;
in_string = !in_string;
continue;
}
if (in_string && (c == '\n' || c == '\r' || c == '\t')) {
if (j + 2U >= cap) {
free(out);
return NULL;
}
out[j++] = '\\';
out[j++] = (c == '\n') ? 'n' : (c == '\r') ? 'r' : 't';
continue;
}
if (j + 1U >= cap) {
free(out);
return NULL;
}
out[j++] = c;
}
out[j] = '\0';
return out;
}
static cJSON* parse_tool_args_json_local(const char* args_json) {
const char* raw_args_json = args_json ? args_json : "{}";
raw_args_json = skip_ws_local(raw_args_json);
if (!raw_args_json || raw_args_json[0] == '\0') {
raw_args_json = "{}";
}
cJSON* args = cJSON_Parse(raw_args_json);
char* repaired_args_json = NULL;
if (args && cJSON_IsString(args) && args->valuestring) {
cJSON* nested = cJSON_Parse(args->valuestring);
if (nested) {
cJSON_Delete(args);
args = nested;
}
}
if (!args) {
repaired_args_json = sanitize_json_string_controls_local(raw_args_json);
if (repaired_args_json) {
args = cJSON_Parse(repaired_args_json);
if (args && cJSON_IsString(args) && args->valuestring) {
cJSON* nested = cJSON_Parse(args->valuestring);
if (nested) {
cJSON_Delete(args);
args = nested;
}
}
}
}
free(repaired_args_json);
return args;
}
static const char* find_key_start_local(const char* in, const char* key) {
if (!in || !key) return NULL;
char pattern[64];
int n = snprintf(pattern, sizeof(pattern), "\"%s\"", key);
if (n <= 0 || (size_t)n >= sizeof(pattern)) return NULL;
return strstr(in, pattern);
}
static int parse_loose_kind_local(const char* in, int* out_kind) {
if (!in || !out_kind) return -1;
const char* p = find_key_start_local(in, "kind");
if (!p) return -1;
p = strchr(p, ':');
if (!p) return -1;
p = skip_ws_local(p + 1);
if (!p || !*p) return -1;
char* end = NULL;
long v = strtol(p, &end, 10);
if (end == p) return -1;
*out_kind = (int)v;
return 0;
}
static char* parse_loose_json_string_value_local(const char* in, const char* key) {
if (!in || !key) return NULL;
const char* p = find_key_start_local(in, key);
if (!p) return NULL;
p = strchr(p, ':');
if (!p) return NULL;
p = skip_ws_local(p + 1);
if (!p || *p != '"') return NULL;
p++;
size_t max_len = strlen(p);
char* out = (char*)malloc(max_len + 1U);
if (!out) return NULL;
size_t j = 0;
int escaping = 0;
for (size_t i = 0; p[i] != '\0'; i++) {
char c = p[i];
if (escaping) {
switch (c) {
case 'n': out[j++] = '\n'; break;
case 'r': out[j++] = '\r'; break;
case 't': out[j++] = '\t'; break;
case '"': out[j++] = '"'; break;
case '\\': out[j++] = '\\'; break;
default: out[j++] = c; break;
}
escaping = 0;
continue;
}
if (c == '\\') {
escaping = 1;
continue;
}
if (c == '"') {
out[j] = '\0';
return out;
}
out[j++] = c;
}
out[j] = '\0';
return out;
}
static cJSON* parse_loose_nostr_post_args_local(const char* in) {
if (!in) return NULL;
int kind = 0;
if (parse_loose_kind_local(in, &kind) != 0) {
return NULL;
}
char* content = parse_loose_json_string_value_local(in, "content");
if (!content) {
return NULL;
}
cJSON* args = cJSON_CreateObject();
if (!args) {
free(content);
return NULL;
}
cJSON_AddNumberToObject(args, "kind", kind);
cJSON_AddStringToObject(args, "content", content);
free(content);
return args;
}
static cJSON* ensure_tags_array_local(cJSON** tags_inout) {
if (!tags_inout) return NULL;
if (*tags_inout) {
if (cJSON_IsArray(*tags_inout)) {
return *tags_inout;
}
cJSON_Delete(*tags_inout);
*tags_inout = NULL;
}
*tags_inout = cJSON_CreateArray();
return *tags_inout;
}
static int has_tag_key_local(cJSON* tags, const char* key) {
if (!tags || !cJSON_IsArray(tags) || !key) return 0;
int n = cJSON_GetArraySize(tags);
for (int i = 0; i < n; i++) {
cJSON* tag = cJSON_GetArrayItem(tags, i);
if (!tag || !cJSON_IsArray(tag)) continue;
cJSON* k = cJSON_GetArrayItem(tag, 0);
if (k && cJSON_IsString(k) && k->valuestring && strcmp(k->valuestring, key) == 0) {
return 1;
}
}
return 0;
}
static int add_string_tag_local(cJSON* tags, const char* key, const char* value) {
if (!tags || !cJSON_IsArray(tags) || !key || !value || value[0] == '\0') return -1;
cJSON* tag = cJSON_CreateArray();
if (!tag) return -1;
cJSON_AddItemToArray(tag, cJSON_CreateString(key));
cJSON_AddItemToArray(tag, cJSON_CreateString(value));
cJSON_AddItemToArray(tags, tag);
return 0;
}
static char* trim_copy_local(const char* start, size_t len) {
while (len > 0 && isspace((unsigned char)start[0])) {
start++;
len--;
}
while (len > 0 && isspace((unsigned char)start[len - 1])) {
len--;
}
char* out = (char*)malloc(len + 1U);
if (!out) return NULL;
memcpy(out, start, len);
out[len] = '\0';
return out;
}
static char* first_markdown_h1_local(const char* content) {
if (!content) return NULL;
const char* p = content;
while (*p) {
const char* line = p;
const char* nl = strchr(line, '\n');
size_t len = nl ? (size_t)(nl - line) : strlen(line);
while (len > 0 && line[len - 1] == '\r') len--;
size_t i = 0;
while (i < len && isspace((unsigned char)line[i])) i++;
if (i < len && line[i] == '#') {
size_t j = i;
while (j < len && line[j] == '#') j++;
if (j < len && isspace((unsigned char)line[j])) {
while (j < len && isspace((unsigned char)line[j])) j++;
if (j < len) return trim_copy_local(line + j, len - j);
}
}
if (!nl) break;
p = nl + 1;
}
return NULL;
}
static int is_paragraph_line_local(const char* line, size_t len) {
size_t i = 0;
while (i < len && isspace((unsigned char)line[i])) i++;
if (i >= len) return 0;
char c = line[i];
if (c == '#' || c == '>' || c == '-' || c == '*' || c == '`' || c == '|') return 0;
if (isdigit((unsigned char)c)) {
size_t j = i;
while (j < len && isdigit((unsigned char)line[j])) j++;
if (j < len && line[j] == '.') return 0;
}
return 1;
}
static char* first_markdown_paragraph_local(const char* content) {
if (!content) return NULL;
const char* p = content;
while (*p) {
const char* line = p;
const char* nl = strchr(line, '\n');
size_t len = nl ? (size_t)(nl - line) : strlen(line);
while (len > 0 && line[len - 1] == '\r') len--;
if (is_paragraph_line_local(line, len)) {
size_t cap = 1024;
size_t used = 0;
char* out = (char*)malloc(cap);
if (!out) return NULL;
const char* q = line;
const char* qnl = nl;
size_t qlen = len;
while (1) {
if (!is_paragraph_line_local(q, qlen)) break;
size_t start = 0;
while (start < qlen && isspace((unsigned char)q[start])) start++;
size_t end = qlen;
while (end > start && isspace((unsigned char)q[end - 1])) end--;
size_t part_len = end - start;
if (used + part_len + 2 >= cap) {
cap = (cap * 2U) + part_len + 16U;
char* bigger = (char*)realloc(out, cap);
if (!bigger) {
free(out);
return NULL;
}
out = bigger;
}
if (part_len > 0) {
if (used > 0) out[used++] = ' ';
memcpy(out + used, q + start, part_len);
used += part_len;
}
if (!qnl) break;
q = qnl + 1;
qnl = strchr(q, '\n');
qlen = qnl ? (size_t)(qnl - q) : strlen(q);
while (qlen > 0 && q[qlen - 1] == '\r') qlen--;
}
out[used] = '\0';
return out;
}
if (!nl) break;
p = nl + 1;
}
return NULL;
}
static char* first_markdown_image_url_local(const char* content) {
if (!content) return NULL;
const char* p = content;
while ((p = strstr(p, "![")) != NULL) {
const char* close_bracket = strchr(p + 2, ']');
if (!close_bracket || close_bracket[1] != '(') {
p += 2;
continue;
}
const char* url_start = close_bracket + 2;
const char* url_end = strchr(url_start, ')');
if (!url_end || url_end <= url_start) {
p += 2;
continue;
}
return trim_copy_local(url_start, (size_t)(url_end - url_start));
}
return NULL;
}
static char* d_tagify_string_local(const char* in, const char* fallback) {
if (!in || in[0] == '\0') {
return fallback ? strdup(fallback) : NULL;
}
size_t len = strlen(in);
char* out = (char*)malloc(len + 1U);
if (!out) return NULL;
size_t j = 0;
int prev_dash = 0;
for (size_t i = 0; i < len; i++) {
unsigned char c = (unsigned char)in[i];
if (isalnum(c)) {
out[j++] = (char)tolower(c);
prev_dash = 0;
} else if (!prev_dash && j > 0) {
out[j++] = '-';
prev_dash = 1;
}
}
while (j > 0 && out[j - 1] == '-') j--;
out[j] = '\0';
if (j == 0) {
free(out);
return fallback ? strdup(fallback) : NULL;
}
return out;
}
static void ensure_nip23_metadata_tags_local(int kind, const char* content, cJSON** tags_inout) {
if (!content || (kind != 30023 && kind != 30024) || !tags_inout) {
return;
}
cJSON* tags = ensure_tags_array_local(tags_inout);
if (!tags) return;
char* title = has_tag_key_local(tags, "title") ? NULL : first_markdown_h1_local(content);
char* summary = has_tag_key_local(tags, "summary") ? NULL : first_markdown_paragraph_local(content);
char* image = has_tag_key_local(tags, "image") ? NULL : first_markdown_image_url_local(content);
if (title) (void)add_string_tag_local(tags, "title", title);
if (summary) (void)add_string_tag_local(tags, "summary", summary);
if (image) (void)add_string_tag_local(tags, "image", image);
if (!has_tag_key_local(tags, "published_at")) {
char published_at[32];
snprintf(published_at, sizeof(published_at), "%lld", (long long)time(NULL));
(void)add_string_tag_local(tags, "published_at", published_at);
}
if (!has_tag_key_local(tags, "d")) {
char* d_tag = NULL;
if (title) {
d_tag = d_tagify_string_local(title, "long-form-note");
} else {
char* derived_title = first_markdown_h1_local(content);
d_tag = d_tagify_string_local(derived_title, "long-form-note");
free(derived_title);
}
if (d_tag) {
(void)add_string_tag_local(tags, "d", d_tag);
free(d_tag);
}
}
free(title);
free(summary);
free(image);
}
static int is_safe_relative_path_local(const char* path) {
if (!path || path[0] == '\0') return 0;
if (path[0] == '/') return 0;
if (strstr(path, "..") != NULL) return 0;
if (strchr(path, '\\') != NULL) return 0;
return 1;
}
static int build_tool_path_local(tools_context_t* ctx, const char* rel_path, char* out, size_t out_size) {
if (!ctx || !ctx->cfg || !rel_path || !out || out_size == 0) return -1;
if (!is_safe_relative_path_local(rel_path)) return -1;
const char* cwd = ctx->cfg->tools.shell.working_directory[0] != '\0'
? ctx->cfg->tools.shell.working_directory
: ".";
int n = 0;
if (strcmp(cwd, ".") == 0) {
n = snprintf(out, out_size, "%s", rel_path);
} else {
n = snprintf(out, out_size, "%s/%s", cwd, rel_path);
}
if (n < 0 || (size_t)n >= out_size) return -1;
return 0;
}
static char* read_entire_file_local(const char* file_path, size_t* out_bytes) {
if (!file_path) return NULL;
FILE* fp = fopen(file_path, "rb");
if (!fp) return NULL;
if (fseek(fp, 0, SEEK_END) != 0) {
fclose(fp);
return NULL;
}
long size = ftell(fp);
if (size < 0) {
fclose(fp);
return NULL;
}
if (fseek(fp, 0, SEEK_SET) != 0) {
fclose(fp);
return NULL;
}
char* buf = (char*)malloc((size_t)size + 1U);
if (!buf) {
fclose(fp);
return NULL;
}
size_t n = fread(buf, 1, (size_t)size, fp);
fclose(fp);
buf[n] = '\0';
if (out_bytes) *out_bytes = n;
return buf;
}
static char* basename_lowercase_dup_local(const char* path) {
if (!path || path[0] == '\0') return NULL;
const char* base = strrchr(path, '/');
base = base ? (base + 1) : path;
if (base[0] == '\0') return NULL;
char* out = strdup(base);
if (!out) return NULL;
for (size_t i = 0; out[i] != '\0'; i++) {
out[i] = (char)tolower((unsigned char)out[i]);
}
return out;
}
char* execute_nostr_post(const char* args_json) {
const char* raw_args_json = args_json ? args_json : "{}";
raw_args_json = skip_ws_local(raw_args_json);
if (!raw_args_json || raw_args_json[0] == '\0') {
raw_args_json = "{}";
}
cJSON* args = cJSON_Parse(raw_args_json);
char* repaired_args_json = NULL;
if (args && cJSON_IsString(args) && args->valuestring) {
cJSON* nested = cJSON_Parse(args->valuestring);
if (nested) {
cJSON_Delete(args);
args = nested;
}
}
if (!args && raw_args_json) {
repaired_args_json = sanitize_json_string_controls_local(raw_args_json);
if (repaired_args_json) {
args = cJSON_Parse(repaired_args_json);
if (args && cJSON_IsString(args) && args->valuestring) {
cJSON* nested = cJSON_Parse(args->valuestring);
if (nested) {
cJSON_Delete(args);
args = nested;
}
}
}
}
if (!args && raw_args_json) {
args = parse_loose_nostr_post_args_local(raw_args_json);
}
if (!args) {
free(repaired_args_json);
return json_error_local("invalid arguments JSON");
}
cJSON* kind = cJSON_GetObjectItemCaseSensitive(args, "kind");
cJSON* content = cJSON_GetObjectItemCaseSensitive(args, "content");
cJSON* tags = cJSON_GetObjectItemCaseSensitive(args, "tags");
if (!kind || !cJSON_IsNumber(kind) || !content || !cJSON_IsString(content) || !content->valuestring) {
cJSON_Delete(args);
free(repaired_args_json);
return json_error_local("nostr_post requires integer kind and string content");
}
if (tags && !cJSON_IsArray(tags)) {
cJSON_Delete(args);
free(repaired_args_json);
return json_error_local("nostr_post tags must be an array when provided");
}
cJSON* tags_dup = NULL;
if (tags) {
tags_dup = cJSON_Duplicate(tags, 1);
if (!tags_dup) {
cJSON_Delete(args);
free(repaired_args_json);
return json_error_local("nostr_post failed to duplicate tags");
}
}
ensure_nip23_metadata_tags_local((int)kind->valuedouble, content->valuestring, &tags_dup);
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event((int)kind->valuedouble,
content->valuestring,
tags_dup,
&publish_result);
cJSON_Delete(tags_dup);
cJSON_Delete(args);
free(repaired_args_json);
if (rc != 0) {
nostr_handler_publish_result_free(&publish_result);
return json_error_local("nostr_post failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", publish_result.success ? 1 : 0);
cJSON_AddStringToObject(out, "message", "nostr_post published");
cJSON_AddNumberToObject(out, "kind", publish_result.kind);
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
cJSON_AddNumberToObject(out, "relay_count", publish_result.relay_count);
cJSON_AddNumberToObject(out, "accepted_by_pool_count", publish_result.accepted_by_pool_count);
if (publish_result.note_uri[0] != '\0') cJSON_AddStringToObject(out, "note_uri", publish_result.note_uri);
if (publish_result.naddr_uri[0] != '\0') cJSON_AddStringToObject(out, "naddr_uri", publish_result.naddr_uri);
if (publish_result.d_tag[0] != '\0') cJSON_AddStringToObject(out, "d_tag", publish_result.d_tag);
cJSON* relays = cJSON_CreateArray();
if (!relays) {
nostr_handler_publish_result_free(&publish_result);
cJSON_Delete(out);
return NULL;
}
for (int i = 0; i < publish_result.relay_count; i++) {
cJSON_AddItemToArray(relays, cJSON_CreateString(publish_result.relays[i] ? publish_result.relays[i] : ""));
}
cJSON_AddItemToObject(out, "relays", relays);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
nostr_handler_publish_result_free(&publish_result);
return json;
}
char* execute_nostr_post_readme(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_tool_args_json_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char readme_path[PATH_MAX];
if (build_tool_path_local(ctx, "README.md", readme_path, sizeof(readme_path)) != 0) {
return json_error_local("failed to resolve README path");
}
size_t bytes_read = 0;
char* content = read_entire_file_local(readme_path, &bytes_read);
if (!content) {
return json_error_local("failed to read README.md");
}
cJSON* tags = cJSON_CreateArray();
if (!tags) {
free(content);
return json_error_local("failed to create tags");
}
if (add_string_tag_local(tags, "d", "readme.md") != 0 ||
add_string_tag_local(tags,
"image",
"https://laantungir.github.io/img_repo/d21c4060632ab3d9d37a6062eeecbdbfbd67f03cb20dbd64838b1ba0d9cd8922.jpg") != 0) {
cJSON_Delete(tags);
free(content);
return json_error_local("failed to set required tags");
}
ensure_nip23_metadata_tags_local(30023, content, &tags);
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event(30023, content, tags, &publish_result);
cJSON_Delete(tags);
free(content);
if (rc != 0) {
nostr_handler_publish_result_free(&publish_result);
return json_error_local("nostr_post_readme failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", publish_result.success ? 1 : 0);
cJSON_AddStringToObject(out, "message", "nostr_post_readme published");
cJSON_AddStringToObject(out, "path", readme_path);
cJSON_AddNumberToObject(out, "bytes_read", (double)bytes_read);
cJSON_AddNumberToObject(out, "kind", publish_result.kind);
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
cJSON_AddNumberToObject(out, "relay_count", publish_result.relay_count);
cJSON_AddNumberToObject(out, "accepted_by_pool_count", publish_result.accepted_by_pool_count);
if (publish_result.note_uri[0] != '\0') cJSON_AddStringToObject(out, "note_uri", publish_result.note_uri);
if (publish_result.naddr_uri[0] != '\0') cJSON_AddStringToObject(out, "naddr_uri", publish_result.naddr_uri);
if (publish_result.d_tag[0] != '\0') cJSON_AddStringToObject(out, "d_tag", publish_result.d_tag);
cJSON* relays = cJSON_CreateArray();
if (!relays) {
nostr_handler_publish_result_free(&publish_result);
cJSON_Delete(out);
return NULL;
}
for (int i = 0; i < publish_result.relay_count; i++) {
cJSON_AddItemToArray(relays, cJSON_CreateString(publish_result.relays[i] ? publish_result.relays[i] : ""));
}
cJSON_AddItemToObject(out, "relays", relays);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
nostr_handler_publish_result_free(&publish_result);
return json;
}
char* execute_nostr_file_md_to_longform_post(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_tool_args_json_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* file = cJSON_GetObjectItemCaseSensitive(args, "file");
cJSON* title = cJSON_GetObjectItemCaseSensitive(args, "title");
cJSON* image = cJSON_GetObjectItemCaseSensitive(args, "image");
cJSON* summary = cJSON_GetObjectItemCaseSensitive(args, "summary");
if (!file || !cJSON_IsString(file) || !file->valuestring || file->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_file_md_to_longform_post requires string file");
}
if (title && !cJSON_IsString(title)) {
cJSON_Delete(args);
return json_error_local("nostr_file_md_to_longform_post title must be string when provided");
}
if (image && !cJSON_IsString(image)) {
cJSON_Delete(args);
return json_error_local("nostr_file_md_to_longform_post image must be string when provided");
}
if (summary && !cJSON_IsString(summary)) {
cJSON_Delete(args);
return json_error_local("nostr_file_md_to_longform_post summary must be string when provided");
}
char file_path[PATH_MAX];
if (build_tool_path_local(ctx, file->valuestring, file_path, sizeof(file_path)) != 0) {
cJSON_Delete(args);
return json_error_local("failed to resolve markdown file path");
}
size_t bytes_read = 0;
char* content = read_entire_file_local(file_path, &bytes_read);
if (!content) {
cJSON_Delete(args);
return json_error_local("failed to read markdown file");
}
char* d_tag = basename_lowercase_dup_local(file->valuestring);
if (!d_tag || d_tag[0] == '\0') {
free(d_tag);
free(content);
cJSON_Delete(args);
return json_error_local("failed to derive d tag from filename");
}
cJSON* tags = cJSON_CreateArray();
if (!tags) {
free(d_tag);
free(content);
cJSON_Delete(args);
return json_error_local("failed to create tags");
}
if (add_string_tag_local(tags, "d", d_tag) != 0) {
free(d_tag);
cJSON_Delete(tags);
free(content);
cJSON_Delete(args);
return json_error_local("failed to set d tag");
}
if (title && title->valuestring && title->valuestring[0] != '\0') {
if (add_string_tag_local(tags, "title", title->valuestring) != 0) {
free(d_tag);
cJSON_Delete(tags);
free(content);
cJSON_Delete(args);
return json_error_local("failed to set title tag");
}
}
if (image && image->valuestring && image->valuestring[0] != '\0') {
if (add_string_tag_local(tags, "image", image->valuestring) != 0) {
free(d_tag);
cJSON_Delete(tags);
free(content);
cJSON_Delete(args);
return json_error_local("failed to set image tag");
}
}
if (summary && summary->valuestring && summary->valuestring[0] != '\0') {
if (add_string_tag_local(tags, "summary", summary->valuestring) != 0) {
free(d_tag);
cJSON_Delete(tags);
free(content);
cJSON_Delete(args);
return json_error_local("failed to set summary tag");
}
}
ensure_nip23_metadata_tags_local(30023, content, &tags);
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event(30023, content, tags, &publish_result);
cJSON_Delete(tags);
free(content);
cJSON_Delete(args);
if (rc != 0) {
free(d_tag);
nostr_handler_publish_result_free(&publish_result);
return json_error_local("nostr_file_md_to_longform_post failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
free(d_tag);
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", publish_result.success ? 1 : 0);
cJSON_AddStringToObject(out, "message", "nostr_file_md_to_longform_post published");
cJSON_AddStringToObject(out, "path", file_path);
cJSON_AddStringToObject(out, "d_tag", d_tag);
cJSON_AddNumberToObject(out, "bytes_read", (double)bytes_read);
cJSON_AddNumberToObject(out, "kind", publish_result.kind);
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
cJSON_AddNumberToObject(out, "relay_count", publish_result.relay_count);
cJSON_AddNumberToObject(out, "accepted_by_pool_count", publish_result.accepted_by_pool_count);
if (publish_result.note_uri[0] != '\0') cJSON_AddStringToObject(out, "note_uri", publish_result.note_uri);
if (publish_result.naddr_uri[0] != '\0') cJSON_AddStringToObject(out, "naddr_uri", publish_result.naddr_uri);
cJSON* relays = cJSON_CreateArray();
if (!relays) {
free(d_tag);
nostr_handler_publish_result_free(&publish_result);
cJSON_Delete(out);
return NULL;
}
for (int i = 0; i < publish_result.relay_count; i++) {
cJSON_AddItemToArray(relays, cJSON_CreateString(publish_result.relays[i] ? publish_result.relays[i] : ""));
}
cJSON_AddItemToObject(out, "relays", relays);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(d_tag);
nostr_handler_publish_result_free(&publish_result);
return json;
}
+62
View File
@@ -0,0 +1,62 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdlib.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
char* execute_nostr_query(const char* args_json) {
cJSON* args = cJSON_Parse(args_json ? args_json : "{}");
if (!args) return json_error_local("invalid arguments JSON");
cJSON* filter = cJSON_GetObjectItemCaseSensitive(args, "filter");
cJSON* timeout = cJSON_GetObjectItemCaseSensitive(args, "timeout_ms");
if (!filter || !cJSON_IsObject(filter)) {
cJSON_Delete(args);
return json_error_local("nostr_query requires object filter");
}
cJSON* filter_dup = cJSON_Duplicate(filter, 1);
if (!filter_dup) {
cJSON_Delete(args);
return json_error_local("failed to duplicate filter");
}
int timeout_ms = (timeout && cJSON_IsNumber(timeout)) ? (int)timeout->valuedouble : 8000;
char* events_json = nostr_handler_query_json(filter_dup, timeout_ms);
cJSON_Delete(filter_dup);
cJSON_Delete(args);
if (!events_json) return json_error_local("nostr_query failed");
cJSON* out = cJSON_CreateObject();
if (!out) {
free(events_json);
return NULL;
}
cJSON* events = cJSON_Parse(events_json);
free(events_json);
if (!events) {
cJSON_Delete(out);
return json_error_local("nostr_query returned invalid JSON");
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddItemToObject(out, "events", events);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
+196
View File
@@ -0,0 +1,196 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdlib.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
char* execute_nostr_relay_status(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* status_json = nostr_handler_relay_status_json();
if (!status_json) {
return json_error_local("nostr_relay_status failed");
}
cJSON* status = cJSON_Parse(status_json);
free(status_json);
if (!status) {
return json_error_local("nostr_relay_status returned invalid JSON");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(status);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddItemToObject(out, "status", status);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_relay_info(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* relay_url = cJSON_GetObjectItemCaseSensitive(args, "relay_url");
if (!relay_url || !cJSON_IsString(relay_url) || !relay_url->valuestring || relay_url->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_relay_info requires relay_url");
}
char* info_json = nostr_handler_relay_info_json(relay_url->valuestring);
cJSON_Delete(args);
if (!info_json) {
return json_error_local("nostr_relay_info failed");
}
cJSON* info = cJSON_Parse(info_json);
free(info_json);
if (!info || !cJSON_IsObject(info)) {
cJSON_Delete(info);
return json_error_local("nostr_relay_info returned invalid JSON");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(info);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddItemToObject(out, "info", info);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_subscription_status(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON_Delete(args);
char* status_json = nostr_handler_subscription_status_json();
if (!status_json) {
return json_error_local("nostr_subscription_status failed");
}
cJSON* status = cJSON_Parse(status_json);
free(status_json);
if (!status || !cJSON_IsObject(status)) {
cJSON_Delete(status);
return json_error_local("nostr_subscription_status returned invalid JSON");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(status);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddItemToObject(out, "status", status);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_subscription_set(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* name = cJSON_GetObjectItemCaseSensitive(args, "name");
if (!name || !cJSON_IsString(name) || !name->valuestring || name->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("nostr_subscription_set requires non-empty string name");
}
cJSON* enabled_item = cJSON_GetObjectItemCaseSensitive(args, "enabled");
int enabled_set = 0;
int enabled = 0;
if (enabled_item) {
if (!cJSON_IsBool(enabled_item)) {
cJSON_Delete(args);
return json_error_local("nostr_subscription_set enabled must be boolean");
}
enabled_set = 1;
enabled = cJSON_IsTrue(enabled_item) ? 1 : 0;
}
cJSON* filter_item = cJSON_GetObjectItemCaseSensitive(args, "filter");
cJSON* filter_dup = NULL;
if (filter_item) {
if (!cJSON_IsObject(filter_item)) {
cJSON_Delete(args);
return json_error_local("nostr_subscription_set filter must be an object");
}
filter_dup = cJSON_Duplicate(filter_item, 1);
if (!filter_dup) {
cJSON_Delete(args);
return json_error_local("nostr_subscription_set filter copy failed");
}
}
int rc = nostr_handler_subscription_set_json(name->valuestring, filter_dup, enabled, enabled_set);
cJSON_Delete(filter_dup);
char* status_json = nostr_handler_subscription_status_json();
cJSON_Delete(args);
if (rc != 0) {
free(status_json);
return json_error_local("nostr_subscription_set failed");
}
cJSON* status = status_json ? cJSON_Parse(status_json) : NULL;
free(status_json);
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(status);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "name", name->valuestring);
cJSON_AddBoolToObject(out, "updated", 1);
if (enabled_set) {
cJSON_AddBoolToObject(out, "enabled", enabled ? 1 : 0);
}
if (status) {
cJSON_AddItemToObject(out, "status", status);
}
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
+302
View File
@@ -0,0 +1,302 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static int is_hex_string_len_local(const char* s, size_t expected_len) {
if (!s) return 0;
if (strlen(s) != expected_len) return 0;
for (size_t i = 0; i < expected_len; i++) {
if (!((s[i] >= '0' && s[i] <= '9') ||
(s[i] >= 'a' && s[i] <= 'f') ||
(s[i] >= 'A' && s[i] <= 'F'))) {
return 0;
}
}
return 1;
}
static int add_string_tag_local(cJSON* tags, const char* key, const char* value) {
if (!tags || !cJSON_IsArray(tags) || !key || !value) return -1;
cJSON* tuple = cJSON_CreateArray();
if (!tuple) return -1;
cJSON_AddItemToArray(tuple, cJSON_CreateString(key));
cJSON_AddItemToArray(tuple, cJSON_CreateString(value));
cJSON_AddItemToArray(tags, tuple);
return 0;
}
static void free_string_array_heap_local(char** items, int count) {
if (!items) return;
for (int i = 0; i < count; i++) free(items[i]);
free(items);
}
char* execute_nostr_react(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* event_id = cJSON_GetObjectItemCaseSensitive(args, "event_id");
cJSON* event_pubkey = cJSON_GetObjectItemCaseSensitive(args, "event_pubkey");
cJSON* event_kind = cJSON_GetObjectItemCaseSensitive(args, "event_kind");
cJSON* reaction = cJSON_GetObjectItemCaseSensitive(args, "reaction");
if (!event_id || !cJSON_IsString(event_id) || !event_id->valuestring || !is_hex_string_len_local(event_id->valuestring, 64U) ||
!event_pubkey || !cJSON_IsString(event_pubkey) || !event_pubkey->valuestring || !is_hex_string_len_local(event_pubkey->valuestring, 64U)) {
cJSON_Delete(args);
return json_error_local("nostr_react requires event_id and event_pubkey as 64-char hex strings");
}
if (event_kind && !cJSON_IsNumber(event_kind)) {
cJSON_Delete(args);
return json_error_local("nostr_react event_kind must be an integer when provided");
}
if (reaction && !cJSON_IsString(reaction)) {
cJSON_Delete(args);
return json_error_local("nostr_react reaction must be a string when provided");
}
cJSON* tags = cJSON_CreateArray();
if (!tags) {
cJSON_Delete(args);
return json_error_local("failed to create tags");
}
if (add_string_tag_local(tags, "e", event_id->valuestring) != 0 ||
add_string_tag_local(tags, "p", event_pubkey->valuestring) != 0) {
cJSON_Delete(tags);
cJSON_Delete(args);
return json_error_local("failed to add required reaction tags");
}
if (event_kind) {
char kind_buf[32];
snprintf(kind_buf, sizeof(kind_buf), "%d", (int)event_kind->valuedouble);
if (add_string_tag_local(tags, "k", kind_buf) != 0) {
cJSON_Delete(tags);
cJSON_Delete(args);
return json_error_local("failed to add k tag");
}
}
const char* reaction_content = (reaction && reaction->valuestring && reaction->valuestring[0] != '\0') ? reaction->valuestring : "+";
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event(7, reaction_content, tags, &publish_result);
cJSON_Delete(tags);
cJSON_Delete(args);
if (rc != 0) {
nostr_handler_publish_result_free(&publish_result);
return json_error_local("nostr_react failed");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
nostr_handler_publish_result_free(&publish_result);
return NULL;
}
cJSON_AddBoolToObject(out, "success", publish_result.success ? 1 : 0);
cJSON_AddStringToObject(out, "message", "nostr_react published");
cJSON_AddStringToObject(out, "reaction", reaction_content);
cJSON_AddNumberToObject(out, "kind", publish_result.kind);
cJSON_AddStringToObject(out, "event_id", publish_result.event_id);
cJSON_AddNumberToObject(out, "relay_count", publish_result.relay_count);
cJSON_AddNumberToObject(out, "accepted_by_pool_count", publish_result.accepted_by_pool_count);
cJSON* relays = cJSON_CreateArray();
if (!relays) {
nostr_handler_publish_result_free(&publish_result);
cJSON_Delete(out);
return NULL;
}
for (int i = 0; i < publish_result.relay_count; i++) {
cJSON_AddItemToArray(relays, cJSON_CreateString(publish_result.relays[i] ? publish_result.relays[i] : ""));
}
cJSON_AddItemToObject(out, "relays", relays);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
nostr_handler_publish_result_free(&publish_result);
return json;
}
char* execute_nostr_profile_get(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* pubkey = cJSON_GetObjectItemCaseSensitive(args, "pubkey");
if (!pubkey || !cJSON_IsString(pubkey) || !pubkey->valuestring || !is_hex_string_len_local(pubkey->valuestring, 64U)) {
cJSON_Delete(args);
return json_error_local("nostr_profile_get requires pubkey as 64-char hex string");
}
cJSON* filter = cJSON_CreateObject();
cJSON* kinds = cJSON_CreateArray();
cJSON* authors = cJSON_CreateArray();
if (!filter || !kinds || !authors) {
cJSON_Delete(filter);
cJSON_Delete(kinds);
cJSON_Delete(authors);
cJSON_Delete(args);
return json_error_local("failed to create profile query filter");
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(0));
cJSON_AddItemToObject(filter, "kinds", kinds);
cJSON_AddItemToArray(authors, cJSON_CreateString(pubkey->valuestring));
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddNumberToObject(filter, "limit", 1);
char* events_json = nostr_handler_query_json(filter, 8000);
cJSON_Delete(filter);
cJSON_Delete(args);
if (!events_json) {
return json_error_local("nostr_profile_get query failed");
}
cJSON* events = cJSON_Parse(events_json);
free(events_json);
if (!events || !cJSON_IsArray(events)) {
cJSON_Delete(events);
return json_error_local("nostr_profile_get returned invalid events JSON");
}
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(events);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
int found = cJSON_GetArraySize(events) > 0;
cJSON_AddBoolToObject(out, "found", found ? 1 : 0);
if (found) {
cJSON* ev = cJSON_GetArrayItem(events, 0);
cJSON* ev_dup = ev ? cJSON_Duplicate(ev, 1) : NULL;
if (ev_dup) {
cJSON_AddItemToObject(out, "event", ev_dup);
}
cJSON* content = ev ? cJSON_GetObjectItemCaseSensitive(ev, "content") : NULL;
if (content && cJSON_IsString(content) && content->valuestring) {
cJSON* profile = cJSON_Parse(content->valuestring);
if (profile && cJSON_IsObject(profile)) {
cJSON_AddItemToObject(out, "profile", profile);
} else {
cJSON_Delete(profile);
cJSON_AddStringToObject(out, "profile_raw", content->valuestring);
}
}
}
cJSON_Delete(events);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
char* execute_nostr_nip05_lookup(const char* args_json) {
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* identifier = cJSON_GetObjectItemCaseSensitive(args, "identifier");
cJSON* pubkey = cJSON_GetObjectItemCaseSensitive(args, "pubkey");
if (!identifier || !cJSON_IsString(identifier) || !identifier->valuestring || strchr(identifier->valuestring, '@') == NULL) {
cJSON_Delete(args);
return json_error_local("nostr_nip05_lookup requires identifier in user@domain format");
}
if (pubkey && (!cJSON_IsString(pubkey) || !pubkey->valuestring || !is_hex_string_len_local(pubkey->valuestring, 64U))) {
cJSON_Delete(args);
return json_error_local("nostr_nip05_lookup pubkey must be a 64-char hex string when provided");
}
char found_pubkey[65] = {0};
char** relays = NULL;
int relay_count = 0;
int rc = 0;
if (pubkey) {
rc = nostr_nip05_verify(identifier->valuestring,
pubkey->valuestring,
&relays,
&relay_count,
10);
} else {
rc = nostr_nip05_lookup(identifier->valuestring,
found_pubkey,
&relays,
&relay_count,
10);
}
cJSON* out = cJSON_CreateObject();
if (!out) {
free_string_array_heap_local(relays, relay_count);
cJSON_Delete(args);
return NULL;
}
cJSON_AddBoolToObject(out, "success", rc == NOSTR_SUCCESS ? 1 : 0);
cJSON_AddStringToObject(out, "identifier", identifier->valuestring);
if (pubkey) {
cJSON_AddBoolToObject(out, "verified", rc == NOSTR_SUCCESS ? 1 : 0);
cJSON_AddStringToObject(out, "pubkey", pubkey->valuestring);
} else if (rc == NOSTR_SUCCESS) {
cJSON_AddStringToObject(out, "pubkey", found_pubkey);
}
cJSON* relay_arr = cJSON_CreateArray();
if (!relay_arr) {
cJSON_Delete(out);
free_string_array_heap_local(relays, relay_count);
cJSON_Delete(args);
return NULL;
}
for (int i = 0; i < relay_count; i++) {
cJSON_AddItemToArray(relay_arr, cJSON_CreateString(relays[i] ? relays[i] : ""));
}
cJSON_AddItemToObject(out, "relays", relay_arr);
if (rc != NOSTR_SUCCESS) {
cJSON_AddNumberToObject(out, "error_code", rc);
}
free_string_array_heap_local(relays, relay_count);
cJSON_Delete(args);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
File diff suppressed because it is too large Load Diff
+629
View File
@@ -0,0 +1,629 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "cjson/cJSON.h"
#include "../nostr_handler.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
#define TASKS_KIND 30078
#define TASKS_D_TAG "tasks"
#define TASKS_APP_TAG "didactyl"
static char* json_error_local(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
static cJSON* parse_args_local(const char* args_json) {
const char* raw = args_json ? args_json : "{}";
cJSON* args = cJSON_Parse(raw);
if (!args || !cJSON_IsObject(args)) {
cJSON_Delete(args);
return NULL;
}
return args;
}
static cJSON* tasks_create_empty_root_local(void) {
cJSON* root = cJSON_CreateObject();
cJSON* tasks = cJSON_CreateArray();
if (!root || !tasks) {
cJSON_Delete(root);
cJSON_Delete(tasks);
return NULL;
}
cJSON_AddItemToObject(root, "tasks", tasks);
cJSON_AddNumberToObject(root, "next_id", 1);
return root;
}
static const char* normalize_task_status_local(const char* status) {
if (!status) return NULL;
if (strcmp(status, "pending") == 0) return "pending";
if (strcmp(status, "active") == 0) return "active";
if (strcmp(status, "done") == 0) return "done";
return NULL;
}
static int nip44_encrypt_self_local(tools_context_t* ctx, const char* plaintext, char** out_ciphertext) {
if (!ctx || !ctx->cfg || !out_ciphertext) return -1;
const char* plain = plaintext ? plaintext : "";
size_t out_cap = (strlen(plain) * 4U) + 1024U;
char* ciphertext = (char*)malloc(out_cap);
if (!ciphertext) return -1;
int rc = nostr_nip44_encrypt(ctx->cfg->keys.private_key,
ctx->cfg->keys.public_key,
plain,
ciphertext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(ciphertext);
return -1;
}
*out_ciphertext = ciphertext;
return 0;
}
static int nip44_decrypt_self_local(tools_context_t* ctx, const char* ciphertext, char** out_plaintext) {
if (!ctx || !ctx->cfg || !ciphertext || !out_plaintext) return -1;
size_t out_cap = strlen(ciphertext) + 1024U;
char* plaintext = (char*)malloc(out_cap);
if (!plaintext) return -1;
int rc = nostr_nip44_decrypt(ctx->cfg->keys.private_key,
ctx->cfg->keys.public_key,
ciphertext,
plaintext,
out_cap);
if (rc != NOSTR_SUCCESS) {
free(plaintext);
return -1;
}
*out_plaintext = plaintext;
return 0;
}
static int query_tasks_ciphertext_local(tools_context_t* ctx, char** out_ciphertext) {
if (!ctx || !ctx->cfg || !out_ciphertext) return -1;
cJSON* filter = cJSON_CreateObject();
cJSON* kinds = cJSON_CreateArray();
cJSON* authors = cJSON_CreateArray();
cJSON* d_vals = cJSON_CreateArray();
if (!filter || !kinds || !authors || !d_vals) {
cJSON_Delete(filter);
cJSON_Delete(kinds);
cJSON_Delete(authors);
cJSON_Delete(d_vals);
return -1;
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(TASKS_KIND));
cJSON_AddItemToObject(filter, "kinds", kinds);
cJSON_AddItemToArray(authors, cJSON_CreateString(ctx->cfg->keys.public_key_hex));
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddItemToArray(d_vals, cJSON_CreateString(TASKS_D_TAG));
cJSON_AddItemToObject(filter, "#d", d_vals);
cJSON_AddNumberToObject(filter, "limit", 1);
char* events_json = nostr_handler_query_json(filter, 4000);
cJSON_Delete(filter);
if (!events_json) {
return -1;
}
cJSON* arr = cJSON_Parse(events_json);
free(events_json);
if (!arr || !cJSON_IsArray(arr) || cJSON_GetArraySize(arr) <= 0) {
cJSON_Delete(arr);
*out_ciphertext = strdup("");
return (*out_ciphertext != NULL) ? 0 : -1;
}
cJSON* ev = cJSON_GetArrayItem(arr, 0);
cJSON* content = ev ? cJSON_GetObjectItemCaseSensitive(ev, "content") : NULL;
const char* cipher = (content && cJSON_IsString(content) && content->valuestring) ? content->valuestring : "";
*out_ciphertext = strdup(cipher);
cJSON_Delete(arr);
return (*out_ciphertext != NULL) ? 0 : -1;
}
static cJSON* tasks_load_root_nostr_local(tools_context_t* ctx) {
char* ciphertext = NULL;
if (query_tasks_ciphertext_local(ctx, &ciphertext) != 0) {
return NULL;
}
if (!ciphertext || ciphertext[0] == '\0') {
free(ciphertext);
return tasks_create_empty_root_local();
}
char* plaintext = NULL;
if (nip44_decrypt_self_local(ctx, ciphertext, &plaintext) != 0) {
free(ciphertext);
return NULL;
}
free(ciphertext);
cJSON* root = cJSON_Parse(plaintext);
free(plaintext);
if (!root || !cJSON_IsObject(root)) {
cJSON_Delete(root);
return NULL;
}
cJSON* tasks = cJSON_GetObjectItemCaseSensitive(root, "tasks");
if (!tasks || !cJSON_IsArray(tasks)) {
cJSON_DeleteItemFromObjectCaseSensitive(root, "tasks");
cJSON_AddItemToObject(root, "tasks", cJSON_CreateArray());
}
cJSON* next_id = cJSON_GetObjectItemCaseSensitive(root, "next_id");
if (!next_id || !cJSON_IsNumber(next_id) || next_id->valuedouble < 1) {
cJSON_DeleteItemFromObjectCaseSensitive(root, "next_id");
cJSON_AddNumberToObject(root, "next_id", 1);
}
return root;
}
static int tasks_save_root_nostr_local(tools_context_t* ctx, cJSON* root) {
if (!ctx || !ctx->cfg || !root) return -1;
char* plaintext = cJSON_PrintUnformatted(root);
if (!plaintext) return -1;
char* ciphertext = NULL;
if (nip44_encrypt_self_local(ctx, plaintext, &ciphertext) != 0) {
free(plaintext);
return -1;
}
free(plaintext);
cJSON* tags = cJSON_CreateArray();
cJSON* d_tag = cJSON_CreateArray();
cJSON* app_tag = cJSON_CreateArray();
if (!tags || !d_tag || !app_tag) {
cJSON_Delete(tags);
cJSON_Delete(d_tag);
cJSON_Delete(app_tag);
free(ciphertext);
return -1;
}
cJSON_AddItemToArray(d_tag, cJSON_CreateString("d"));
cJSON_AddItemToArray(d_tag, cJSON_CreateString(TASKS_D_TAG));
cJSON_AddItemToArray(tags, d_tag);
cJSON_AddItemToArray(app_tag, cJSON_CreateString("app"));
cJSON_AddItemToArray(app_tag, cJSON_CreateString(TASKS_APP_TAG));
cJSON_AddItemToArray(tags, app_tag);
nostr_publish_result_t publish_result;
memset(&publish_result, 0, sizeof(publish_result));
int rc = nostr_handler_publish_kind_event(TASKS_KIND, ciphertext, tags, &publish_result);
cJSON_Delete(tags);
free(ciphertext);
nostr_handler_publish_result_free(&publish_result);
return rc == 0 ? 0 : -1;
}
static cJSON* task_find_by_id_local(cJSON* tasks, int id, int* out_index) {
if (!tasks || !cJSON_IsArray(tasks) || id <= 0) return NULL;
int n = cJSON_GetArraySize(tasks);
for (int i = 0; i < n; i++) {
cJSON* task = cJSON_GetArrayItem(tasks, i);
cJSON* tid = task ? cJSON_GetObjectItemCaseSensitive(task, "id") : NULL;
if (tid && cJSON_IsNumber(tid) && (int)tid->valuedouble == id) {
if (out_index) *out_index = i;
return task;
}
}
return NULL;
}
char* execute_task_manage(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
cJSON* args = parse_args_local(args_json);
if (!args) return json_error_local("invalid arguments JSON");
cJSON* action = cJSON_GetObjectItemCaseSensitive(args, "action");
if (!action || !cJSON_IsString(action) || !action->valuestring || action->valuestring[0] == '\0') {
cJSON_Delete(args);
return json_error_local("task_manage requires string action");
}
cJSON* root = tasks_load_root_nostr_local(ctx);
if (!root) {
cJSON_Delete(args);
return json_error_local("failed to load tasks memory");
}
cJSON* tasks = cJSON_GetObjectItemCaseSensitive(root, "tasks");
if (!tasks || !cJSON_IsArray(tasks)) {
cJSON_DeleteItemFromObjectCaseSensitive(root, "tasks");
tasks = cJSON_CreateArray();
cJSON_AddItemToObject(root, "tasks", tasks);
}
cJSON* next_id_item = cJSON_GetObjectItemCaseSensitive(root, "next_id");
int next_id = (next_id_item && cJSON_IsNumber(next_id_item) && next_id_item->valuedouble >= 1)
? (int)next_id_item->valuedouble
: 1;
const char* action_s = action->valuestring;
int mutated = 0;
if (strcmp(action_s, "list") == 0) {
} else if (strcmp(action_s, "add") == 0) {
cJSON* text = cJSON_GetObjectItemCaseSensitive(args, "text");
cJSON* status = cJSON_GetObjectItemCaseSensitive(args, "status");
if (!text || !cJSON_IsString(text) || !text->valuestring || text->valuestring[0] == '\0') {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage add requires non-empty string text");
}
const char* normalized_status = "pending";
if (status && !cJSON_IsNull(status)) {
if (!cJSON_IsString(status) || !status->valuestring) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage add status must be string when provided");
}
normalized_status = normalize_task_status_local(status->valuestring);
if (!normalized_status) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage add status must be pending, active, or done");
}
}
cJSON* task = cJSON_CreateObject();
if (!task) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("allocation failure");
}
time_t now = time(NULL);
cJSON_AddNumberToObject(task, "id", next_id++);
cJSON_AddStringToObject(task, "text", text->valuestring);
cJSON_AddStringToObject(task, "status", normalized_status);
cJSON_AddNumberToObject(task, "created_at", (double)now);
cJSON_AddNumberToObject(task, "updated_at", (double)now);
cJSON_AddItemToArray(tasks, task);
mutated = 1;
} else if (strcmp(action_s, "update") == 0) {
cJSON* id = cJSON_GetObjectItemCaseSensitive(args, "id");
cJSON* text = cJSON_GetObjectItemCaseSensitive(args, "text");
cJSON* status = cJSON_GetObjectItemCaseSensitive(args, "status");
if (!id || !cJSON_IsNumber(id) || id->valuedouble < 1) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage update requires integer id");
}
if ((!text || cJSON_IsNull(text)) && (!status || cJSON_IsNull(status))) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage update requires text and/or status");
}
cJSON* task = task_find_by_id_local(tasks, (int)id->valuedouble, NULL);
if (!task) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task not found");
}
if (text && !cJSON_IsNull(text)) {
if (!cJSON_IsString(text) || !text->valuestring || text->valuestring[0] == '\0') {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage update text must be non-empty string when provided");
}
cJSON_DeleteItemFromObjectCaseSensitive(task, "text");
cJSON_AddStringToObject(task, "text", text->valuestring);
mutated = 1;
}
if (status && !cJSON_IsNull(status)) {
if (!cJSON_IsString(status) || !status->valuestring) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage update status must be string when provided");
}
const char* normalized_status = normalize_task_status_local(status->valuestring);
if (!normalized_status) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage update status must be pending, active, or done");
}
cJSON_DeleteItemFromObjectCaseSensitive(task, "status");
cJSON_AddStringToObject(task, "status", normalized_status);
mutated = 1;
}
if (mutated) {
time_t now = time(NULL);
cJSON_DeleteItemFromObjectCaseSensitive(task, "updated_at");
cJSON_AddNumberToObject(task, "updated_at", (double)now);
}
} else if (strcmp(action_s, "remove") == 0) {
cJSON* id = cJSON_GetObjectItemCaseSensitive(args, "id");
if (!id || !cJSON_IsNumber(id) || id->valuedouble < 1) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage remove requires integer id");
}
int idx = -1;
cJSON* task = task_find_by_id_local(tasks, (int)id->valuedouble, &idx);
if (!task || idx < 0) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task not found");
}
cJSON_DeleteItemFromArray(tasks, idx);
mutated = 1;
} else if (strcmp(action_s, "clear") == 0) {
cJSON* status = cJSON_GetObjectItemCaseSensitive(args, "status");
if (!status || cJSON_IsNull(status)) {
while (cJSON_GetArraySize(tasks) > 0) {
cJSON_DeleteItemFromArray(tasks, 0);
}
mutated = 1;
} else {
if (!cJSON_IsString(status) || !status->valuestring) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage clear status must be string when provided");
}
const char* normalized_status = normalize_task_status_local(status->valuestring);
if (!normalized_status) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage clear status must be pending, active, or done");
}
int i = 0;
while (i < cJSON_GetArraySize(tasks)) {
cJSON* task = cJSON_GetArrayItem(tasks, i);
cJSON* task_status = task ? cJSON_GetObjectItemCaseSensitive(task, "status") : NULL;
const char* task_status_s = (task_status && cJSON_IsString(task_status) && task_status->valuestring)
? task_status->valuestring
: "pending";
if (strcmp(task_status_s, normalized_status) == 0) {
cJSON_DeleteItemFromArray(tasks, i);
mutated = 1;
} else {
i++;
}
}
}
} else if (strcmp(action_s, "replace") == 0) {
cJSON* tasks_in = cJSON_GetObjectItemCaseSensitive(args, "tasks");
if (!tasks_in || !cJSON_IsArray(tasks_in)) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage replace requires array tasks");
}
while (cJSON_GetArraySize(tasks) > 0) {
cJSON_DeleteItemFromArray(tasks, 0);
}
int n = cJSON_GetArraySize(tasks_in);
time_t now = time(NULL);
for (int i = 0; i < n; i++) {
cJSON* text = cJSON_GetArrayItem(tasks_in, i);
if (!text || !cJSON_IsString(text) || !text->valuestring || text->valuestring[0] == '\0') {
continue;
}
cJSON* task = cJSON_CreateObject();
if (!task) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("allocation failure");
}
cJSON_AddNumberToObject(task, "id", next_id++);
cJSON_AddStringToObject(task, "text", text->valuestring);
cJSON_AddStringToObject(task, "status", "pending");
cJSON_AddNumberToObject(task, "created_at", (double)now);
cJSON_AddNumberToObject(task, "updated_at", (double)now);
cJSON_AddItemToArray(tasks, task);
}
mutated = 1;
} else {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("task_manage action must be one of: list, add, update, remove, clear, replace");
}
if (mutated) {
cJSON_DeleteItemFromObjectCaseSensitive(root, "next_id");
cJSON_AddNumberToObject(root, "next_id", next_id);
if (tasks_save_root_nostr_local(ctx, root) != 0) {
cJSON_Delete(args);
cJSON_Delete(root);
return json_error_local("failed to persist tasks memory");
}
}
cJSON* out = cJSON_CreateObject();
if (!out) {
cJSON_Delete(args);
cJSON_Delete(root);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "action", action_s);
cJSON_AddBoolToObject(out, "mutated", mutated ? 1 : 0);
cJSON_AddNumberToObject(out, "count", cJSON_GetArraySize(tasks));
cJSON* tasks_dup = cJSON_Duplicate(tasks, 1);
if (!tasks_dup) {
cJSON_Delete(args);
cJSON_Delete(root);
cJSON_Delete(out);
return NULL;
}
cJSON_AddItemToObject(out, "tasks", tasks_dup);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
cJSON_Delete(args);
cJSON_Delete(root);
return json;
}
char* execute_task_list(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
char* listed = execute_task_manage(ctx, "{\"action\":\"list\"}");
if (!listed) return json_error_local("task_list failed to list tasks");
cJSON* listed_root = cJSON_Parse(listed);
if (!listed_root || !cJSON_IsObject(listed_root)) {
cJSON_Delete(listed_root);
free(listed);
return json_error_local("task_list received invalid task_manage response");
}
cJSON* tasks = cJSON_GetObjectItemCaseSensitive(listed_root, "tasks");
int tcount = (tasks && cJSON_IsArray(tasks)) ? cJSON_GetArraySize(tasks) : 0;
size_t cap = 512U;
char* content = (char*)malloc(cap);
if (!content) {
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
size_t used = 0U;
int n = snprintf(content + used,
cap - used,
"## Current Task List\n\n### Current Tasks\n\nYour active task list - short-term working memory for tracking plan steps.\n\n");
if (n < 0) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
used += (size_t)n;
int written = 0;
for (int i = 0; i < tcount; i++) {
cJSON* task = cJSON_GetArrayItem(tasks, i);
cJSON* id = task ? cJSON_GetObjectItemCaseSensitive(task, "id") : NULL;
cJSON* text = task ? cJSON_GetObjectItemCaseSensitive(task, "text") : NULL;
cJSON* status = task ? cJSON_GetObjectItemCaseSensitive(task, "status") : NULL;
if (!text || !cJSON_IsString(text) || !text->valuestring || text->valuestring[0] == '\0') {
continue;
}
const char* status_s = (status && cJSON_IsString(status) && status->valuestring) ? status->valuestring : "pending";
const char* mark = " ";
if (strcmp(status_s, "done") == 0) mark = "x";
else if (strcmp(status_s, "active") == 0) mark = "-";
int id_value = (id && cJSON_IsNumber(id)) ? (int)id->valuedouble : (i + 1);
int needed = snprintf(NULL, 0, "- [%s] %d. %s\n", mark, id_value, text->valuestring);
if (needed < 0) continue;
if (used + (size_t)needed + 1U > cap) {
size_t next = cap;
while (used + (size_t)needed + 1U > next) next *= 2U;
char* grown = (char*)realloc(content, next);
if (!grown) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
content = grown;
cap = next;
}
snprintf(content + used, cap - used, "- [%s] %d. %s\n", mark, id_value, text->valuestring);
used += (size_t)needed;
written++;
}
if (written == 0) {
const char* fallback = "- [ ] No active tasks yet.\n";
size_t need = strlen(fallback);
if (used + need + 1U > cap) {
size_t next = cap;
while (used + need + 1U > next) next *= 2U;
char* grown = (char*)realloc(content, next);
if (!grown) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
content = grown;
cap = next;
}
memcpy(content + used, fallback, need + 1U);
used += need;
}
cJSON* args = parse_args_local(args_json);
if (!args) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return json_error_local("invalid arguments JSON");
}
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", content);
cJSON* tasks_dup = tasks ? cJSON_Duplicate(tasks, 1) : cJSON_CreateArray();
if (!tasks_dup) tasks_dup = cJSON_CreateArray();
cJSON_AddItemToObject(out, "tasks", tasks_dup);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(content);
cJSON_Delete(listed_root);
free(listed);
return json;
}
+2 -1
View File
@@ -1,7 +1,7 @@
#ifndef DIDACTYL_TOOLS_H
#define DIDACTYL_TOOLS_H
#include "config.h"
#include "../config.h"
struct trigger_manager;
@@ -10,6 +10,7 @@ typedef struct {
struct trigger_manager* trigger_manager;
int template_sender_tier;
const char* template_current_user_message;
const char* template_trigger_event_json;
} tools_context_t;
int tools_init(tools_context_t* ctx, didactyl_config_t* cfg);
+3
View File
@@ -0,0 +1,3 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
+283
View File
@@ -0,0 +1,283 @@
#define _POSIX_C_SOURCE 200809L
#include "tools_internal.h"
#include <stdlib.h>
#include <string.h>
#include "cjson/cJSON.h"
static char* json_error(const char* msg) {
cJSON* root = cJSON_CreateObject();
if (!root) return NULL;
cJSON_AddBoolToObject(root, "success", 0);
cJSON_AddStringToObject(root, "error", msg ? msg : "unknown error");
char* out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
int tools_init_legacy(tools_context_t* ctx, didactyl_config_t* cfg) {
if (!ctx || !cfg) return -1;
memset(ctx, 0, sizeof(*ctx));
ctx->cfg = cfg;
ctx->trigger_manager = NULL;
ctx->template_sender_tier = 0;
ctx->template_current_user_message = NULL;
ctx->template_trigger_event_json = NULL;
return 0;
}
void tools_cleanup_legacy(tools_context_t* ctx) {
if (!ctx) return;
memset(ctx, 0, sizeof(*ctx));
}
char* tools_execute_legacy(tools_context_t* ctx, const char* tool_name, const char* args_json) {
if (!tool_name) return json_error("missing tool name");
if (strcmp(tool_name, "nostr_post") == 0) {
return execute_nostr_post(args_json);
}
if (strcmp(tool_name, "nostr_delete") == 0) {
return execute_nostr_delete(args_json);
}
if (strcmp(tool_name, "nostr_react") == 0) {
return execute_nostr_react(args_json);
}
if (strcmp(tool_name, "nostr_profile_get") == 0) {
return execute_nostr_profile_get(args_json);
}
if (strcmp(tool_name, "nostr_relay_status") == 0) {
return execute_nostr_relay_status(args_json);
}
if (strcmp(tool_name, "nostr_nip05_lookup") == 0) {
return execute_nostr_nip05_lookup(args_json);
}
if (strcmp(tool_name, "nostr_encode") == 0) {
return execute_nostr_encode(args_json);
}
if (strcmp(tool_name, "nostr_decode") == 0) {
return execute_nostr_decode(args_json);
}
if (strcmp(tool_name, "nostr_dm_send") == 0) {
return execute_nostr_dm_send(args_json);
}
if (strcmp(tool_name, "nostr_relay_info") == 0) {
return execute_nostr_relay_info(args_json);
}
if (strcmp(tool_name, "nostr_subscription_status") == 0) {
return execute_nostr_subscription_status(args_json);
}
if (strcmp(tool_name, "nostr_subscription_set") == 0) {
return execute_nostr_subscription_set(args_json);
}
if (strcmp(tool_name, "nostr_encrypt") == 0) {
return execute_nostr_encrypt(ctx, args_json);
}
if (strcmp(tool_name, "nostr_decrypt") == 0) {
return execute_nostr_decrypt(ctx, args_json);
}
if (strcmp(tool_name, "nostr_dm_send_nip17") == 0) {
return execute_nostr_dm_send_nip17(args_json);
}
if (strcmp(tool_name, "nostr_list_manage") == 0) {
return execute_nostr_list_manage(ctx, args_json);
}
if (strcmp(tool_name, "nostr_query") == 0) {
return execute_nostr_query(args_json);
}
if (strcmp(tool_name, "nostr_my_events") == 0) {
return execute_nostr_my_events(ctx, args_json);
}
if (strcmp(tool_name, "agent_version") == 0) {
return execute_agent_version(args_json);
}
if (strcmp(tool_name, "nostr_pubkey") == 0) {
return execute_nostr_pubkey(ctx, args_json);
}
if (strcmp(tool_name, "nostr_npub") == 0) {
return execute_nostr_npub(ctx, args_json);
}
if (strcmp(tool_name, "my_pubkey") == 0) {
return execute_nostr_pubkey(ctx, args_json);
}
if (strcmp(tool_name, "my_npub") == 0) {
return execute_nostr_npub(ctx, args_json);
}
if (strcmp(tool_name, "local_http_fetch") == 0) {
return execute_local_http_fetch(ctx, args_json);
}
if (strcmp(tool_name, "local_shell_exec") == 0) {
return execute_local_shell_exec(ctx, args_json);
}
if (strcmp(tool_name, "local_file_read") == 0) {
return execute_local_file_read(ctx, args_json);
}
if (strcmp(tool_name, "local_file_write") == 0) {
return execute_local_file_write(ctx, args_json);
}
if (strcmp(tool_name, "skill_create") == 0) {
return execute_skill_create(ctx, args_json);
}
if (strcmp(tool_name, "skill_list") == 0) {
return execute_skill_list(ctx, args_json);
}
if (strcmp(tool_name, "skill_adopt") == 0) {
return execute_skill_adopt(ctx, args_json);
}
if (strcmp(tool_name, "skill_remove") == 0) {
return execute_skill_remove(ctx, args_json);
}
if (strcmp(tool_name, "skill_search") == 0) {
return execute_skill_search(args_json);
}
if (strcmp(tool_name, "skill_edit") == 0) {
return execute_skill_edit(ctx, args_json);
}
if (strcmp(tool_name, "trigger_list") == 0) {
return execute_trigger_list(ctx, args_json);
}
if (strcmp(tool_name, "tool_list") == 0) {
return execute_tool_list(ctx, args_json);
}
if (strcmp(tool_name, "model_get") == 0) {
return execute_model_get(args_json);
}
if (strcmp(tool_name, "model_set") == 0) {
return execute_model_set(ctx, args_json);
}
if (strcmp(tool_name, "model_list") == 0) {
return execute_model_list(args_json);
}
if (strcmp(tool_name, "nostr_post_readme") == 0) {
return execute_nostr_post_readme(ctx, args_json);
}
if (strcmp(tool_name, "nostr_file_md_to_longform_post") == 0) {
return execute_nostr_file_md_to_longform_post(ctx, args_json);
}
if (strcmp(tool_name, "task_manage") == 0) {
return execute_task_manage(ctx, args_json);
}
if (strcmp(tool_name, "admin_identity") == 0) {
return execute_admin_identity(ctx, args_json);
}
if (strcmp(tool_name, "nostr_admin_profile") == 0) {
return execute_nostr_admin_profile(ctx, args_json);
}
if (strcmp(tool_name, "nostr_admin_contacts") == 0) {
return execute_nostr_admin_contacts(ctx, args_json);
}
if (strcmp(tool_name, "nostr_admin_relays") == 0) {
return execute_nostr_admin_relays(ctx, args_json);
}
if (strcmp(tool_name, "nostr_admin_notes") == 0) {
return execute_nostr_admin_notes(ctx, args_json);
}
if (strcmp(tool_name, "task_list") == 0) {
return execute_task_list(ctx, args_json);
}
if (strcmp(tool_name, "message_current") == 0) {
return execute_message_current(ctx, args_json);
}
if (strcmp(tool_name, "agent_identity") == 0) {
return execute_agent_identity(ctx, args_json);
}
if (strcmp(tool_name, "nostr_agent_profile") == 0) {
return execute_nostr_agent_profile(ctx, args_json);
}
if (strcmp(tool_name, "nostr_agent_contacts") == 0) {
return execute_nostr_agent_contacts(ctx, args_json);
}
if (strcmp(tool_name, "nostr_agent_relays") == 0) {
return execute_nostr_agent_relays(ctx, args_json);
}
if (strcmp(tool_name, "nostr_agent_notes") == 0) {
return execute_nostr_agent_notes(ctx, args_json);
}
if (strcmp(tool_name, "my_kind0_profile") == 0) {
return execute_nostr_agent_profile(ctx, args_json);
}
if (strcmp(tool_name, "my_contacts") == 0) {
return execute_nostr_agent_contacts(ctx, args_json);
}
if (strcmp(tool_name, "my_relays") == 0) {
return execute_nostr_agent_relays(ctx, args_json);
}
if (strcmp(tool_name, "my_notes") == 0) {
return execute_nostr_agent_notes(ctx, args_json);
}
if (strcmp(tool_name, "memory_save") == 0) {
return execute_memory_save(ctx, args_json);
}
if (strcmp(tool_name, "memory_recall") == 0) {
return execute_memory_recall(ctx, args_json);
}
if (strcmp(tool_name, "my_memory") == 0) {
return execute_my_memory(ctx, args_json);
}
if (strcmp(tool_name, "memory_short_term_read") == 0) {
return execute_memory_short_term_read(ctx, args_json);
}
if (strcmp(tool_name, "config_store") == 0) {
return execute_config_store(ctx, args_json);
}
if (strcmp(tool_name, "config_recall") == 0) {
return execute_config_recall(ctx, args_json);
}
if (strcmp(tool_name, "adopted_skills") == 0) {
return execute_adopted_skills(ctx, args_json);
}
if (strcmp(tool_name, "trigger_event") == 0) {
return execute_trigger_event(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_balance") == 0) {
return execute_cashu_wallet_balance(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_info") == 0) {
return execute_cashu_wallet_info(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_mint_quote") == 0) {
return execute_cashu_wallet_mint_quote(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_mint_check") == 0) {
return execute_cashu_wallet_mint_check(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_mint_claim") == 0) {
return execute_cashu_wallet_mint_claim(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_melt_quote") == 0) {
return execute_cashu_wallet_melt_quote(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_melt_pay") == 0) {
return execute_cashu_wallet_melt_pay(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_check_proofs") == 0) {
return execute_cashu_wallet_check_proofs(ctx, args_json);
}
if (strcmp(tool_name, "cashu_wallet_receive_token") == 0) {
return execute_cashu_wallet_receive_token(ctx, args_json);
}
return json_error("unknown tool");
}
int tools_init(tools_context_t* ctx, didactyl_config_t* cfg) {
int rc = tools_init_legacy(ctx, cfg);
if (rc != 0) return rc;
if (memory_init(ctx) != 0) {
/* Keep agent startup resilient: memory may be empty or temporarily unavailable. */
return 0;
}
return 0;
}
void tools_cleanup(tools_context_t* ctx) {
memory_cleanup();
tools_cleanup_legacy(ctx);
}
char* tools_execute(tools_context_t* ctx, const char* tool_name, const char* args_json) {
return tools_execute_legacy(ctx, tool_name, args_json);
}
+85
View File
@@ -0,0 +1,85 @@
#ifndef DIDACTYL_TOOLS_INTERNAL_H
#define DIDACTYL_TOOLS_INTERNAL_H
#include "tools.h"
int tools_init_legacy(tools_context_t* ctx, didactyl_config_t* cfg);
void tools_cleanup_legacy(tools_context_t* ctx);
char* tools_build_openai_schema_json_legacy(const tools_context_t* ctx);
char* tools_execute_legacy(tools_context_t* ctx, const char* tool_name, const char* args_json);
char* execute_tool_list(tools_context_t* ctx, const char* args_json);
char* execute_trigger_list(tools_context_t* ctx, const char* args_json);
char* execute_message_current(tools_context_t* ctx, const char* args_json);
char* execute_agent_identity(tools_context_t* ctx, const char* args_json);
char* execute_agent_version(const char* args_json);
char* execute_nostr_agent_profile(tools_context_t* ctx, const char* args_json);
char* execute_nostr_agent_contacts(tools_context_t* ctx, const char* args_json);
char* execute_nostr_agent_relays(tools_context_t* ctx, const char* args_json);
char* execute_nostr_agent_notes(tools_context_t* ctx, const char* args_json);
char* execute_model_get(const char* args_json);
char* execute_model_set(tools_context_t* ctx, const char* args_json);
char* execute_model_list(const char* args_json);
char* execute_nostr_query(const char* args_json);
char* execute_nostr_my_events(tools_context_t* ctx, const char* args_json);
char* execute_nostr_pubkey(tools_context_t* ctx, const char* args_json);
char* execute_nostr_npub(tools_context_t* ctx, const char* args_json);
char* execute_nostr_encode(const char* args_json);
char* execute_nostr_decode(const char* args_json);
char* execute_nostr_react(const char* args_json);
char* execute_nostr_profile_get(const char* args_json);
char* execute_nostr_nip05_lookup(const char* args_json);
char* execute_nostr_relay_status(const char* args_json);
char* execute_nostr_relay_info(const char* args_json);
char* execute_nostr_subscription_status(const char* args_json);
char* execute_nostr_subscription_set(const char* args_json);
char* execute_nostr_dm_send(const char* args_json);
char* execute_nostr_encrypt(tools_context_t* ctx, const char* args_json);
char* execute_nostr_decrypt(tools_context_t* ctx, const char* args_json);
char* execute_nostr_dm_send_nip17(const char* args_json);
char* execute_nostr_delete(const char* args_json);
char* execute_nostr_list_manage(tools_context_t* ctx, const char* args_json);
char* execute_admin_identity(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_profile(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_contacts(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_relays(tools_context_t* ctx, const char* args_json);
char* execute_nostr_admin_notes(tools_context_t* ctx, const char* args_json);
char* execute_task_list(tools_context_t* ctx, const char* args_json);
char* execute_task_manage(tools_context_t* ctx, const char* args_json);
char* execute_local_http_fetch(tools_context_t* ctx, const char* args_json);
char* execute_local_shell_exec(tools_context_t* ctx, const char* args_json);
char* execute_local_file_read(tools_context_t* ctx, const char* args_json);
char* execute_local_file_write(tools_context_t* ctx, const char* args_json);
char* execute_nostr_post(const char* args_json);
char* execute_nostr_post_readme(tools_context_t* ctx, const char* args_json);
char* execute_nostr_file_md_to_longform_post(tools_context_t* ctx, const char* args_json);
char* execute_skill_create(tools_context_t* ctx, const char* args_json);
char* execute_skill_list(tools_context_t* ctx, const char* args_json);
char* execute_skill_adopt(tools_context_t* ctx, const char* args_json);
char* execute_skill_remove(tools_context_t* ctx, const char* args_json);
char* execute_skill_edit(tools_context_t* ctx, const char* args_json);
char* execute_skill_search(const char* args_json);
char* execute_memory_save(tools_context_t* ctx, const char* args_json);
char* execute_memory_recall(tools_context_t* ctx, const char* args_json);
char* execute_my_memory(tools_context_t* ctx, const char* args_json);
char* execute_memory_short_term_read(tools_context_t* ctx, const char* args_json);
char* execute_config_store(tools_context_t* ctx, const char* args_json);
char* execute_config_recall(tools_context_t* ctx, const char* args_json);
char* execute_adopted_skills(tools_context_t* ctx, const char* args_json);
char* execute_trigger_event(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_balance(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_info(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_mint_quote(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_mint_check(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_mint_claim(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_melt_quote(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_melt_pay(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_check_proofs(tools_context_t* ctx, const char* args_json);
char* execute_cashu_wallet_receive_token(tools_context_t* ctx, const char* args_json);
int memory_init(tools_context_t* ctx);
void memory_cleanup(void);
#endif
File diff suppressed because it is too large Load Diff
+572 -92
View File
@@ -8,10 +8,15 @@
#include <time.h>
#include <ctype.h>
#include "agent.h"
#include "cjson/cJSON.h"
#include "debug.h"
#include "nostr_handler.h"
#include "llm.h"
void agent_on_trigger(const char* skill_d_tag,
const char* skill_content,
cJSON* triggering_event,
const char* relay_url);
typedef struct {
trigger_manager_t* mgr;
@@ -35,6 +40,9 @@ trigger_type_t trigger_type_from_string(const char* s) {
if (strcmp(s, "chain") == 0) {
return TRIGGER_TYPE_CHAIN;
}
if (strcmp(s, "dm") == 0) {
return TRIGGER_TYPE_DM;
}
return TRIGGER_TYPE_NOSTR_SUBSCRIPTION;
}
@@ -46,6 +54,8 @@ const char* trigger_type_to_string(trigger_type_t t) {
return "cron";
case TRIGGER_TYPE_CHAIN:
return "chain";
case TRIGGER_TYPE_DM:
return "dm";
case TRIGGER_TYPE_NOSTR_SUBSCRIPTION:
default:
return "nostr-subscription";
@@ -194,18 +204,202 @@ static int cron_field_matches(const char* field, int value, int min_v, int max_v
return 0;
}
static int cron_normalize_expression(const char* expr, char* out, size_t out_sz, int* out_expanded) {
if (out_expanded) {
*out_expanded = 0;
}
if (!expr || !out || out_sz == 0) {
return -1;
}
while (*expr && isspace((unsigned char)*expr)) {
expr++;
}
if (*expr == '\0') {
return -1;
}
const char* mapped = NULL;
if (strcmp(expr, "*") == 0) {
mapped = "* * * * *";
} else if (strcmp(expr, "@yearly") == 0 || strcmp(expr, "@annually") == 0) {
mapped = "0 0 1 1 *";
} else if (strcmp(expr, "@monthly") == 0) {
mapped = "0 0 1 * *";
} else if (strcmp(expr, "@weekly") == 0) {
mapped = "0 0 * * 0";
} else if (strcmp(expr, "@daily") == 0 || strcmp(expr, "@midnight") == 0) {
mapped = "0 0 * * *";
} else if (strcmp(expr, "@hourly") == 0) {
mapped = "0 * * * *";
}
const char* src = mapped ? mapped : expr;
int n = snprintf(out, out_sz, "%s", src);
if (n < 0 || (size_t)n >= out_sz) {
return -1;
}
if (mapped && out_expanded) {
*out_expanded = 1;
}
return 0;
}
static int cron_field_token_valid(const char* token, int min_v, int max_v) {
if (!token || token[0] == '\0') {
return 0;
}
if (strcmp(token, "*") == 0) {
return 1;
}
const char* slash = strchr(token, '/');
int step = 0;
char base[64];
if (slash) {
size_t base_len = (size_t)(slash - token);
if (base_len == 0 || base_len >= sizeof(base)) {
return 0;
}
memcpy(base, token, base_len);
base[base_len] = '\0';
char* endptr = NULL;
long step_l = strtol(slash + 1, &endptr, 10);
if (endptr == slash + 1 || *endptr != '\0' || step_l <= 0 || step_l > 1024) {
return 0;
}
step = (int)step_l;
} else {
int n = snprintf(base, sizeof(base), "%s", token);
if (n < 0 || (size_t)n >= sizeof(base)) {
return 0;
}
}
if (strcmp(base, "*") == 0) {
return step == 0 || step <= (max_v - min_v + 1);
}
const char* dash = strchr(base, '-');
if (dash) {
char left[32];
char right[32];
size_t left_len = (size_t)(dash - base);
size_t right_len = strlen(dash + 1);
if (left_len == 0 || right_len == 0 || left_len >= sizeof(left) || right_len >= sizeof(right)) {
return 0;
}
memcpy(left, base, left_len);
left[left_len] = '\0';
memcpy(right, dash + 1, right_len + 1U);
char* e1 = NULL;
char* e2 = NULL;
long a = strtol(left, &e1, 10);
long b = strtol(right, &e2, 10);
if (!e1 || *e1 != '\0' || !e2 || *e2 != '\0') {
return 0;
}
if ((int)a < min_v || (int)b > max_v || (int)a > (int)b) {
return 0;
}
return 1;
}
char* e = NULL;
long n = strtol(base, &e, 10);
if (!e || *e != '\0') {
return 0;
}
if ((int)n < min_v || (int)n > max_v) {
return 0;
}
return 1;
}
static int cron_field_valid(const char* field, int min_v, int max_v) {
if (!field || field[0] == '\0') {
return 0;
}
char tmp[128];
int n = snprintf(tmp, sizeof(tmp), "%s", field);
if (n < 0 || (size_t)n >= sizeof(tmp)) {
return 0;
}
int tokens = 0;
char* saveptr = NULL;
char* token = strtok_r(tmp, ",", &saveptr);
while (token) {
while (*token == ' ') token++;
if (!cron_field_token_valid(token, min_v, max_v)) {
return 0;
}
tokens++;
token = strtok_r(NULL, ",", &saveptr);
}
return tokens > 0;
}
static int cron_expr_is_valid(const char* expr, char* normalized_out, size_t normalized_out_size) {
if (!normalized_out || normalized_out_size == 0) {
return 0;
}
if (cron_normalize_expression(expr, normalized_out, normalized_out_size, NULL) != 0) {
return 0;
}
char parse_buf[TRIGGER_FILTER_JSON_MAX];
int n = snprintf(parse_buf, sizeof(parse_buf), "%s", normalized_out);
if (n < 0 || (size_t)n >= sizeof(parse_buf)) {
return 0;
}
char* fields[5] = {0};
int nf = 0;
char* saveptr = NULL;
char* tok = strtok_r(parse_buf, " \t", &saveptr);
while (tok && nf < 5) {
fields[nf++] = tok;
tok = strtok_r(NULL, " \t", &saveptr);
}
if (nf != 5 || tok != NULL) {
return 0;
}
if (!cron_field_valid(fields[0], 0, 59)) return 0;
if (!cron_field_valid(fields[1], 0, 23)) return 0;
if (!cron_field_valid(fields[2], 1, 31)) return 0;
if (!cron_field_valid(fields[3], 1, 12)) return 0;
if (!cron_field_valid(fields[4], 0, 6)) return 0;
return 1;
}
static int cron_matches_now(const char* expr, time_t now_ts) {
if (!expr || expr[0] == '\0') {
return 0;
}
char buf[TRIGGER_FILTER_JSON_MAX];
snprintf(buf, sizeof(buf), "%s", expr);
char normalized[TRIGGER_FILTER_JSON_MAX];
if (!cron_expr_is_valid(expr, normalized, sizeof(normalized))) {
return 0;
}
char parse_buf[TRIGGER_FILTER_JSON_MAX];
snprintf(parse_buf, sizeof(parse_buf), "%s", normalized);
char* fields[5] = {0};
int nf = 0;
char* saveptr = NULL;
char* tok = strtok_r(buf, " \t", &saveptr);
char* tok = strtok_r(parse_buf, " \t", &saveptr);
while (tok && nf < 5) {
fields[nf++] = tok;
tok = strtok_r(NULL, " \t", &saveptr);
@@ -327,76 +521,127 @@ static int parse_address_tag(const char* addr, int* out_kind, char out_pubkey[65
return 0;
}
static char* build_template_output(const active_trigger_t* t, cJSON* event, const char* relay_url) {
(void)relay_url;
if (!t || !event) return NULL;
cJSON* content = cJSON_GetObjectItemCaseSensitive(event, "content");
cJSON* pubkey = cJSON_GetObjectItemCaseSensitive(event, "pubkey");
cJSON* id = cJSON_GetObjectItemCaseSensitive(event, "id");
cJSON* kind = cJSON_GetObjectItemCaseSensitive(event, "kind");
const char* content_s = (content && cJSON_IsString(content) && content->valuestring) ? content->valuestring : "";
const char* pubkey_s = (pubkey && cJSON_IsString(pubkey) && pubkey->valuestring) ? pubkey->valuestring : "unknown";
const char* id_s = (id && cJSON_IsString(id) && id->valuestring) ? id->valuestring : "";
int kind_i = (kind && cJSON_IsNumber(kind)) ? (int)kind->valuedouble : -1;
const char* tmpl = t->skill_content;
if (!tmpl || tmpl[0] == '\0') {
return NULL;
}
char out[TRIGGER_SKILL_CONTENT_MAX + 256];
snprintf(out,
sizeof(out),
"%s\n\n[event id=%s kind=%d pubkey=%s]\n%s",
tmpl,
id_s,
kind_i,
pubkey_s,
content_s);
return strdup(out);
static const char* trim_ws_local(const char* s) {
while (s && *s && isspace((unsigned char)*s)) s++;
return s ? s : "";
}
static void execute_template_action(trigger_manager_t* mgr,
const active_trigger_t* t,
cJSON* event,
const char* relay_url) {
if (!mgr || !mgr->cfg || !t || !event) {
static void parse_trigger_runtime_tags(cJSON* tags,
const char** out_llm,
const char** out_tools,
int* out_has_max_tokens,
int* out_max_tokens,
int* out_has_temperature,
double* out_temperature,
int* out_has_seed,
int* out_seed) {
if (out_llm) *out_llm = NULL;
if (out_tools) *out_tools = NULL;
if (out_has_max_tokens) *out_has_max_tokens = 0;
if (out_max_tokens) *out_max_tokens = 0;
if (out_has_temperature) *out_has_temperature = 0;
if (out_temperature) *out_temperature = 0.0;
if (out_has_seed) *out_has_seed = 0;
if (out_seed) *out_seed = 0;
if (!tags || !cJSON_IsArray(tags)) {
return;
}
char* rendered = build_template_output(t, event, relay_url);
if (!rendered) {
return;
cJSON* llm = find_tag_value_string(tags, "llm");
cJSON* tools = find_tag_value_string(tags, "tools");
cJSON* max_tokens = find_tag_value_string(tags, "max_tokens");
cJSON* temperature = find_tag_value_string(tags, "temperature");
cJSON* seed = find_tag_value_string(tags, "seed");
if (out_llm && llm && cJSON_IsString(llm) && llm->valuestring && llm->valuestring[0] != '\0') {
*out_llm = llm->valuestring;
}
if (out_tools && tools && cJSON_IsString(tools) && tools->valuestring && tools->valuestring[0] != '\0') {
*out_tools = tools->valuestring;
}
if (strncmp(rendered, "DM admin:", 9) == 0) {
const char* body = rendered + 9;
while (*body == ' ') body++;
(void)nostr_handler_send_dm_auto(mgr->cfg->admin.pubkey, body);
} else if (strncmp(rendered, "POST:", 5) == 0) {
const char* body = rendered + 5;
while (*body == ' ') body++;
(void)nostr_handler_publish_kind_event(1, body, NULL, NULL);
} else if (strncmp(rendered, "LOG:", 4) == 0) {
const char* body = rendered + 4;
while (*body == ' ') body++;
DEBUG_INFO("[didactyl] trigger template log (%s): %s", t->skill_d_tag, body);
} else {
(void)nostr_handler_send_dm_auto(mgr->cfg->admin.pubkey, rendered);
if (out_has_max_tokens && out_max_tokens && max_tokens && cJSON_IsString(max_tokens) && max_tokens->valuestring) {
char* endptr = NULL;
long n = strtol(trim_ws_local(max_tokens->valuestring), &endptr, 10);
if (endptr && *trim_ws_local(endptr) == '\0' && n > 0 && n <= 1000000) {
*out_has_max_tokens = 1;
*out_max_tokens = (int)n;
}
}
free(rendered);
if (out_has_temperature && out_temperature && temperature && cJSON_IsString(temperature) && temperature->valuestring) {
char* endptr = NULL;
double n = strtod(trim_ws_local(temperature->valuestring), &endptr);
if (endptr && *trim_ws_local(endptr) == '\0' && n >= 0.0 && n <= 2.0) {
*out_has_temperature = 1;
*out_temperature = n;
}
}
if (out_has_seed && out_seed && seed && cJSON_IsString(seed) && seed->valuestring) {
char* endptr = NULL;
long n = strtol(trim_ws_local(seed->valuestring), &endptr, 10);
if (endptr && *trim_ws_local(endptr) == '\0') {
*out_has_seed = 1;
*out_seed = (int)n;
}
}
}
static void apply_trigger_runtime_to_llm_config(const active_trigger_t* t, llm_config_t* cfg) {
if (!t || !cfg) return;
if (t->llm_spec[0] != '\0') {
const char* spec = t->llm_spec;
const char* comma = strchr(spec, ',');
size_t len = comma ? (size_t)(comma - spec) : strlen(spec);
while (len > 0 && isspace((unsigned char)spec[len - 1])) len--;
while (*spec && isspace((unsigned char)*spec)) spec++;
const char* slash = memchr(spec, '/', len);
if (slash) {
const char* model = slash + 1;
size_t model_len = len - (size_t)(model - spec);
if (model_len > 0 && model_len < sizeof(cfg->model)) {
snprintf(cfg->model, sizeof(cfg->model), "%.*s", (int)model_len, model);
}
} else if (len > 0 && len < sizeof(cfg->model)) {
snprintf(cfg->model, sizeof(cfg->model), "%.*s", (int)len, spec);
}
}
if (t->has_max_tokens && t->max_tokens > 0) {
cfg->max_tokens = t->max_tokens;
}
if (t->has_temperature) {
cfg->temperature = t->temperature;
}
}
static void execute_llm_action(const active_trigger_t* t, cJSON* event, const char* relay_url) {
if (!t || !event) {
return;
}
llm_config_t old_cfg;
int had_old_cfg = (llm_get_config(&old_cfg) == 0);
int overridden = 0;
if (had_old_cfg &&
(t->llm_spec[0] != '\0' || t->has_max_tokens || t->has_temperature)) {
llm_config_t next = old_cfg;
apply_trigger_runtime_to_llm_config(t, &next);
if (llm_set_config(&next) == 0) {
overridden = 1;
}
}
agent_on_trigger(t->skill_d_tag, t->skill_content, event, relay_url);
if (overridden) {
(void)llm_set_config(&old_cfg);
}
}
static int maybe_fire_trigger_locked(trigger_manager_t* mgr, int index, cJSON* event, const char* relay_url) {
@@ -426,11 +671,8 @@ static int maybe_fire_trigger_locked(trigger_manager_t* mgr, int index, cJSON* e
active_trigger_t trigger_copy = *t;
pthread_mutex_unlock(&mgr->mutex);
if (trigger_copy.action_type == TRIGGER_ACTION_TEMPLATE) {
execute_template_action(mgr, &trigger_copy, event, relay_url);
} else {
execute_llm_action(&trigger_copy, event, relay_url);
}
(void)mgr;
execute_llm_action(&trigger_copy, event, relay_url);
pthread_mutex_lock(&mgr->mutex);
return 1;
@@ -554,7 +796,7 @@ int trigger_manager_init(trigger_manager_t* mgr, didactyl_config_t* cfg) {
return -1;
}
mgr->last_poll_at = time(NULL);
mgr->last_poll_at = 0;
DEBUG_INFO("[didactyl] trigger manager initialized (capacity=%d)", mgr->capacity);
return 0;
@@ -690,11 +932,46 @@ int trigger_manager_load_from_skills(trigger_manager_t* mgr) {
(strcmp(trigger_s, "nostr-subscription") == 0 ||
strcmp(trigger_s, "webhook") == 0 ||
strcmp(trigger_s, "cron") == 0 ||
strcmp(trigger_s, "chain") == 0);
strcmp(trigger_s, "chain") == 0 ||
strcmp(trigger_s, "dm") == 0);
if (trigger_supported && filter_s && filter_s[0] != '\0') {
trigger_action_type_t at = (strcmp(action_s, "template") == 0) ? TRIGGER_ACTION_TEMPLATE : TRIGGER_ACTION_LLM;
if (strcmp(action_s, "template") == 0) {
DEBUG_WARN("[didactyl] trigger action template is deprecated; forcing llm for d_tag=%s", d_tag);
}
const char* llm_s = NULL;
const char* tools_s = NULL;
int has_max_tokens = 0;
int max_tokens = 0;
int has_temperature = 0;
double temperature = 0.0;
int has_seed = 0;
int seed = 0;
parse_trigger_runtime_tags(tags,
&llm_s,
&tools_s,
&has_max_tokens,
&max_tokens,
&has_temperature,
&temperature,
&has_seed,
&seed);
int is_enabled = (strcmp(enabled_s, "false") == 0 || strcmp(enabled_s, "0") == 0) ? 0 : 1;
if (trigger_manager_add(mgr, d_tag, content->valuestring, filter_s, at, trigger_s, is_enabled) == 0) {
if (trigger_manager_add(mgr,
d_tag,
content->valuestring,
filter_s,
TRIGGER_ACTION_LLM,
trigger_s,
is_enabled,
llm_s,
tools_s,
has_max_tokens,
max_tokens,
has_temperature,
temperature,
has_seed,
seed) == 0) {
loaded++;
}
}
@@ -760,18 +1037,53 @@ int trigger_manager_load_from_startup_events(trigger_manager_t* mgr) {
(strcmp(trigger_s, "nostr-subscription") == 0 ||
strcmp(trigger_s, "webhook") == 0 ||
strcmp(trigger_s, "cron") == 0 ||
strcmp(trigger_s, "chain") == 0);
strcmp(trigger_s, "chain") == 0 ||
strcmp(trigger_s, "dm") == 0);
if (!trigger_supported || !filter_s || filter_s[0] == '\0') {
cJSON_Delete(tags);
continue;
}
trigger_action_type_t at = (strcmp(action_s, "template") == 0) ? TRIGGER_ACTION_TEMPLATE : TRIGGER_ACTION_LLM;
if (strcmp(action_s, "template") == 0) {
DEBUG_WARN("[didactyl] startup trigger action template is deprecated; forcing llm for d_tag=%s", d_tag);
}
int is_enabled = (strcmp(enabled_s, "false") == 0 || strcmp(enabled_s, "0") == 0) ? 0 : 1;
if (trigger_manager_add(mgr, d_tag, ev->content, filter_s, at, trigger_s, is_enabled) == 0) {
const char* llm_s = NULL;
const char* tools_s = NULL;
int has_max_tokens = 0;
int max_tokens = 0;
int has_temperature = 0;
double temperature = 0.0;
int has_seed = 0;
int seed = 0;
parse_trigger_runtime_tags(tags,
&llm_s,
&tools_s,
&has_max_tokens,
&max_tokens,
&has_temperature,
&temperature,
&has_seed,
&seed);
if (trigger_manager_add(mgr,
d_tag,
ev->content,
filter_s,
TRIGGER_ACTION_LLM,
trigger_s,
is_enabled,
llm_s,
tools_s,
has_max_tokens,
max_tokens,
has_temperature,
temperature,
has_seed,
seed) == 0) {
loaded++;
DEBUG_INFO("[didactyl] startup trigger registered d_tag=%s action=%s enabled=%d", d_tag, at == TRIGGER_ACTION_TEMPLATE ? "template" : "llm", is_enabled);
DEBUG_INFO("[didactyl] startup trigger registered d_tag=%s action=%s enabled=%d", d_tag, "llm", is_enabled);
} else {
DEBUG_WARN("[didactyl] startup trigger failed d_tag=%s", d_tag);
}
@@ -789,12 +1101,24 @@ int trigger_manager_add(trigger_manager_t* mgr,
const char* filter_json,
trigger_action_type_t action_type,
const char* trigger_type_str,
int enabled) {
int enabled,
const char* llm_spec,
const char* tools_policy,
int has_max_tokens,
int max_tokens,
int has_temperature,
double temperature,
int has_seed,
int seed) {
if (!mgr || !skill_d_tag || skill_d_tag[0] == '\0' || !content || !filter_json) {
return -1;
}
if (action_type != TRIGGER_ACTION_LLM && action_type != TRIGGER_ACTION_TEMPLATE) {
if (action_type == TRIGGER_ACTION_TEMPLATE) {
DEBUG_WARN("[didactyl] trigger action template is deprecated; forcing llm for d_tag=%s", skill_d_tag);
action_type = TRIGGER_ACTION_LLM;
}
if (action_type != TRIGGER_ACTION_LLM) {
return -1;
}
@@ -803,7 +1127,21 @@ int trigger_manager_add(trigger_manager_t* mgr,
int existing = find_trigger_index_locked(mgr, skill_d_tag);
if (existing >= 0) {
pthread_mutex_unlock(&mgr->mutex);
return trigger_manager_update(mgr, skill_d_tag, content, filter_json, action_type, trigger_type_str, enabled);
return trigger_manager_update(mgr,
skill_d_tag,
content,
filter_json,
action_type,
trigger_type_str,
enabled,
llm_spec,
tools_policy,
has_max_tokens,
max_tokens,
has_temperature,
temperature,
has_seed,
seed);
}
int max_active = mgr->cfg ? mgr->cfg->triggers.max_active : TRIGGER_DEFAULT_MAX_ACTIVE;
@@ -831,8 +1169,23 @@ int trigger_manager_add(trigger_manager_t* mgr,
t->last_seen_created_at = 0;
t->last_cron_fire = 0;
if (t->trigger_type == TRIGGER_TYPE_CRON) {
snprintf(t->cron_expr, sizeof(t->cron_expr), "%s", filter_json);
char normalized_cron[sizeof(t->cron_expr)] = {0};
if (!cron_expr_is_valid(filter_json, normalized_cron, sizeof(normalized_cron))) {
pthread_mutex_unlock(&mgr->mutex);
DEBUG_WARN("[didactyl] trigger add rejected: invalid cron expression d_tag=%s expr=%s", skill_d_tag, filter_json);
memset(t, 0, sizeof(*t));
return -1;
}
snprintf(t->cron_expr, sizeof(t->cron_expr), "%s", normalized_cron);
}
snprintf(t->llm_spec, sizeof(t->llm_spec), "%s", llm_spec ? llm_spec : "");
snprintf(t->tools_policy, sizeof(t->tools_policy), "%s", tools_policy ? tools_policy : "");
t->has_max_tokens = has_max_tokens ? 1 : 0;
t->max_tokens = max_tokens;
t->has_temperature = has_temperature ? 1 : 0;
t->temperature = temperature;
t->has_seed = has_seed ? 1 : 0;
t->seed = seed;
t->subscription = NULL;
t->subscription_ctx = NULL;
@@ -976,11 +1329,8 @@ int trigger_manager_fire_chains(trigger_manager_t* mgr,
}
}
if (trigger_copy.action_type == TRIGGER_ACTION_TEMPLATE) {
execute_template_action(mgr, &trigger_copy, event, "chain");
} else {
execute_llm_action(&trigger_copy, event, "chain");
}
(void)mgr;
execute_llm_action(&trigger_copy, event, "chain");
cJSON_Delete(event);
fired_count++;
}
@@ -999,12 +1349,24 @@ int trigger_manager_update(trigger_manager_t* mgr,
const char* filter_json,
trigger_action_type_t action_type,
const char* trigger_type_str,
int enabled) {
int enabled,
const char* llm_spec,
const char* tools_policy,
int has_max_tokens,
int max_tokens,
int has_temperature,
double temperature,
int has_seed,
int seed) {
if (!mgr || !skill_d_tag || skill_d_tag[0] == '\0' || !content || !filter_json) {
return -1;
}
if (action_type != TRIGGER_ACTION_LLM && action_type != TRIGGER_ACTION_TEMPLATE) {
if (action_type == TRIGGER_ACTION_TEMPLATE) {
DEBUG_WARN("[didactyl] trigger action template is deprecated; forcing llm for d_tag=%s", skill_d_tag);
action_type = TRIGGER_ACTION_LLM;
}
if (action_type != TRIGGER_ACTION_LLM) {
return -1;
}
@@ -1013,7 +1375,21 @@ int trigger_manager_update(trigger_manager_t* mgr,
int idx = find_trigger_index_locked(mgr, skill_d_tag);
if (idx < 0) {
pthread_mutex_unlock(&mgr->mutex);
return trigger_manager_add(mgr, skill_d_tag, content, filter_json, action_type, trigger_type_str, enabled);
return trigger_manager_add(mgr,
skill_d_tag,
content,
filter_json,
action_type,
trigger_type_str,
enabled,
llm_spec,
tools_policy,
has_max_tokens,
max_tokens,
has_temperature,
temperature,
has_seed,
seed);
}
active_trigger_t* t = &mgr->triggers[idx];
@@ -1023,10 +1399,24 @@ int trigger_manager_update(trigger_manager_t* mgr,
t->enabled = clamp_enabled(enabled);
t->trigger_type = trigger_type_from_string(trigger_type_str);
if (t->trigger_type == TRIGGER_TYPE_CRON) {
snprintf(t->cron_expr, sizeof(t->cron_expr), "%s", filter_json);
char normalized_cron[sizeof(t->cron_expr)] = {0};
if (!cron_expr_is_valid(filter_json, normalized_cron, sizeof(normalized_cron))) {
pthread_mutex_unlock(&mgr->mutex);
DEBUG_WARN("[didactyl] trigger update rejected: invalid cron expression d_tag=%s expr=%s", skill_d_tag, filter_json);
return -1;
}
snprintf(t->cron_expr, sizeof(t->cron_expr), "%s", normalized_cron);
} else {
t->cron_expr[0] = '\0';
}
snprintf(t->llm_spec, sizeof(t->llm_spec), "%s", llm_spec ? llm_spec : "");
snprintf(t->tools_policy, sizeof(t->tools_policy), "%s", tools_policy ? tools_policy : "");
t->has_max_tokens = has_max_tokens ? 1 : 0;
t->max_tokens = max_tokens;
t->has_temperature = has_temperature ? 1 : 0;
t->temperature = temperature;
t->has_seed = has_seed ? 1 : 0;
t->seed = seed;
if (register_trigger_subscription_locked(mgr, t) != 0) {
pthread_mutex_unlock(&mgr->mutex);
@@ -1068,6 +1458,7 @@ int trigger_manager_poll(trigger_manager_t* mgr) {
}
if (mgr->last_poll_at > 0 && (now - mgr->last_poll_at) < 30) {
DEBUG_LOG("[didactyl] trigger cron poll throttled (delta=%ld)", (long)(now - mgr->last_poll_at));
return 0;
}
mgr->last_poll_at = now;
@@ -1083,9 +1474,16 @@ int trigger_manager_poll(trigger_manager_t* mgr) {
}
const char* expr = (t->cron_expr[0] != '\0') ? t->cron_expr : t->filter_json;
if (!cron_matches_now(expr, now)) {
char normalized_expr[64] = {0};
if (!cron_expr_is_valid(expr, normalized_expr, sizeof(normalized_expr))) {
DEBUG_WARN("[didactyl] cron trigger skipped: invalid expression d_tag=%s expr=%s", t->skill_d_tag, expr ? expr : "");
continue;
}
if (!cron_matches_now(normalized_expr, now)) {
continue;
}
DEBUG_INFO("[didactyl] cron trigger matched d_tag=%s expr=%s", t->skill_d_tag, normalized_expr);
if (t->last_cron_fire > 0 && (now - t->last_cron_fire) < 50) {
continue;
@@ -1103,13 +1501,10 @@ int trigger_manager_poll(trigger_manager_t* mgr) {
if (event) {
cJSON_AddStringToObject(event, "type", "cron");
cJSON_AddStringToObject(event, "d_tag", trigger_copy.skill_d_tag);
cJSON_AddStringToObject(event, "cron_expr", expr);
cJSON_AddStringToObject(event, "cron_expr", normalized_expr);
cJSON_AddNumberToObject(event, "created_at", (double)now);
if (trigger_copy.action_type == TRIGGER_ACTION_TEMPLATE) {
execute_template_action(mgr, &trigger_copy, event, "cron");
} else {
execute_llm_action(&trigger_copy, event, "cron");
}
(void)mgr;
execute_llm_action(&trigger_copy, event, "cron");
cJSON_Delete(event);
fired++;
}
@@ -1121,6 +1516,79 @@ int trigger_manager_poll(trigger_manager_t* mgr) {
return fired;
}
static int dm_filter_matches_tier(const char* filter_json, didactyl_sender_tier_t tier) {
if (!filter_json || filter_json[0] == '\0') {
return 0;
}
cJSON* root = cJSON_Parse(filter_json);
if (!root || !cJSON_IsObject(root)) {
cJSON_Delete(root);
return 0;
}
cJSON* from = cJSON_GetObjectItemCaseSensitive(root, "from");
const char* from_s = (from && cJSON_IsString(from) && from->valuestring) ? from->valuestring : "admin";
int match = 0;
if (strcmp(from_s, "any") == 0) {
match = 1;
} else if (strcmp(from_s, "admin") == 0) {
match = (tier == DIDACTYL_SENDER_ADMIN);
} else if (strcmp(from_s, "wot") == 0) {
match = (tier == DIDACTYL_SENDER_WOT);
}
cJSON_Delete(root);
return match;
}
int trigger_manager_fire_dm(trigger_manager_t* mgr,
const char* sender_pubkey_hex,
const char* message,
didactyl_sender_tier_t tier,
const char* source_label) {
if (!mgr || !sender_pubkey_hex || !message) {
return -1;
}
cJSON* event = cJSON_CreateObject();
if (!event) {
return -1;
}
cJSON_AddStringToObject(event, "type", "dm");
cJSON_AddStringToObject(event, "sender_pubkey", sender_pubkey_hex);
cJSON_AddStringToObject(event, "message", message);
cJSON_AddStringToObject(event, "tier",
tier == DIDACTYL_SENDER_ADMIN ? "admin" :
(tier == DIDACTYL_SENDER_WOT ? "wot" : "stranger"));
cJSON_AddNumberToObject(event, "created_at", (double)time(NULL));
int fired_total = 0;
pthread_mutex_lock(&mgr->mutex);
int count_snapshot = mgr->count;
for (int i = 0; i < count_snapshot; i++) {
active_trigger_t* t = &mgr->triggers[i];
if (!t->enabled || t->trigger_type != TRIGGER_TYPE_DM) {
continue;
}
if (!dm_filter_matches_tier(t->filter_json, tier)) {
continue;
}
int fired = maybe_fire_trigger_locked(mgr, i, event, source_label ? source_label : "dm");
if (fired > 0) {
fired_total += fired;
}
}
pthread_mutex_unlock(&mgr->mutex);
cJSON_Delete(event);
return fired_total;
}
char* trigger_manager_status_json(trigger_manager_t* mgr) {
if (!mgr) {
cJSON* err = cJSON_CreateObject();
@@ -1162,11 +1630,23 @@ char* trigger_manager_status_json(trigger_manager_t* mgr) {
cJSON_AddStringToObject(item, "skill_d_tag", t->skill_d_tag);
cJSON_AddStringToObject(item, "filter_json", t->filter_json);
cJSON_AddStringToObject(item, "type", trigger_type_to_string(t->trigger_type));
cJSON_AddStringToObject(item, "action", t->action_type == TRIGGER_ACTION_TEMPLATE ? "template" : "llm");
cJSON_AddStringToObject(item, "action", "llm");
cJSON_AddBoolToObject(item, "enabled", t->enabled ? 1 : 0);
cJSON_AddBoolToObject(item, "subscribed", t->subscription ? 1 : 0);
cJSON_AddStringToObject(item, "llm", t->llm_spec);
cJSON_AddStringToObject(item, "tools", t->tools_policy);
cJSON_AddBoolToObject(item, "has_max_tokens", t->has_max_tokens ? 1 : 0);
if (t->has_max_tokens) cJSON_AddNumberToObject(item, "max_tokens", t->max_tokens);
cJSON_AddBoolToObject(item, "has_temperature", t->has_temperature ? 1 : 0);
if (t->has_temperature) cJSON_AddNumberToObject(item, "temperature", t->temperature);
cJSON_AddBoolToObject(item, "has_seed", t->has_seed ? 1 : 0);
if (t->has_seed) cJSON_AddNumberToObject(item, "seed", t->seed);
cJSON_AddNumberToObject(item, "last_fired", (double)t->last_fired);
cJSON_AddNumberToObject(item, "last_seen_created_at", (double)t->last_seen_created_at);
if (t->trigger_type == TRIGGER_TYPE_CRON) {
cJSON_AddStringToObject(item, "cron_expr", t->cron_expr);
cJSON_AddNumberToObject(item, "last_cron_fire", (double)t->last_cron_fire);
}
cJSON_AddItemToArray(arr, item);
}
+34 -3
View File
@@ -6,6 +6,7 @@
#include "config.h"
#include "cjson/cJSON.h"
#include "nostr_handler.h"
#include "../nostr_core_lib/nostr_core/nostr_core.h"
#define TRIGGER_DEFAULT_MAX_ACTIVE 16
@@ -22,7 +23,8 @@ typedef enum {
TRIGGER_TYPE_NOSTR_SUBSCRIPTION = 0,
TRIGGER_TYPE_WEBHOOK = 1,
TRIGGER_TYPE_CRON = 2,
TRIGGER_TYPE_CHAIN = 3
TRIGGER_TYPE_CHAIN = 3,
TRIGGER_TYPE_DM = 4
} trigger_type_t;
typedef struct {
@@ -36,6 +38,14 @@ typedef struct {
time_t last_seen_created_at;
time_t last_cron_fire;
char cron_expr[64];
char llm_spec[256];
char tools_policy[256];
int has_max_tokens;
int max_tokens;
int has_temperature;
double temperature;
int has_seed;
int seed;
nostr_pool_subscription_t* subscription;
void* subscription_ctx;
} active_trigger_t;
@@ -61,7 +71,15 @@ int trigger_manager_add(trigger_manager_t* mgr,
const char* filter_json,
trigger_action_type_t action_type,
const char* trigger_type_str,
int enabled);
int enabled,
const char* llm_spec,
const char* tools_policy,
int has_max_tokens,
int max_tokens,
int has_temperature,
double temperature,
int has_seed,
int seed);
int trigger_manager_remove(trigger_manager_t* mgr, const char* skill_d_tag);
int trigger_manager_find(trigger_manager_t* mgr, const char* skill_d_tag, active_trigger_t* out);
int trigger_manager_update(trigger_manager_t* mgr,
@@ -70,7 +88,15 @@ int trigger_manager_update(trigger_manager_t* mgr,
const char* filter_json,
trigger_action_type_t action_type,
const char* trigger_type_str,
int enabled);
int enabled,
const char* llm_spec,
const char* tools_policy,
int has_max_tokens,
int max_tokens,
int has_temperature,
double temperature,
int has_seed,
int seed);
int trigger_manager_fire(trigger_manager_t* mgr,
const char* skill_d_tag,
cJSON* event,
@@ -79,6 +105,11 @@ int trigger_manager_fire_chains(trigger_manager_t* mgr,
const char* source_skill_d_tag,
cJSON* source_event,
const char* source_label);
int trigger_manager_fire_dm(trigger_manager_t* mgr,
const char* sender_pubkey_hex,
const char* message,
didactyl_sender_tier_t tier,
const char* source_label);
int trigger_manager_active_count(trigger_manager_t* mgr);
int trigger_manager_poll(trigger_manager_t* mgr);
char* trigger_manager_status_json(trigger_manager_t* mgr);
+1 -1
View File
@@ -1 +1 @@
{"tasks":[],"next_id":9}
{"tasks":[{"id":9,"text":"Publish README.md as longform post","created_at":1773326251,"status":"done","updated_at":1773326287},{"id":10,"text":"Publish docs/CONTEXT.md as longform post","created_at":1773326251,"status":"done","updated_at":1773326310},{"id":11,"text":"Publish docs/TOOLS.md as longform post","created_at":1773326251,"status":"done","updated_at":1773326320},{"id":12,"text":"Publish docs/SUBSCRIPTIONS.md as longform post","created_at":1773326251,"status":"done","updated_at":1773327937},{"id":13,"text":"DM admin after each publish","created_at":1773326251,"status":"done","updated_at":1773327937},{"id":14,"text":"Return final summary","created_at":1773326251,"status":"done","updated_at":1773327937}],"next_id":15}
+4 -2
View File
@@ -63,8 +63,8 @@ assert_grep "trigger_type_to_string" src/trigger_manager.c "Trigger type seriali
assert_grep "\"/api/trigger/\*\"" src/http_api.c "Webhook API route registered"
assert_grep "handle_trigger_webhook\(" src/http_api.c "Webhook handler implemented"
assert_grep "nostr-subscription, webhook, cron, chain" src/tools.c "skill_create validation accepts 4 trigger types"
assert_grep "skill_edit trigger must be one of: nostr-subscription, webhook, cron, chain" src/tools.c "skill_edit validation accepts 4 trigger types"
assert_grep "skill_create trigger must be one of: nostr-subscription, webhook, cron, chain, dm" src/tools/tool_skill.c "skill_create validation accepts supported trigger types"
assert_grep "skill_edit trigger must be one of: nostr-subscription, webhook, cron, chain, dm" src/tools/tool_skill.c "skill_edit validation accepts supported trigger types"
assert_grep "trigger_manager_fire_chains\(" src/agent.c "Post-execution chain hook wired in agent"
@@ -84,6 +84,8 @@ if command -v curl >/dev/null 2>&1; then
if [[ "$HTTP_CODE" == "200" || "$HTTP_CODE" == "400" || "$HTTP_CODE" == "404" || "$HTTP_CODE" == "503" ]]; then
pass "Webhook endpoint responds on local API (http code: $HTTP_CODE)"
elif [[ "$HTTP_CODE" == "000" || -z "$HTTP_CODE" ]]; then
pass "Webhook endpoint probe skipped (no local API listener detected)"
else
fail "Webhook endpoint probe did not get expected response (http code: ${HTTP_CODE:-none})"
fi
+53
View File
@@ -0,0 +1,53 @@
#!/bin/bash
set -euo pipefail
LOG_FILE="${1:-}"
if [ -z "$LOG_FILE" ]; then
for candidate in "./didactyl.log" "./debug.log" "./context.log.md"; do
if [ -f "$candidate" ]; then
LOG_FILE="$candidate"
break
fi
done
fi
if [ -z "$LOG_FILE" ] || [ ! -f "$LOG_FILE" ]; then
echo "Log file not found." >&2
echo "Tried defaults: ./didactyl.log ./debug.log ./context.log.md" >&2
echo "Usage: $0 [path/to/logfile]" >&2
exit 1
fi
echo "Following numbered LLM API calls from: $LOG_FILE"
echo "(Press Ctrl+C to stop)"
# Count only outbound provider calls from src/llm.c:
# [didactyl] llm request: method=... url=...
START_API=$(tail -n 20000 "$LOG_FILE" | grep -Ec "\\[didactyl\\] llm request:" || true)
[ -z "$START_API" ] && START_API=0
echo "Starting api_call count from: $START_API"
tail -n 0 -F "$LOG_FILE" \
| awk -v api_start="$START_API" '
BEGIN { api = api_start }
{
line = $0
if (line !~ /\[didactyl\] llm request:/) next
api++
method = "?"
url = "?"
if (match(line, /method=[A-Z]+/)) {
method = substr(line, RSTART + 7, RLENGTH - 7)
}
if (match(line, /url=[^ ]+/)) {
url = substr(line, RSTART + 4, RLENGTH - 4)
}
printf "%d) %s %s\n", api, method, url
fflush()
}
'