Compare commits

...

19 Commits

Author SHA1 Message Date
Didactyl User
b3534e6eee v0.2.53 - Add signer_health.c to Dockerfile.alpine-musl source list (was missing, causing static build failure) 2026-07-10 19:18:43 -04:00
Didactyl User
3ed3733b76 v0.2.52 - Fix trigger manager bypassing skill adoption list — cron/webhook triggers now only fire for adopted and enabled skills 2026-07-10 19:13:19 -04:00
Didactyl User
4430c36bcb v0.2.51 - Implement n_signer integration through Phase 4: signer config/CLI/wizard, signer-backed signing/encryption/auth/cashu/blossom paths, nsigner_unix e2e validation, and signer health observability 2026-07-08 14:36:04 -04:00
Didactyl User
f5a5c93ce3 v0.2.50 - Fix startup step-14 false-negative by adding sync self-skill retry validation and post-auth query REQ resend 2026-06-13 07:35:10 -04:00
Didactyl User
c1bf0b2956 v0.2.49 - Add startup-failure DM de-dup with marker, relay-state/needed-event diagnostics, and clear-on-READY rearm 2026-06-13 06:56:04 -04:00
Didactyl User
d13044d267 chore(agent): remove dead DM-history helper functions and orphaned constants 2026-04-28 07:34:17 -04:00
Didactyl User
8bb90a31a5 v0.2.48 - Remove admin kind 10123 from subscription and upsert, add debug logging 2026-04-22 10:58:07 -04:00
Didactyl User
b6ca2bf3bf v0.2.47 - nostr: exclude admin from kind 10123 self-skill adoption and add self-skill upsert debug logs 2026-04-21 06:35:53 -04:00
Didactyl User
73c368e4e5 v0.2.46 - Finalize skill_list formatting cleanup and adopted-author cache refresh improvements 2026-04-16 18:15:55 -04:00
Didactyl User
2a091aabf7 v0.2.45 - Expand skill refresh to include adopted authors and clean up skill_list output 2026-04-16 18:06:20 -04:00
Didactyl User
c877ca646e v0.2.44 - Fix adoption list selection to self-authored latest event in agent and skill tool 2026-04-16 17:25:47 -04:00
Didactyl User
b5b479e9a8 v0.2.43 - Fix /help adopted-skills section to use latest kind 10123 event by created_at in CLI and HTTP views 2026-04-16 16:59:50 -04:00
Didactyl User
52f1cd3b30 v0.2.42 - Make skill_refresh re-query relays and reload self-skill cache before invalidating adopted-skills cache 2026-04-16 16:38:11 -04:00
Didactyl User
09d45febdd v0.2.41 - Fix adopted-skills cache to select latest kind 10123 event by created_at in agent refresh path 2026-04-15 14:12:44 -04:00
Didactyl User
b9e90f0b21 v0.2.40 - Fix adoption list freshness by selecting newest kind 10123 event and temporarily disable periodic relay-backed trigger reconciliation for validation 2026-04-14 17:47:57 -04:00
Didactyl User
59bd2603e2 v0.2.39 - Add 15-minute relay-backed trigger reconciliation in trigger_manager_poll to recover missed self-skill events and re-register missing triggers 2026-04-14 16:36:53 -04:00
Didactyl User
5e6610823f v0.2.38 - Resolve NIP-17 gift wrap send failure investigation and docs 2026-04-11 15:53:52 -04:00
Didactyl User
112fe8e5ef v0.2.37 - Add nostr-core relay reconnect cooldown with stability-based reset to prevent flapping loops 2026-04-10 06:13:21 -04:00
Didactyl User
ed852f16df v0.2.36 - Block model_get/model_set/model_list inside skill_run with explicit policy gate 2026-04-09 11:30:19 -04:00
136 changed files with 8373 additions and 332 deletions

View File

@@ -123,7 +123,7 @@ RUN NOSTR_LIB=$(ls /build/nostr_core_lib/libnostr_core_*.a 2>/dev/null | head -1
src/tools/tool_task.c src/tools/tool_nostr_list.c src/tools/tool_nostr_block.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/tools/tool_blossom.c src/trigger_manager.c \
src/cashu_wallet.c src/nostr_block_list.c src/prompt_template.c src/http_api.c src/setup_wizard.c src/mongoose.c src/debug.c \
src/json_to_markdown.c src/context_roles.c src/context_format.c \
src/json_to_markdown.c src/context_roles.c src/context_format.c src/signer_health.c \
-o /build/didactyl_static \
$NOSTR_LIB \
-lsecp256k1 \

View File

@@ -1,5 +1,5 @@
CC = gcc
CFLAGS = -std=c99 -Wall -Wextra -Wpedantic -O2 -D_GNU_SOURCE -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L -DMG_TLS=MG_TLS_BUILTIN
CFLAGS = -std=c99 -Wall -Wextra -Wpedantic -O2 -D_GNU_SOURCE -D_DEFAULT_SOURCE -D_POSIX_C_SOURCE=200809L -DMG_TLS=MG_TLS_BUILTIN -DNOSTR_ENABLE_NSIGNER_CLIENT=1
SRC_DIR = src
TARGET = didactyl
@@ -44,7 +44,8 @@ SRCS = \
$(SRC_DIR)/nostr_block_list.c \
$(SRC_DIR)/json_to_markdown.c \
$(SRC_DIR)/context_roles.c \
$(SRC_DIR)/context_format.c
$(SRC_DIR)/context_format.c \
$(SRC_DIR)/signer_health.c
INCLUDES = \
-I$(SRC_DIR) \

View File

@@ -54,11 +54,11 @@ Skills compose by adoption-list order (`10123`) and trigger tags carry runtime e
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.2.35
## Current Status — v0.2.53
**Active build — this project is barely working. Experiment at your own risk.**
> Last release update: v0.2.35 — Remove top-level dm_protocol from genesis configs and set user-settings kind 30078 dm_protocol to both
> Last release update: v0.2.53Add signer_health.c to Dockerfile.alpine-musl source list (was missing, causing static build failure)
- Connects to configured relays with auto-reconnect and relay state transition logging
- Publishes configured startup events per relay as each relay becomes connected

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
{"id":"gen-1777375164-jltZoEFnh01JRUoyFbYw","object":"chat.completion","created":1777375164,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Hello! I'm a test agent built with Didactyl. I don't have a specific personal name configured, but I'm here to help you with various tasks using the tools available to me.\n\nI can help you with things like:\n- **Nostr interactions** - posting, querying events, managing profiles, sending DMs, etc.\n- **File operations** - reading and writing local files\n- **Shell commands** - executing commands in the system\n- **Skills management** - creating, editing, and running skills\n- **HTTP requests** - fetching web resources\n- **Wallet operations** - managing Cashu ecash wallets\n- **File hosting** - uploading/downloading files via Blossom\n- And more!\n\nIs there anything specific you'd like me to help you with?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9369,"completion_tokens":178,"total_tokens":9547,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":9366,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0126005,"upstream_inference_prompt_cost":0.0117105,"upstream_inference_completions_cost":0.00089},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,31 @@
{"id":"gen-1777375169-LOcgKM5Oya3Y7QIaAKTG","object":"chat.completion","created":1777375169,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I'm **Didactyl**, a Nostr-based AI agent. Here's a brief overview of what I am:\n\n**Core Identity:**\n- An autonomous agent running on the Nostr protocol\n- Equipped with a comprehensive toolkit for interacting with Nostr, managing tasks, handling encrypted communications, and more\n- Designed to be extensible through skills and configurable through various settings\n\n**Key Capabilities:**\n- **Nostr Integration**: Post notes, send encrypted DMs (NIP-04 and NIP-17), manage block lists, handle relays, and query events\n- **Skill System**: Create, adopt, and execute skills that extend my functionality with custom behaviors and triggers\n- **Task Management**: Maintain short-term task memory on Nostr for tracking and managing work\n- **Encrypted Memory**: Store and recall encrypted agent memory and configuration\n- **LLM Configuration**: Flexible model selection and parameter tuning\n- **Ecash/Cashu**: Wallet support for privacy-preserving payments\n- **File Management**: Read/write local files and upload/download via Blossom servers\n- **HTTP Requests**: Fetch external resources\n- **Shell Execution**: Run local commands when needed\n\n**Design Philosophy:**\nI'm built to be a helpful, privacy-conscious assistant that respects decentralized principles. I can operate autonomously or collaboratively, respond to various triggers (DMs, cron jobs, webhooks, subscriptions), and maintain context across conversations through encrypted storage.\n\nIs there something specific you'd like me to help you with?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9373,"completion_tokens":348,"total_tokens":9721,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":338,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0030687,"upstream_inference_prompt_cost":0.0013287,"upstream_inference_completions_cost":0.00174},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
{"id":"gen-1777375237-UNuX3x5bOLRo3Yf2fhGV","object":"chat.completion","created":1777375237,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I'm ready to help! I'm a test agent running on the Didactyl platform. I have access to a comprehensive set of tools for:\n\n- **Nostr operations**: posting, querying, reactions, DMs, profiles, relays, encryption\n- **File management**: reading and writing local files\n- **Skills**: creating, managing, and executing skills\n- **LLM configuration**: managing model settings and parameters\n- **Wallet**: Cashu ecash wallet operations\n- **Storage**: Blossom file uploads/downloads\n- **Utilities**: shell execution, HTTP requests, version info\n\nFeel free to ask me to:\n- Post to Nostr\n- Query events or profiles\n- Manage skills and tasks\n- Read/write files\n- Execute shell commands\n- Work with encrypted storage\n- Or anything else you'd like to test!\n\nWhat would you like me to do?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9354,"completion_tokens":199,"total_tokens":9553,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":9351,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.01268675,"upstream_inference_prompt_cost":0.01169175,"upstream_inference_completions_cost":0.000995},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
{"id":"gen-1777375250-jFanwsCICZFqoelE44Pq","object":"chat.completion","created":1777375250,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I see you've sent a very long string of \"A\" characters. \n\nIs there something specific I can help you with? I'm a test agent with access to various tools for working with Nostr, file operations, HTTP requests, skills, wallets, and more.\n\nFeel free to ask me a question or request something, and I'll do my best to assist you!","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":16024,"completion_tokens":83,"total_tokens":16107,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":6992,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0100582,"upstream_inference_prompt_cost":0.0096432,"upstream_inference_completions_cost":0.000415},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
{"id":"gen-1777375274-zsPFOGPaSztcq1eWkJwI","object":"chat.completion","created":1777375274,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I understand! After the system restarts, I should say hello. \n\nHowever, I should note that I'm currently running and ready to help you. If you're planning to restart the system or agent, just let me know when it comes back up, and I'll greet you with a hello!\n\nIs there anything else you'd like me to help you with in the meantime?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9367,"completion_tokens":84,"total_tokens":9451,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":332,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0017412,"upstream_inference_prompt_cost":0.0013212,"upstream_inference_completions_cost":0.00042},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375278-hK1kwZuer9Lsw5MLxeTY","object":"chat.completion","created":1777375278,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Hello! I'm a test agent ready to help you with whatever you need.","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9367,"completion_tokens":19,"total_tokens":9386,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":332,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0014162,"upstream_inference_prompt_cost":0.0013212,"upstream_inference_completions_cost":0.000095},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
{"id":"gen-1777375342-uCRzfhu0bf1KkFyxOXma","object":"chat.completion","created":1777375342,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll list your Blossom blobs. First, I need to get your pubkey, then I'll need to know which Blossom server to query. Let me start by getting your pubkey:","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01EuoCso6xsH4hg6MtqtEbwB","function":{"name":"nostr_pubkey","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9369,"completion_tokens":84,"total_tokens":9453,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":334,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0017437,"upstream_inference_prompt_cost":0.0013237,"upstream_inference_completions_cost":0.00042},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375355-ZuuW9IXNHn2xcCnAxE0y","object":"chat.completion","created":1777375355,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll check your Cashu wallet balance for you.","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01AjyEY1765A49f2DE6Uh3GG","function":{"name":"cashu_wallet_balance","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9368,"completion_tokens":52,"total_tokens":9420,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":332,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015822,"upstream_inference_prompt_cost":0.0013222,"upstream_inference_completions_cost":0.00026},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
{"id":"gen-1777375359-KpRY8FHWdC5j7tFYnf99","object":"chat.completion","created":1777375359,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Your Cashu wallet is currently **empty** with a balance of **0**. \n\nThe wallet appears to not be loaded yet. This could mean:\n- No mints have been configured\n- No ecash tokens have been received or minted yet\n- The wallet needs to be initialized\n\nWould you like me to help you:\n1. Check wallet mint configuration?\n2. Request a mint quote to add funds?\n3. Configure a mint for your wallet?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9450,"completion_tokens":103,"total_tokens":9553,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9364,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015374,"upstream_inference_prompt_cost":0.0010224,"upstream_inference_completions_cost":0.000515},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
{"id":"gen-1777375423-T6U7hn04dTKnjjFxe19S","object":"chat.completion","created":1777375423,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":null,"refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01RaaLJ4ePRXjbbfg3o6LV73","function":{"name":"nostr_pubkey","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9371,"completion_tokens":39,"total_tokens":9410,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":336,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015212,"upstream_inference_prompt_cost":0.0013262,"upstream_inference_completions_cost":0.000195},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375436-giGLkkFTP46gGTSS9xMv","object":"chat.completion","created":1777375436,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":null,"refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01Y23Q4voefWXQYThdYWU2cL","function":{"name":"my_npub","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9367,"completion_tokens":38,"total_tokens":9405,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":332,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015112,"upstream_inference_prompt_cost":0.0013212,"upstream_inference_completions_cost":0.00019},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375439-LiTUe0VdwVXCM9os7FiY","object":"chat.completion","created":1777375439,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"My npub is: **npub1r6chzymdhvd6d9dj79pfdt073zsls82zyrx86xrtpcfehr8qek7q3rkewf**\n\nThis is my Nostr public key encoded in bech32 format. You can use this to find me on the Nostr network!","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9513,"completion_tokens":83,"total_tokens":9596,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9364,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015004,"upstream_inference_prompt_cost":0.0010854,"upstream_inference_completions_cost":0.000415},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375502-52pu2oVKedn2eurqBVit","object":"chat.completion","created":1777375502,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll retrieve my identity information for you.","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01SEn9gQoVzuKX74JfWfVckc","function":{"name":"agent_identity","arguments":"{}"}},{"type":"function","index":1,"id":"toolu_bdrk_018BxAiMzYUvQbWzDQygahVA","function":{"name":"nostr_agent_profile","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9367,"completion_tokens":68,"total_tokens":9435,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":330,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0016607,"upstream_inference_prompt_cost":0.0013207,"upstream_inference_completions_cost":0.00034},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375516-xBn93xlI322fzADQ3nPP","object":"chat.completion","created":1777375516,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll check the agent version for you.","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_013wKmxmgG5JTUiyGbohVjAN","function":{"name":"agent_version","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9365,"completion_tokens":46,"total_tokens":9411,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":330,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015487,"upstream_inference_prompt_cost":0.0013187,"upstream_inference_completions_cost":0.00023},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375519-JJvmXyq4ll76c2D49pEi","object":"chat.completion","created":1777375519,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I'm **Didactyl v0.2.48**, a sovereign AI agent daemon running on Nostr. \n\nHere are the details:\n- **Name:** Didactyl\n- **Version:** v0.2.48 (Major: 0, Minor: 2, Patch: 48)\n- **Description:** A sovereign AI agent daemon on Nostr\n- **Repository:** https://git.laantungir.net/laantungir/didactyl.git\n\nIs there anything else you'd like to know?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9497,"completion_tokens":124,"total_tokens":9621,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9362,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0016912,"upstream_inference_prompt_cost":0.0010712,"upstream_inference_completions_cost":0.00062},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375582-HLkTRcL7ciicnO3WG706","object":"chat.completion","created":1777375582,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll fetch information about my administrator for you.","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_018YfVsvGA6DtB9CBZH3WFbw","function":{"name":"admin_identity","arguments":"{}"}},{"type":"function","index":1,"id":"toolu_bdrk_01Q35faB3GUEqVgeXcYagANX","function":{"name":"nostr_admin_profile","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9365,"completion_tokens":69,"total_tokens":9434,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":330,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0016637,"upstream_inference_prompt_cost":0.0013187,"upstream_inference_completions_cost":0.000345},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
{"id":"gen-1777375596-rVYt4DZZqybR0cri83ok","object":"chat.completion","created":1777375596,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll fetch your current task list for you.","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01SkQiJkNcACnKfxoaL8QUHT","function":{"name":"task_list","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9367,"completion_tokens":47,"total_tokens":9414,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":332,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015562,"upstream_inference_prompt_cost":0.0013212,"upstream_inference_completions_cost":0.000235},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375600-1i2NzbywIG7vr1pbbB7L","object":"chat.completion","created":1777375600,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Your current task list is empty! You don't have any active tasks yet.\n\nWould you like me to help you:\n- **Add a task** - I can create a new task for you\n- **View completed tasks** - Check what you've already done\n- **Set up a task** - Help you organize something you're working on\n\nJust let me know what you'd like to do, or provide the task details and I can add them for you.","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9480,"completion_tokens":100,"total_tokens":9580,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9364,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0015524,"upstream_inference_prompt_cost":0.0010524,"upstream_inference_completions_cost":0.0005},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
{"id":"gen-1777375663-e99PoJts5k6BizMUmNhQ","object":"chat.completion","created":1777375663,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll add a task and then remove it for you.","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_017Lhypkwt8Wx9eo9yQS3vmF","function":{"name":"task_manage","arguments":"{\"action\": \"add\", \"text\": \"test harness probe task\", \"status\": \"pending\"}"}}]}}],"usage":{"prompt_tokens":9377,"completion_tokens":104,"total_tokens":9481,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":342,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0018537,"upstream_inference_prompt_cost":0.0013337,"upstream_inference_completions_cost":0.00052},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375677-0RglWxj5Ki0dNNPe4Do4","object":"chat.completion","created":1777375677,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"I'll save a test harness probe to memory and then recall it.","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01GBGt8MaQjzZj4i23ij5caL","function":{"name":"memory_save","arguments":"{\"content\": \"Test harness probe - system verification checkpoint. Agent memory subsystem operational. Timestamp: current session. This entry confirms memory_save and memory_recall functions are working correctly.\"}"}}]}}],"usage":{"prompt_tokens":9380,"completion_tokens":103,"total_tokens":9483,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":344,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0018522,"upstream_inference_prompt_cost":0.0013372,"upstream_inference_completions_cost":0.000515},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
{"id":"gen-1777375680-CxwbupX8iy37rE7N441O","object":"chat.completion","created":1777375680,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"tool_calls","native_finish_reason":"tool_use","message":{"role":"assistant","content":"Great! Now let me recall the memory:","refusal":null,"reasoning":null,"tool_calls":[{"type":"function","index":0,"id":"toolu_bdrk_01QgBARiRY5FTx8TJH3GhzU6","function":{"name":"memory_recall","arguments":"{}"}}]}}],"usage":{"prompt_tokens":9569,"completion_tokens":46,"total_tokens":9615,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9376,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0013606,"upstream_inference_prompt_cost":0.0011306,"upstream_inference_completions_cost":0.00023},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
{"id":"gen-1777375696-JOdX4gcv02mKizye0xyb","object":"chat.completion","created":1777375696,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Perfect! ✅ **Test harness probe successful:**\n\n**Saved to memory:**\n- Content: \"Test harness probe - system verification checkpoint. Agent memory subsystem operational. Timestamp: current session. This entry confirms memory_save and memory_recall functions are working correctly.\"\n- Event ID: `6311c65cf9b52fe1fe9bce8052a09f594d6b3dc1f83f8030f45106b8b3a108e2`\n- Kind: 30078 (encrypted agent config)\n- D-tag: \"memory\"\n\n**Recalled from memory:**\n- Successfully retrieved the exact content that was saved\n- Content length: 199 bytes\n- No truncation occurred\n\nThe memory subsystem is operational and both save/recall functions are working correctly! 🎯","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9676,"completion_tokens":188,"total_tokens":9864,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9376,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0021776,"upstream_inference_prompt_cost":0.0012376,"upstream_inference_completions_cost":0.00094},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,15 @@
{"id":"gen-1777375736-lYPEXYI3bEyeSmVzv9zh","object":"chat.completion","created":1777375736,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Hello! I'm a Didactyl Agent - a test agent designed to help you with various tasks. I can assist with things like:\n\n- **Nostr protocol operations** (posting, querying events, managing profiles, etc.)\n- **File operations** (reading and writing local files)\n- **Shell commands** (executing system commands)\n- **HTTP requests** (fetching web resources)\n- **Skills management** (creating, running, and managing reusable skills)\n- **Task management** (tracking and managing tasks)\n- **Wallet operations** (Cashu ecash and Lightning)\n- **File storage** (Blossom server uploads/downloads)\n- And more!\n\nI don't have a specific personal name beyond being your Didactyl Agent, but I'm here to help you with whatever you need. What can I assist you with today?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9369,"completion_tokens":194,"total_tokens":9563,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":334,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0022937,"upstream_inference_prompt_cost":0.0013237,"upstream_inference_completions_cost":0.00097},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
{"id":"gen-1777375740-7wwdu6DnbPK2uHfm9Dhh","object":"chat.completion","created":1777375740,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I'm **Didactyl**, a Nostr-native AI agent. Here's what I do:\n\n**Core Identity:**\n- I'm an autonomous agent running on the Nostr protocol, designed to interact with decentralized networks and handle both on-chain and off-chain tasks\n- I can publish posts, send encrypted messages, manage lists, and interact with the Nostr ecosystem\n\n**Key Capabilities:**\n- **Nostr Operations**: Post notes, send DMs, manage contacts, verify identities, and query events from relays\n- **Skills System**: I can create, adopt, and run modular skills that extend my functionality\n- **Memory & Tasks**: I maintain encrypted memory and task lists stored on Nostr for persistence\n- **Financial**: I can handle Cashu ecash wallets and payments\n- **File Management**: I can read/write local files and interact with Blossom file servers\n- **LLM Integration**: I'm powered by configurable language models and can execute complex workflows\n- **Automation**: I support triggered skills via webhooks, cron schedules, DMs, and Nostr subscriptions\n\n**How I Work:**\nI'm a test agent in this instance, ready to help you explore what I can do. I combine Nostr's decentralized messaging with AI reasoning to create a flexible, privacy-respecting automation platform.\n\nWhat would you like to do? I can help with Nostr interactions, skill management, file operations, or just about anything else you need!","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9373,"completion_tokens":333,"total_tokens":9706,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":338,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0029937,"upstream_inference_prompt_cost":0.0013287,"upstream_inference_completions_cost":0.001665},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
{"id":"gen-1777375776-aZoApJ1ae9UcNjTPlooQ","object":"chat.completion","created":1777375776,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"# Didactyl Agent\n\nHello! I'm a test agent ready to assist you. I have access to a comprehensive set of tools including:\n\n- **Nostr Protocol**: Publishing events, querying data, managing profiles, DMs, encryption, and more\n- **File Operations**: Reading and writing local files\n- **Shell Execution**: Running commands in the working directory\n- **Skills Management**: Creating, listing, adopting, and running skills\n- **HTTP Requests**: Fetching web resources\n- **LLM Configuration**: Managing model settings\n- **Task & Memory Management**: Storing and recalling agent state\n- **Cashu Wallet**: Managing ecash tokens and mints\n- **Blossom**: File upload/download to Blossom servers\n\nI'm ready to help with any requests. What would you like me to do?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9354,"completion_tokens":188,"total_tokens":9542,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":0,"cache_write_tokens":9351,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.01263175,"upstream_inference_prompt_cost":0.01169175,"upstream_inference_completions_cost":0.00094},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
{"id":"gen-1777375790-hGgvQ0etnXavfdB3WnzF","object":"chat.completion","created":1777375790,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I see you've sent a very long string of the letter \"A\". \n\nI'm here to help! Could you please let me know what you'd actually like me to do? For example, I can:\n\n- Answer questions\n- Help with Nostr-related tasks (posting, querying events, managing profiles, etc.)\n- Execute shell commands\n- Read or write files\n- Manage skills and tasks\n- Work with cryptocurrency wallets (Cashu)\n- Upload/download files (Blossom)\n- And much more\n\nWhat would you like assistance with?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":16024,"completion_tokens":128,"total_tokens":16152,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":6992,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0102832,"upstream_inference_prompt_cost":0.0096432,"upstream_inference_completions_cost":0.00064},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
{"id":"gen-1777375810-NHr1i5tqdEPozD3NpLCF","object":"chat.completion","created":1777375810,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Hello! I'm a test agent powered by Didactyl. I don't have a specific personal name, but you can think of me as your Didactyl assistant. I'm here to help you with various tasks using the tools and capabilities available to me, including Nostr integration, file management, skill management, and more.\n\nIs there anything I can help you with today?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9369,"completion_tokens":84,"total_tokens":9453,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9366,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0013596,"upstream_inference_prompt_cost":0.0009396,"upstream_inference_completions_cost":0.00042},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,23 @@
{"id":"gen-1777375813-DRu7RouOiJlA3MKNwdc3","object":"chat.completion","created":1777375813,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I'm **Didactyl**, a Nostr-based AI agent. Here's a brief description of what I am:\n\n## Core Identity\n- A decentralized autonomous agent that operates on the Nostr protocol\n- I can publish, query, and interact with Nostr events across multiple relays\n- I have my own pubkey and can act independently or on behalf of an admin user\n\n## Key Capabilities\n- **Nostr Integration**: Publish notes, long-form posts, reactions, and encrypted DMs\n- **Skill System**: I can create, adopt, and execute specialized skills (reusable AI workflows)\n- **Task Management**: Track and manage tasks stored on Nostr\n- **Memory**: I maintain encrypted agent memory for continuity across conversations\n- **LLM Integration**: I'm powered by configurable language models (currently using an OpenAI-compatible backend)\n- **Wallet & Payments**: I can manage Cashu ecash wallets and handle Lightning payments\n- **File Operations**: I can read/write files and interact with Blossom file storage servers\n- **Web Integration**: I can fetch HTTP resources and execute shell commands\n\n## How I Work\nI respond to requests and use tools when needed. I can be triggered by:\n- Direct messages (DMs)\n- Scheduled tasks (cron jobs)\n- Nostr subscriptions\n- Webhooks\n- Skill chains\n\nI'm designed to be privacy-respecting, leveraging Nostr's encryption where appropriate, and can operate autonomously or collaboratively with an admin user.\n\nWhat would you like to know more about, or how can I help you?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9373,"completion_tokens":365,"total_tokens":9738,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9370,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.002765,"upstream_inference_prompt_cost":0.00094,"upstream_inference_completions_cost":0.001825},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,17 @@
{"id":"gen-1777375880-ECGT0ZdA9f6YOQOw8lM9","object":"chat.completion","created":1777375880,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I'm ready to help! I'm a Didactyl agent designed to assist you with various tasks using the available tools.\n\nI can help you with:\n\n- **Nostr Operations**: Post notes, query events, manage profiles, send DMs, handle encryption, manage lists and block lists\n- **Skill Management**: Create, edit, list, search, and run skills\n- **Local Operations**: Read/write files, execute shell commands, fetch HTTP resources\n- **Agent Configuration**: Manage LLM settings, model selection, and runtime configuration\n- **Memory & Tasks**: Store and recall agent memory, manage task lists\n- **Wallet Operations**: Check balances, mint/melt ecash, send/receive tokens\n- **File Storage**: Upload/download files via Blossom servers\n- **Relay Management**: Check relay status, fetch relay info, manage subscriptions\n\nWhat would you like me to help you with?","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9354,"completion_tokens":203,"total_tokens":9557,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9351,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0019531,"upstream_inference_prompt_cost":0.0009381,"upstream_inference_completions_cost":0.001015},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
{"id":"gen-1777375894-scuuv4LZNWVF29yV05L7","object":"chat.completion","created":1777375894,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"I see you've sent a very long string of the letter \"A\". \n\nI'm a test agent here to help you with requests and use tools when needed. Is there something specific I can help you with? Feel free to ask me a question or let me know what you'd like to do, and I'll do my best to assist using the available tools.","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":16024,"completion_tokens":78,"total_tokens":16102,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":16024,"cache_write_tokens":0,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0019924,"upstream_inference_prompt_cost":0.0016024,"upstream_inference_completions_cost":0.00039},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,19 @@
{"id":"gen-1777376029-xUzuqdFfKe7nM3xi1ooh","object":"chat.completion","created":1777376029,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Hello! 👋 I'm the Didactyl test agent, and I'm ready to help. I received your message: \"Hello from smoke test\"\n\nI have access to a wide range of tools including:\n\n- **Nostr Protocol Tools** - posting, querying, DMs, profiles, relays, etc.\n- **File Operations** - reading and writing local files\n- **Shell Commands** - executing commands\n- **Skills Management** - creating, editing, and running skills\n- **HTTP Requests** - fetching web resources\n- **Cashu Wallet** - ecash operations\n- **Blossom** - file storage/retrieval\n- **Configuration & Memory** - storing and recalling agent state\n\nWhat would you like me to help you with? Feel free to ask me to:\n- Post to Nostr\n- Query events or profiles\n- Manage files\n- Run commands\n- Create or manage skills\n- Handle any other tasks you need","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9364,"completion_tokens":216,"total_tokens":9580,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":328,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0023972,"upstream_inference_prompt_cost":0.0013172,"upstream_inference_completions_cost":0.00108},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
{"id":"gen-1777376040-qkXhEUESTodU6M3rpqhw","object":"chat.completion","created":1777376040,"model":"anthropic/claude-4.5-haiku-20251001","provider":"Amazon Bedrock","system_fingerprint":null,"choices":[{"index":0,"logprobs":null,"finish_reason":"stop","native_finish_reason":"end_turn","message":{"role":"assistant","content":"Hello! I'm ready to help you with any requests you might have.","refusal":null,"reasoning":null}}],"usage":{"prompt_tokens":9367,"completion_tokens":18,"total_tokens":9385,"cost":0,"is_byok":true,"prompt_tokens_details":{"cached_tokens":9032,"cache_write_tokens":332,"audio_tokens":0,"video_tokens":0},"cost_details":{"upstream_inference_cost":0.0014112,"upstream_inference_prompt_cost":0.0013212,"upstream_inference_completions_cost":0.00009},"completion_tokens_details":{"reasoning_tokens":0,"image_tokens":0,"audio_tokens":0}}}

1
didactyl.pid Normal file
View File

@@ -0,0 +1 @@
131350

70
didactyl_nsigner.log Normal file
View File

@@ -0,0 +1,70 @@
Didactyl - sovereign Nostr agent
Usage:
./didactyl [options]
Options:
-h, --help
Show this help text and exit.
-v, --version
Show version and exit.
--config <path>
Path to config/genesis JSONC file (default: ./genesis.jsonc).
If file is missing, startup falls back to minimal nsec-only mode.
--nsec <nsec_or_hex>
Private key as nsec1... or 64-char hex; overrides DIDACTYL_NSEC.
--admin <npub_or_hex>
Administrator pubkey override; accepts npub1... or 64-char hex.
--api-port <port>
Enable HTTP API and bind to this port (1-65535).
--api-bind <addr>
Enable HTTP API and bind address (example: 127.0.0.1).
--debug <0-5>
Log level (0=fatal, 1=error, 2=warn, 3=info, 4=debug, 5=trace).
--signer <mode>
Signer provider: local | nsigner_unix | nsigner_tcp.
Overrides signer.mode in config and DIDACTYL_SIGNER.
In nsigner_* modes --nsec/DIDACTYL_NSEC are not required.
--signer-socket <name>
Abstract socket name for nsigner_unix (without leading @).
--signer-role <role>
n_signer role selector (default: main).
--signer-timeout <ms>
Per-call signer timeout in milliseconds (default: 15000).
--signer-tcp <host:port>
Shorthand for --signer nsigner_tcp with host/port parsed.
--dump-schemas
Print tool schemas JSON and exit.
--test-tool <name> <args_json>
Execute one tool call locally and print JSON result, then exit.
Environment:
DIDACTYL_NSEC
Fallback private key when --nsec is not provided (local mode only).
DIDACTYL_SIGNER
Fallback signer mode when --signer is not provided.
Examples:
1) Genesis-based startup
./didactyl --config genesis.jsonc
2) nsec-only startup (no config file)
./didactyl --nsec nsec1...
3) nsec via environment variable
DIDACTYL_NSEC=nsec1... ./didactyl
4) Override API bind/port
./didactyl --config genesis.jsonc --api-bind 127.0.0.1 --api-port 8484
5) Sign with a running n_signer (separate the nsec from the agent)
./didactyl --signer nsigner_unix --signer-socket nsigner_hairy_dog --admin npub1...
6) n_signer via TCP
./didactyl --signer-tcp 127.0.0.1:7777 --admin npub1...
7) Dump tool schemas
./didactyl --dump-schemas
8) Test a tool invocation
./didactyl --test-tool config_recall '{"config_name":"llm_config"}'

1
exit_code.txt Normal file
View File

@@ -0,0 +1 @@
1

70
help_output.txt Normal file
View File

@@ -0,0 +1,70 @@
Didactyl - sovereign Nostr agent
Usage:
./didactyl [options]
Options:
-h, --help
Show this help text and exit.
-v, --version
Show version and exit.
--config <path>
Path to config/genesis JSONC file (default: ./genesis.jsonc).
If file is missing, startup falls back to minimal nsec-only mode.
--nsec <nsec_or_hex>
Private key as nsec1... or 64-char hex; overrides DIDACTYL_NSEC.
--admin <npub_or_hex>
Administrator pubkey override; accepts npub1... or 64-char hex.
--api-port <port>
Enable HTTP API and bind to this port (1-65535).
--api-bind <addr>
Enable HTTP API and bind address (example: 127.0.0.1).
--debug <0-5>
Log level (0=fatal, 1=error, 2=warn, 3=info, 4=debug, 5=trace).
--signer <mode>
Signer provider: local | nsigner_unix | nsigner_tcp.
Overrides signer.mode in config and DIDACTYL_SIGNER.
In nsigner_* modes --nsec/DIDACTYL_NSEC are not required.
--signer-socket <name>
Abstract socket name for nsigner_unix (without leading @).
--signer-role <role>
n_signer role selector (default: main).
--signer-timeout <ms>
Per-call signer timeout in milliseconds (default: 15000).
--signer-tcp <host:port>
Shorthand for --signer nsigner_tcp with host/port parsed.
--dump-schemas
Print tool schemas JSON and exit.
--test-tool <name> <args_json>
Execute one tool call locally and print JSON result, then exit.
Environment:
DIDACTYL_NSEC
Fallback private key when --nsec is not provided (local mode only).
DIDACTYL_SIGNER
Fallback signer mode when --signer is not provided.
Examples:
1) Genesis-based startup
./didactyl --config genesis.jsonc
2) nsec-only startup (no config file)
./didactyl --nsec nsec1...
3) nsec via environment variable
DIDACTYL_NSEC=nsec1... ./didactyl
4) Override API bind/port
./didactyl --config genesis.jsonc --api-bind 127.0.0.1 --api-port 8484
5) Sign with a running n_signer (separate the nsec from the agent)
./didactyl --signer nsigner_unix --signer-socket nsigner_hairy_dog --admin npub1...
6) n_signer via TCP
./didactyl --signer-tcp 127.0.0.1:7777 --admin npub1...
7) Dump tool schemas
./didactyl --dump-schemas
8) Test a tool invocation
./didactyl --test-tool config_recall '{"config_name":"llm_config"}'

1
nostr_core_lib.old Submodule

Submodule nostr_core_lib.old added at af06f23939

668
nsigner.log Normal file
View File

@@ -0,0 +1,668 @@
nsigner v0.0.33
Seed phrase is valid and accepted.
System is ready and waiting for connections on @didactyl_test_signer.
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
(none)

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
(none)

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120609 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120609 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120623 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120609 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120623 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120609 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120741 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120623 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120609 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON
Roles
Role Purpose Curve Selector
-------------------- ------------ ------------ ------------
main nostr secp256k1 nostr_index
Activity (latest first)
0708-120741 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120623 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120609 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120554 uid:1000 get_public_key(main) ALLOWED:prompt
0708-120532 uid:1000 get_public_key(main) ALLOWED:prompt

================================================================================
n_signer v0.0.33
================================================================================
> Main Menu
Connections
listen: unix @didactyl_test_signer
client: nsigner --socket-name didactyl_test_signer client '<json>'
fips ipv6: fdb8:36ad:c97a:44a9:e70e:e591:5d53:8f28
fips npub: npub10vt4scusw6lq27qw83nfwp5sqer492h0tnwa8ugqjvp6l4xuz2qsdycrwd
q/x quit
l lock/reunlock
r refresh
A toggle auto-approve
session=unlocked (12 words) signer=didactyl_test_signer derived=1 auto-approve=ON

1
nsigner.pid Normal file
View File

@@ -0,0 +1 @@
131270

View File

@@ -0,0 +1,247 @@
# Cron Trigger Pipeline: How It Works and How to Make It Robust
## Current Architecture: Skill Events → Trigger Registration
The pipeline has **two paths** for getting a cron trigger loaded, plus a **polling loop** that actually fires them.
### Path 1: Bulk load at startup (EOSE-driven)
```mermaid
sequenceDiagram
participant Main as main.c startup
participant NH as nostr_handler
participant Relays as Nostr Relays
participant TM as trigger_manager
Main->>TM: trigger_manager_init - capacity=16, last_poll_at=0
Main->>TM: trigger_manager_load_from_startup_events
Note over TM: Loads triggers from genesis startup_events<br/>only dm triggers typically here
Main->>NH: nostr_handler_set_self_skill_eose_callback<br/>registers on_self_skill_eose_load_triggers
Main->>NH: nostr_handler_subscribe_self_skills
NH->>Relays: REQ kinds 31123, 31124, 10123<br/>authors = agent pubkey
Relays-->>NH: EVENT skill events arrive one by one
NH->>NH: on_self_skill_event for each<br/>caches in g_self_skill_events<br/>calls register_trigger_from_self_skill_event
Relays-->>NH: EOSE
NH->>NH: on_self_skill_eose sets g_self_skill_eose_received=1
NH->>Main: calls on_self_skill_eose_load_triggers callback
Main->>TM: trigger_manager_load_from_skills<br/>reads ALL cached skills via<br/>nostr_handler_get_self_events_by_kind_json
Note over TM: For each skill with trigger+filter tags:<br/>calls trigger_manager_add
Main->>Main: nostr_handler_wait_for_self_skill_eose returns 0
Main->>Main: Startup step 14 passes
Main->>Main: Enter main poll loop
```
### Path 2: Live skill event (post-startup)
```mermaid
sequenceDiagram
participant Relays as Nostr Relays
participant NH as nostr_handler
participant TM as trigger_manager
Note over NH: Subscription stays open after EOSE
Relays-->>NH: New/updated skill EVENT arrives
NH->>NH: on_self_skill_event
NH->>NH: register_trigger_from_self_skill_event
Note over NH: Checks: kind 31123/31124?<br/>Has trigger+filter tags?<br/>Is adopted via kind 10123?
NH->>TM: trigger_manager_add or update
NH->>NH: self_skill_cache_upsert_event_locked
```
### Path 3: Cron polling in main loop
```mermaid
sequenceDiagram
participant Main as main loop
participant TM as trigger_manager
participant Agent as agent.c
loop Every iteration
Main->>TM: trigger_manager_poll
Note over TM: Throttled to once per 30 seconds
TM->>TM: For each trigger where type==CRON:<br/>1. Validate cron_expr<br/>2. Check cron_matches_now<br/>3. Check last_cron_fire dedup - 50s guard
TM->>Agent: execute_llm_action with synthetic cron event
end
```
---
## The Six Failure Points
I have identified six places where a cron trigger can silently fail to load or fire. They are ordered from most likely to least likely given the logs from laantungir.net.
### 1. EOSE timeout kills startup entirely
**Where:** [`main.c:14941515`](src/main.c:1494)
The agent waits 15 seconds for self-skill EOSE. If relays are slow or the connection is flaky, this times out and **the entire agent process exits**:
```c
const int self_skill_eose_timeout_ms = 15000;
if (nostr_handler_wait_for_self_skill_eose(self_skill_eose_timeout_ms) != 0) {
// ... prints error, cleans up, return 1
}
```
From [`debug.log`](debug.log) line 670:
```
[2026-04-06 16:16:49] [ERROR] startup checklist [14] Subscribe self-skill cache: failed
(self-skill EOSE not received within timeout)
```
**Impact:** If the agent crashes at startup, no triggers load at all. If systemd restarts it and it crashes again, you get a restart loop with zero cron execution.
### 2. Adoption check gates live trigger registration
**Where:** [`nostr_handler.c:1462`](src/nostr_handler.c:1462)
When a skill event arrives live via [`on_self_skill_event()`](src/nostr_handler.c:2428), it calls [`register_trigger_from_self_skill_event()`](src/nostr_handler.c:1418) which checks:
```c
if (!self_skill_is_adopted_local(kind_val, pubkey->valuestring, d_tag)) {
DEBUG_INFO("live self-skill trigger ignored (not adopted) d_tag=%s", d_tag);
return;
}
```
[`self_skill_is_adopted_local()`](src/nostr_handler.c:1366) scans `g_self_skill_events` for a kind 10123 event with an `["a", "31123:<pubkey>:<d_tag>"]` tag. If the adoption event hasn't arrived yet (race condition — skill event arrives before adoption event), the trigger is silently skipped.
**Critically:** The bulk load path in [`trigger_manager_load_from_skills()`](src/trigger_manager.c:818) does **NOT** check adoption at all — it loads every skill with trigger+filter tags. So the adoption gate only affects the live path.
### 3. Bulk load is one-shot with `loaded_once` guard
**Where:** [`main.c:42`](src/main.c:42)
```c
if (ctx->loaded_once) {
DEBUG_TRACE("deferred trigger load skipped (already loaded once)");
return;
}
```
The EOSE callback fires once, calls [`trigger_manager_load_from_skills()`](src/trigger_manager.c:818), sets `loaded_once = 1`, and never runs again. If a skill event arrives **after** EOSE but **before** the live path processes it, it falls into a gap:
- The bulk load already ran and won't run again
- The live [`register_trigger_from_self_skill_event()`](src/nostr_handler.c:1418) may reject it due to the adoption check
### 4. Cron expression validation rejects silently at add time
**Where:** [`trigger_manager.c:11061112`](src/trigger_manager.c:1106)
```c
if (t->trigger_type == TRIGGER_TYPE_CRON) {
if (!cron_expr_is_valid(filter_json, normalized_cron, sizeof(normalized_cron))) {
DEBUG_WARN("trigger add rejected: invalid cron expression d_tag=%s expr=%s", ...);
memset(t, 0, sizeof(*t));
return -1;
}
}
```
This does log a warning, but the caller in [`trigger_manager_load_from_skills()`](src/trigger_manager.c:896) just silently skips to the next skill. The `considered` count increments but `loaded` does not — the only evidence is in the log line `trigger manager loaded X trigger(s) from self skills (considered=Y)` where X < Y.
The existing plan in [`fix_cron_triggers_not_firing.md`](plans/fix_cron_triggers_not_firing.md) documents that a bare `*` was being used instead of `* * * * *`, and that shorthand expansion was added. This has been fixed.
### 5. Poll throttle delays first evaluation by up to 30 seconds
**Where:** [`trigger_manager.c:1395`](src/trigger_manager.c:1395)
```c
if (mgr->last_poll_at > 0 && (now - mgr->last_poll_at) < 30) {
return 0;
}
```
After init, `last_poll_at` starts at 0 (fixed from the original bug where it was `time(NULL)`), so the first poll runs immediately. But subsequent polls are throttled to every 30 seconds. For a daily cron this is fine, but it means the cron match window is checked at most twice per minute.
### 6. Cron dedup guard can skip legitimate fires
**Where:** [`trigger_manager.c:1422`](src/trigger_manager.c:1422)
```c
if (t->last_cron_fire > 0 && (now - t->last_cron_fire) < 50) {
continue;
}
```
With a 30-second poll interval and a 50-second dedup window, a cron that matches at minute X will fire once and then be suppressed for the next poll. This is correct behavior for preventing double-fires within the same minute. But if the system clock jumps or NTP adjusts, this could cause unexpected skips.
---
## Robustness Suggestions
### A. Retry EOSE with backoff instead of hard abort
**Current:** EOSE timeout process exit.
**Proposed:** Retry 23 times with increasing timeout (15s, 30s, 60s). If all retries fail, start the agent in degraded mode with only startup-config triggers active, and schedule a background re-attempt.
```mermaid
flowchart TD
SUB[Subscribe self-skills] --> WAIT{Wait for EOSE}
WAIT -->|Received| LOAD[Load triggers from skills]
WAIT -->|Timeout 15s| RETRY1{Retry 1 - 30s timeout}
RETRY1 -->|Received| LOAD
RETRY1 -->|Timeout| RETRY2{Retry 2 - 60s timeout}
RETRY2 -->|Received| LOAD
RETRY2 -->|Timeout| DEGRADED[Start in degraded mode<br/>startup triggers only<br/>schedule background retry]
LOAD --> READY[Agent READY]
DEGRADED --> READY
```
### B. Remove adoption gate from live trigger registration
The bulk load path doesn't check adoption. The live path does. This inconsistency means a skill created via `skill_create` with `auto_adopt=true` might not register its trigger if the adoption event arrives on a different relay or with different timing.
**Proposed:** Either:
1. Remove the adoption check from [`register_trigger_from_self_skill_event()`](src/nostr_handler.c:1462) to match the bulk path, OR
2. Add the adoption check to the bulk path too for consistency, but with a fallback: if adoption events haven't loaded yet, defer the check.
Option 1 is simpler and more robust. The agent already only subscribes to its own pubkey's events, so all skills in the cache are self-authored.
### C. Allow re-running bulk trigger load
Remove the `loaded_once` guard or replace it with a debounced re-load. When new skill events arrive after EOSE, schedule a re-scan of all cached skills after a short delay (e.g., 5 seconds). This closes the gap between EOSE and late-arriving events.
### D. Add a periodic trigger reconciliation
Every N minutes (e.g., 5), compare the set of cached skills that have trigger+filter tags against the active trigger list. Register any missing triggers. This is a safety net that catches any trigger that was missed during startup.
```c
// In trigger_manager_poll, after cron evaluation:
if (now - mgr->last_reconcile_at > 300) {
trigger_manager_load_from_skills(mgr); // idempotent via update path
mgr->last_reconcile_at = now;
}
```
### E. Log trigger registration summary at startup
After the deferred trigger load, log not just the count but also which trigger types were loaded:
```
trigger manager loaded 3 trigger(s): dm=2 cron=1 webhook=0 chain=0 nostr-sub=0
```
This makes it immediately obvious from the log whether a cron trigger was picked up.
### F. Add an HTTP API endpoint for trigger status
Expose `/api/triggers` that returns the same JSON as the `trigger_list` tool. This allows external monitoring (e.g., a health check script) to verify that expected cron triggers are loaded without going through the LLM.
---
## Summary of What Happened on laantungir.net
Based on the logs:
1. The agent started successfully multiple times (startup step 14 passed with `skills=3 adoptions=1` or similar).
2. The deferred trigger load status shows **only dm-type triggers** were loaded no cron triggers appear in any log entry.
3. On 2026-04-06, the agent failed at startup step 14 with EOSE timeout, meaning it never even got to trigger loading.
4. There is **zero** evidence of `cron trigger matched` or `cron trigger skipped` in any log file, confirming the cron trigger was never in the active trigger set.
The most likely explanation: the cron skill event exists on relays but either:
- It was missing the `["trigger", "cron"]` and/or `["filter", "<expr>"]` tags when it was published
- It was not adopted (no kind 10123 event referencing it) and arrived via the live path where adoption is checked
- The cron expression was invalid and was silently rejected at add time
- The EOSE timeout prevented the agent from ever reaching the trigger loading phase
Running `trigger_list` on the live server will definitively answer which of these is the case.

View File

@@ -0,0 +1,148 @@
# Fix: Self-Skill Startup Race (step 14 false-negative)
## Symptom
`didactyl.service` / `simon.service` intermittently fail startup at step 14:
```
startup checklist [14] Subscribe self-skill cache: failed (no skill events found after EOSE)
```
…even though the required events (kind 31123/31124 skills and kind 10123 adoption list)
demonstrably exist on `relay.laantungir.net` (verified with `nak`, returned in well under
a second). On other restarts the identical setup succeeds: `ok (skills=3 adoptions=1)`.
The failure is timing-dependent.
## How startup relay polling works (mechanics)
- Each startup step opens its **own** subscription (its own `REQ` + filter). Step 14's
filter is built in [`nostr_handler_subscribe_self_skills()`](src/nostr_handler.c:2800):
`{"kinds":[31123,31124,10123],"authors":[<agent_pubkey>],"limit":300}`.
- That subscription is sent to **all** configured relays in parallel inside
[`nostr_relay_pool_subscribe()`](nostr_core_lib/nostr_core/core_relay_pool.c:967).
- This is the **async/streaming** path: events arrive over time via
[`on_self_skill_event()`](src/nostr_handler.c:2478) which upserts into the shared cache
`g_self_skill_events`, and an EOSE-complete callback
([`on_self_skill_eose`](src/nostr_handler.c:2066)) flips `g_self_skill_eose_received`.
- Step 14 then immediately runs
[`nostr_handler_validate_self_skill_cache()`](src/nostr_handler.c:3089) against whatever
is in the cache at that instant.
## Root cause
The async EOSE-complete signal is decoupled from "did the relay that actually has the
events get queried and deliver yet." Two independent contributing factors:
1. **Relay connection timing.** The self-skill subscription is registered shortly after
startup. If `relay.laantungir.net` is not yet fully connected when the subscription's
completion is computed, the empty relays (`damus`, `primal`) EOSE almost instantly and
the per-relay **timeout fallback**
([`core_relay_pool.c:2128`](nostr_core_lib/nostr_core/core_relay_pool.c:2128)) marks the
remaining relay "done" after `relay_timeout_seconds` (=12) without ever receiving its
events. EOSE-complete fires with an empty cache → validation fails.
2. **Validation fires the instant completion is signaled**, with no re-check, so any race
where laantungir's events land microseconds later is lost.
This matches the `<1s` `nak` observation: when laantungir is connected and queried, it
answers almost instantly; the failures are the cycles where it wasn't
connected/queried/processed before the async completion fired.
### Why FIRST → FULL_SET alone does NOT fix it
`maybe_complete_subscription_eose()` waits for **all** relays in both modes; the only
difference is the payload passed to the callback. The cache is filled by the EVENT
callback, not the EOSE payload. Changing the mode changes neither connection timing nor
when events are available.
## Fix: use the synchronous query for the startup self-skill load
There is already a correct, synchronous "collect all events until EOSE/timeout, then
return them" primitive used elsewhere at startup (e.g. kind-10002 discovery):
- [`nostr_handler_query_json()`](src/nostr_handler.c:3395) →
[`nostr_relay_pool_query_sync()`](nostr_core_lib/nostr_core/core_relay_pool.c:1340).
- A self-skill-specific wrapper already exists and reuses it:
[`nostr_handler_refresh_self_skill_cache_from_relays()`](src/nostr_handler.c:3751),
which queries kinds 31123/31124/10123 for the agent author (and also pulls adopted
skills), populating the cache synchronously.
The synchronous query is the architecturally correct tool for "give me the complete
current set before proceeding," which is exactly what step 14 needs. It also drives the
poll/receive loop itself
([`core_relay_pool.c:1405`](nostr_core_lib/nostr_core/core_relay_pool.c:1405)) until all
connected relays EOSE or the timeout elapses.
### Important caveat to handle: connection readiness
`nostr_relay_pool_query_sync()` only queries relays that are **connected at call time**
(`if (connected_count == 0) return NULL;` at
[`core_relay_pool.c:1392`](nostr_core_lib/nostr_core/core_relay_pool.c:1392)). If
`relay.laantungir.net` is still mid-connect when step 14 runs, a sync query could still
miss it. Therefore the fix must ensure the relay holding the events is connected (or wait
briefly for it) before/within the query.
### Plan
1. **Replace the step-14 async wait+validate with a synchronous load.** In
[`src/main.c`](src/main.c) step 14 (~line 1518), instead of relying solely on
`nostr_handler_wait_for_self_skill_eose()` + an immediate
`nostr_handler_validate_self_skill_cache()`:
- Keep registering the live subscription (so ongoing skill updates still stream in via
`on_self_skill_event`) — this is still wanted for runtime.
- For the startup *gate*, call
[`nostr_handler_refresh_self_skill_cache_from_relays(timeout_ms)`](src/nostr_handler.c:3751)
with a sensible timeout (e.g. 800010000 ms). This performs the synchronous,
connection-aware query and fills `g_self_skill_events`.
- Then run `nostr_handler_validate_self_skill_cache(&skills, &adoptions)`.
2. **Wait for the self relay (laantungir) to be connected before the sync query.** Reuse
the existing relay-readiness helper pattern (`wait_for_connected_relays`) — but ensure
we wait specifically until the relay list discovered from kind 10002 (which includes
`relay.laantungir.net`) is connected, not just "any relay." If we already have a
connected-count wait, extend/bound it so the relay that owns the events has a fair
chance to connect before the sync query runs.
3. **Bounded retry around the sync query.** If the first sync query returns an empty cache,
retry the sync query a small, bounded number of times (e.g. up to ~58s total),
pumping `nostr_handler_poll()` between attempts to let connections settle. Only fail
step 14 after the bounded retries still yield an empty cache. This converts a transient
connection-timing miss into a brief wait instead of a hard failure.
4. **Keep the async subscription for runtime updates.** Do not remove the live
subscription; it's still responsible for picking up skill changes after startup. Only
the *startup gate* switches to the synchronous load for determinism.
### Why this is the right layer
- It uses the library's intended synchronous collect-all primitive rather than racing a
streaming subscription against an immediate validation.
- It is connection-aware and bounded, so a slow/late relay connect becomes a short wait,
not a false "no skill events" failure.
- It does not require modifying `nostr_core_lib` (though if desired, a follow-up could add
a `query_sync` variant that waits for a named relay to connect; not required here).
## Interaction with the failure-DM throttle (already shipped)
- On success, the READY path clears the throttle marker
([`src/main.c`](src/main.c) `startup_failure_marker_clear`). No change needed.
- After this fix, step-14 failures should be genuinely rare (real outage / events truly
absent), and the (single, throttled) failure DM will carry relay states + needed event
kinds for accurate diagnosis.
## Verification
1. Build (`make`) clean, then `build_static.sh`.
2. Deploy to VM410; restart both services many times in a row and confirm step 14 reaches
`ok (skills=N adoptions=M)` **consistently** (no intermittent false negatives).
3. Inspect logs to confirm the synchronous query path is used and that, on a cold cycle,
it waits for `relay.laantungir.net` to connect and then returns the events.
4. Negative test: configure only empty relays (no skill events anywhere) and confirm step
14 still fails after the bounded retries (no false positive), sending exactly one
throttled failure DM.
5. Confirm a normal successful startup still sends the startup DM and clears the marker.
## Out of scope (possible follow-ups)
- Adding a `nostr_core_lib` `query_sync` variant that explicitly waits for specific
relays to connect before issuing the REQ.
- Softening step 14 into a degraded-start mode.

View File

@@ -0,0 +1,77 @@
# Fix: Trigger Manager Bypasses Skill Adoption List
## Problem
`trigger_manager_load_from_skills()` and `trigger_manager_reconcile_from_relays()`
activate cron/webhook/subscription triggers for **every** self-authored skill event
(kind 31123/31124) that has trigger metadata, without checking whether the skill is
on the kind 10123 adoption list.
This means a skill that was published but never adopted (or was un-adopted) will
still have its cron trigger firing.
Contrast: `agent.c:refresh_adopted_skills_cache_if_needed()` properly fetches the
kind 10123 list, parses `"a"` tags, and only loads adopted skills — and also checks
the `enabled` tag. The trigger manager was written as a parallel system that skips
both gates.
## Root Cause
- `trigger_manager.c:939``trigger_manager_load_from_skills()`: no reference to
kind 10123 or adoption anywhere in the function. Calls `trigger_manager_add()`
unconditionally.
- `trigger_manager.c:592``trigger_manager_reconcile_from_relays()`: same bug.
Currently disabled (`enable_periodic_reconcile = 0` at line 1575) but should be
fixed before re-enabling.
- Neither function checks the `enabled` tag either, unlike
`trigger_manager_load_from_startup_events()` (line 1078) which does check it.
## Fix
### 1. Add a static helper: `load_adopted_d_tags()`
Add a static function in `trigger_manager.c` that:
- Fetches kind 10123 events via `nostr_handler_get_self_events_by_kind_json(10123)`
- Selects the latest event by `created_at` (same logic as agent.c)
- Parses `"a"` tags using a local `parse_skill_address_tag_local()` equivalent
- Populates a fixed-size array of adopted d_tag strings
- Returns the count
Since both call sites only deal with self-authored skills, matching on d_tag
alone is sufficient (the pubkey in the "a" tag will be the agent's own).
### 2. Add `enabled` tag check
Both functions should read the `enabled` tag (defaulting to `"true"`) and skip
skills where `enabled` is `false` or `0`, matching the pattern already used in
`trigger_manager_load_from_startup_events()`.
### 3. Gate `trigger_manager_load_from_skills()`
Before calling `trigger_manager_add()`, check:
1. The skill's d_tag is in the adopted set
2. The skill's `enabled` tag is not false/0
If the adoption list is empty or missing, log a warning and load nothing (do not
fall back to loading all skills — that's the bug).
### 4. Gate `trigger_manager_reconcile_from_relays()`
Apply the same adoption + enabled checks. This ensures the code is correct when
`enable_periodic_reconcile` is eventually flipped back to 1.
### 5. Pass `is_enabled` to `trigger_manager_add()`
Currently both functions pass `1` (hardcoded enabled) as the `enabled` parameter.
Change to pass the actual `is_enabled` value derived from the `enabled` tag.
## Files Changed
- `src/trigger_manager.c` — add helper, fix both functions
## Risk
Low. The fix adds a filter before `trigger_manager_add()`. If the adoption list
is present and correct, behavior is unchanged for adopted skills. If the adoption
list is missing, triggers simply won't load (which is the correct behavior —
nothing should fire if nothing is adopted).

View File

@@ -0,0 +1,127 @@
# NIP-17 Gift Wrap Send Failure — Investigation
## Status: Resolved — Fixed in code (2026-04-11)
## Date Discovered: 2026-04-11
## Symptom
Every outbound NIP-17 DM send from the Anvil agent fails with:
```
NIP-17 send aborted: gift_wrap creation failed for 1ec454734dcbf6fe...
auto DM fallback to NIP-04 for 1ec454734dcbf6fe... after NIP-17 send failure
```
The agent successfully falls back to NIP-04 (kind 4), so DMs are still delivered. However, NIP-17 outbound is completely broken.
**Inbound NIP-17 works fine** — the agent successfully receives and decrypts kind 1059 gift wraps from the admin.
## Affected Code Path
### Send path (broken):
1. `nostr_handler_send_dm_auto_with_role()` in `src/nostr_handler.c:3193` — routes to NIP-17 when `dm_protocol` is `nip17` or `both`
2. `nostr_handler_send_dm_nip17_with_role()` in `src/nostr_handler.c:4050` — creates chat event, calls `nostr_nip17_send_dm()`
3. `nostr_nip17_send_dm()` in `nostr_core_lib/nostr_core/nip017.c:260` — iterates recipients, creates seal + gift wrap
4. `nostr_nip59_create_seal()` in `nostr_core_lib/nostr_core/nip059.c:150`**encrypts rumor JSON with NIP-44**
5. `nostr_nip59_create_gift_wrap()` in `nostr_core_lib/nostr_core/nip059.c:226` — wraps seal with random key
### Receive path (working):
1. `on_event()` receives kind 1059
2. `nostr_nip17_receive_dm()` in `nostr_core_lib/nostr_core/nip017.c:326` — unwraps gift, unseals rumor
3. Successfully extracts kind 14 content
## Probable Root Cause: Fixed Buffer Overflow in Seal Encryption
In `nostr_core_lib/nostr_core/nip059.c:163-165`:
```c
char encrypted_content[4096]; // Should be large enough for most events
int encrypt_result = nostr_nip44_encrypt(sender_private_key, recipient_public_key,
rumor_json, encrypted_content, sizeof(encrypted_content));
```
The seal creation uses a **fixed 4096-byte stack buffer** for the NIP-44 encrypted output. The rumor JSON includes the full DM message content. When the agent sends long responses (the FIPS mesh conversation had multi-KB markdown tables), the rumor JSON easily exceeds 4096 bytes after NIP-44 encryption overhead (base64 encoding roughly 4/3x expansion + padding + nonce).
**Evidence:**
- The agent's DM responses in the log were 2-5KB of markdown content
- After JSON serialization of the kind 14 rumor (adding pubkey, tags, created_at, kind fields), the total is larger
- NIP-44 encryption adds: 32-byte nonce + padding + base64 encoding → roughly 1.5-2x expansion
- A 3KB message → ~4.5KB rumor JSON → ~6-9KB encrypted → overflows 4096 buffer
- `nostr_nip44_encrypt()` returns error, `nostr_nip59_create_seal()` returns NULL
- `nostr_nip17_send_dm()` skips the recipient, returns 0 wraps
- `nostr_handler_send_dm_nip17_with_role()` logs "gift_wrap creation failed"
**Why receive works:** The receive path uses `nostr_nip44_decrypt()` which likely allocates dynamically or has a larger buffer.
## Secondary Suspect: NIP-44 Encryption Implementation
The NIP-44 encrypt function itself may have issues with large payloads. Need to check:
- `nostr_nip44_encrypt()` in `nostr_core_lib/nostr_core/nip044.c`
- Whether it handles the output buffer size parameter correctly
- Whether it returns an error code that distinguishes "buffer too small" from other failures
## Anvil Config Context
The Anvil agent's genesis config (`/home/user/anvil/genesis.jsonc`) has:
```json
"dm_protocol": "nip04"
```
But the encrypted user-settings on Nostr (kind 30078) may have overridden this to `"both"` at runtime, which is why NIP-17 send is being attempted.
## Recommended Fix
### Option A: Dynamic allocation (preferred)
Replace the fixed 4096-byte buffer in `nostr_nip59_create_seal()` with dynamic allocation:
```c
size_t rumor_len = strlen(rumor_json);
size_t encrypted_buf_size = rumor_len * 2 + 256; // generous overhead for NIP-44
char* encrypted_content = malloc(encrypted_buf_size);
```
### Option B: Larger fixed buffer (quick fix)
Increase the buffer to 64KB or 128KB:
```c
char encrypted_content[131072]; // 128KB should handle any reasonable DM
```
Note: This is a stack allocation, so very large buffers could cause stack overflow.
### Also check `nostr_nip59_create_gift_wrap()`
The gift wrap function at `nip059.c:226` may have a similar fixed-buffer issue for encrypting the seal JSON.
## Log Evidence
From `/home/user/anvil/debug.log` (2026-04-11):
```
[2026-04-11 09:45:14] [WARN ] NIP-17 send aborted: gift_wrap creation failed for 1ec454734dcbf6fe...
[2026-04-11 09:45:14] [WARN ] auto DM fallback to NIP-04 for 1ec454734dcbf6fe... after NIP-17 send failure
[2026-04-11 09:50:16] [WARN ] NIP-17 send aborted: gift_wrap creation failed for 1ec454734dcbf6fe...
[2026-04-11 09:50:16] [WARN ] auto DM fallback to NIP-04 for 1ec454734dcbf6fe... after NIP-17 send failure
[2026-04-11 09:53:42] [WARN ] NIP-17 send aborted: gift_wrap creation failed for 1ec454734dcbf6fe...
[2026-04-11 09:53:42] [WARN ] auto DM fallback to NIP-04 for 1ec454734dcbf6fe... after NIP-17 send failure
```
This pattern is 100% consistent — every outbound NIP-17 attempt fails, every time.
## Related Files
- `nostr_core_lib/nostr_core/nip059.c` — Gift wrap / seal creation (probable bug location)
- `nostr_core_lib/nostr_core/nip044.c` — NIP-44 encryption (check buffer handling)
- `nostr_core_lib/nostr_core/nip017.c` — NIP-17 DM send/receive orchestration
- `src/nostr_handler.c:4050` — Agent-level NIP-17 send function
- `plans/nip17_messaging.md` — Original NIP-17 implementation plan
## Related Existing Plan
The `plans/nip17_messaging.md` document covers the original NIP-17 implementation. This investigation is specifically about the send-side gift wrap failure that emerged in production.
## Resolution Summary
Implemented in `nostr_core_lib/nostr_core/nip059.c`:
- Replaced fixed encryption buffers in `nostr_nip59_create_seal()` and `nostr_nip59_create_gift_wrap()` with dynamically sized heap buffers calculated from NIP-44 padding/base64 overhead.
- Replaced fixed decrypt buffers in `nostr_nip59_unwrap_gift()` and `nostr_nip59_unseal_rumor()` with dynamic buffers sized from ciphertext length.
- Added missing cleanup path in `nostr_nip59_create_seal()` for failure after encryption allocation.
Expected outcome: outbound NIP-17 gift wrap creation no longer fails for multi-KB DM payloads due to fixed buffer limits.

View File

@@ -0,0 +1,440 @@
# n_signer Integration Plan — didactyl
## Goal
Separate control of the nsec from the didactyl agent by routing signing/encryption
through `n_signer` — a separate foreground process that holds key material in locked
memory and signs on request. A later phase may embed n_signer into the didactyl binary
so one self-contained binary spawns an n_signer in a separate window; that is deferred
because of a reliability concern (if the agent loses signing ability it cannot even DM
its admin about the failure).
This plan covers two distinct work items:
1. **Update didactyl's vendored `nostr_core_lib`** to the upstream version that already
implements the nsigner client (M1M6 complete, upstream `VERSION` 0.6.6). This is a
mechanical sync that changes no runtime behavior.
2. **Opt-in migration of didactyl call sites** to the `nostr_signer_t` provider so the
raw private key can leave the agent process. This is the actual nsec-separation work
and is staged so reliability is preserved.
---
## Background — what upstream already provides
Upstream `nostr_core_lib` (git.laantungir.net/nostr_core_lib, v0.6.6) has shipped the
full signer abstraction. didactyl's vendored copy predates all of it.
New upstream modules:
- [`nostr_core/nostr_signer.{h,c}`](../nostr_core_lib/nostr_core/nostr_signer.h) —
`nostr_signer_t` opaque handle + vtable. Two backends:
- **local** — `nostr_signer_local(privkey[32])`, wraps today's raw-key path. Output-equivalent.
- **remote (nsigner)** — `nostr_signer_nsigner_unix/serial/tcp/fds(...)`, guarded by
`NOSTR_ENABLE_NSIGNER_CLIENT`.
- [`nostr_core/nsigner_client.{h,c}`](../nostr_core_lib/nostr_core/nsigner_client.h) —
framing, JSON-RPC verbs, kind-27235 auth envelope, error mapping.
- [`nostr_core/nsigner_transport.{h,c}`](../nostr_core_lib/nostr_core/nsigner_transport.h) —
pluggable transport vtable: AF_UNIX abstract, TCP, USB-CDC serial, fd-pair (stdio/qrexec).
Verbs mirror n_signer's wire contract: `get_public_key`, `sign_event`,
`nip04_encrypt/decrypt`, `nip44_encrypt/decrypt`.
Parallel `*_with_signer` entry points added across the library (legacy raw-key APIs are
preserved as thin wrappers over the local backend, so existing projects keep compiling
and behaving identically):
- NIP-01: `nostr_create_and_sign_event_with_signer`
- NIP-17: `nostr_nip17_create_relay_list_event_with_signer`,
`nostr_nip17_send_dm_with_signer`, `nostr_nip17_receive_dm_with_signer`
- NIP-42: `nostr_nip42_create_auth_event_with_signer`
- NIP-46: request/response/decrypt/session-init `*_with_signer` variants
- NIP-59: seal/unwrap/unseal `*_with_signer` variants
- NIP-60 / NIP-61: all cashu event-creation `*_with_signer` variants
- Blossom: `blossom_create_auth_header_with_signer`,
`blossom_upload_with_signer`, `blossom_upload_file_with_signer`,
`blossom_delete_with_signer`
- Relay pool: `nostr_relay_pool_set_auth_with_signer` — the pool now stores an
`auth_signer` instead of a raw key, so NIP-42 AUTH events are signed through the
provider on relay challenge. **This was the hardest blocker and it is already solved
upstream.**
Upstream `build.sh` unconditionally defines `-DNOSTR_ENABLE_NSIGNER_CLIENT=1` and
compiles `nostr_signer.c`, `nsigner_transport.c`, `nsigner_client.c`.
Dependency direction is unchanged and non-circular: n_signer (server) depends on
`nostr_core_lib` for leaf crypto; `nostr_core_lib` gains a *client* that consumes its
own primitives. Nobody imports anyone's binary in a loop.
---
## Current didactyl state (what we are updating from)
- `nostr_core_lib/` is a **vendored source directory** (no git submodule; no
`.gitmodules`). Built via `./nostr_core_lib/build.sh --nips=001,004,...,061` into a
static `libnostr_core_*.a`, linked by [`Makefile`](../Makefile:56) and the Docker
static build ([`Dockerfile.alpine-musl`](../Dockerfile.alpine-musl:81)).
- The vendored tree has **none** of the nsigner pieces: no `nostr_signer.*`,
no `nsigner_*.*`, no `*_with_signer` variants. The relay pool still uses the raw-key
AUTH path ([`nostr_core_lib/nostr_core/core_relay_pool.c`](../nostr_core_lib/nostr_core/core_relay_pool.c:682)).
- didactyl holds the raw 32-byte key in [`cfg->keys.private_key`](../src/config.h:16)
and passes it directly into ~30+ library call sites (event signing, NIP-04/44
encrypt/decrypt, NIP-17 gift wraps, NIP-60/61 cashu, blossom, relay pool AUTH).
---
## Architecture (target)
```mermaid
graph TD
A[didactyl src] --> B[nostr_core_lib vendored]
B --> C[nostr_signer_t local backend]
B --> D[nostr_signer_t nsigner remote backend]
D --> E[nsigner client: framing + auth envelope]
E --> F[nostr_create_and_sign_event in nostr_core_lib]
G[n_signer server binary] --> B
```
didactyl constructs **one** `nostr_signer_t*` at startup and threads it through every
signing/encryption/AUTH call site. The backend is chosen by config:
- `signer.mode = "local"``nostr_signer_local(cfg->keys.private_key)` (today's behavior).
- `signer.mode = "nsigner_unix"``nostr_signer_nsigner_unix(socket_name, role, timeout_ms)`.
- (future) `nsigner_tcp`, `nsigner_serial`, `nsigner_fds`.
The raw `cfg->keys.private_key` is only populated in `local` mode. In remote modes the
agent process never holds the nsec; it learns its own pubkey via
`nostr_signer_get_public_key()`.
---
## Phasing
### Phase 1 — Update vendored nostr_core_lib (mechanical, zero behavior change)
Goal: bring didactyl's `nostr_core_lib` source tree to upstream v0.6.6 so the signer
abstraction and nsigner client are available. **No didactyl source changes.** Existing
raw-privkey APIs are preserved upstream as thin wrappers over the local backend, so all
~30 call sites keep compiling and behaving identically.
Steps:
1. Snapshot current vendored tree for diffing/rollback:
`cp -a nostr_core_lib nostr_core_lib.old`
2. Replace the vendored source tree with upstream v0.6.6. Preferred: copy the upstream
`nostr_core/`, `cjson/`, `nostr_websocket/`, `platform/`, `build.sh`, `CMakeLists.txt`
into `nostr_core_lib/`, preserving didactyl-local build quirks only if any exist
(none found — the Dockerfile already `sed`s `build.sh` in-place for fortification).
Do **not** carry over upstream's prebuilt `.a`/`.o` files, `pool.log`, `.venv*`,
`backups/`, `verify_*` artifacts — match didactyl's existing `.gitignore` hygiene.
3. Rebuild the static library:
`cd nostr_core_lib && ./build.sh --nips=001,004,005,006,011,013,017,019,021,042,044,046,059,060,061`
(same NIP set as today; `nostr_signer.c` / `nsigner_*.c` are compiled unconditionally
by upstream `build.sh`).
4. Rebuild didactyl: `make clean && make`. Confirm it compiles and links with no source
changes.
5. Smoke test: run the agent with an nsec-only config and confirm signing/DMs/relay AUTH
still work byte-for-byte (the upstream local backend is output-equivalent to the
legacy path; there is an upstream test `test_event_creation_equivalence_with_signer`
that asserts this).
6. Static (Docker) build: `./build_static.sh`. The Dockerfile copies `nostr_core_lib/`
and runs `./build.sh --nips=all`; verify the static binary still builds and runs.
7. Record the upstream version pinned in this repo (e.g. a one-line
`nostr_core_lib/UPSTREAM_VERSION` file = `0.6.6`) so future syncs are auditable.
Exit criteria: didactyl builds and runs identically, but now links a `nostr_core_lib`
that exposes `nostr_signer_t` and the nsigner client. No nsec separation yet.
### Phase 2 — Signer provider in didactyl config + startup (local backend, still no separation)
Goal: introduce a `nostr_signer_t*` in didactyl constructed at startup, backed by
`local` mode by default. This is the seam; behavior is still identical.
#### 2a. Config schema
[`src/config.c`](../src/config.c) / [`src/config.h`](../src/config.h): add a `signer`
block (sibling of `keys`):
```jsonc
"signer": {
"mode": "local", // "local" | "nsigner_unix" | (future) "nsigner_tcp" | "nsigner_serial" | "nsigner_fds"
"socket_name": "", // nsigner_unix: abstract socket name (without @); empty = auto-discover single running signer
"role": "main", // n_signer role selector
"timeout_ms": 15000,
"auth_privkey_hex": "" // optional, for TCP auth envelope only
}
```
Default `mode = "local"`. Backward compatible: if `signer` block is absent, behave as
`local` using `keys.nsec`. Validation: in any `nsigner_*` mode, `keys.nsec` is optional
and ignored (the agent learns its pubkey from the signer); in `local` mode `keys.nsec`
remains required.
#### 2b. User-facing surfaces (how the operator chooses n_signer)
didactyl has three startup surfaces today; the n_signer choice is exposed on all three,
consistent with existing patterns:
**1. Interactive setup wizard** ([`src/setup_wizard.c`](../src/setup_wizard.c),
`new_agent_identity_step` at line ~2116). Today the Identity page offers:
`[g]enerate new keypair` / `[p]rovide existing nsec`. Add a third option:
- `[s]ign with a running n_signer (separate the nsec from the agent)`
When chosen, the wizard:
- Does **not** prompt for an nsec. Instead prompts for:
- socket name (default: auto-discover the single running signer),
- role (default `main`),
- timeout (default 15000ms).
- Performs a live `nostr_signer_nsigner_unix(...)` + `nostr_signer_get_public_key()`
connectivity check immediately, so the operator gets confirmation ("Connected to
n_signer @nsigner_hairy_dog; agent npub: npub1...") before proceeding.
- Writes `signer.mode = "nsigner_unix"` (plus socket_name/role/timeout) into the
generated genesis JSONC and **omits** `keys.nsec`.
- The existing `[p]rovide existing nsec` path stays as `local` mode (the default).
This keeps the trust model visible at the moment the operator commits to an identity:
either the nsec lives in the agent (`local`) or it does not (`nsigner_unix`).
**2. CLI flags + env** ([`src/main.c`](../src/main.c) `print_usage` at line ~141 and
arg parsing at line ~1233). Add:
- `--signer <mode>` — one of `local`, `nsigner_unix`, `nsigner_tcp`, `nsigner_serial`,
`nsigner_fds`. Overrides `signer.mode` in config.
- `--signer-socket <name>` — abstract socket name (nsigner_unix).
- `--signer-role <role>` — n_signer role selector (default `main`).
- `--signer-timeout <ms>` — per-call timeout (default 15000).
- `--signer-tcp <host:port>` — shorthand for `--signer nsigner_tcp` + host/port.
- `DIDACTYL_SIGNER` env — fallback for `--signer` (mirrors the `DIDACTYL_NSEC` pattern).
When `--signer nsigner_unix` (or `DIDACTYL_SIGNER=nsigner_unix`) is set, `--nsec` /
`DIDACTYL_NSEC` are not required and are ignored if present. This enables headless /
systemd deployment where the nsec never touches the agent's argv or environment.
Update `print_usage` examples to show the n_signer path, e.g.:
`%s --signer nsigner_unix --signer-socket nsigner_hairy_dog --admin npub1...`
**3. Genesis JSONC config** — the `signer` block in 2a is the canonical, persistent
form. The wizard writes it; CLI flags override it for a single run; env vars are the
last fallback. This matches how `keys.nsec` / `--nsec` / `DIDACTYL_NSEC` already layer.
Precedence (highest to lowest): CLI flag → env var → genesis `signer` block → default
`local`. Same precedence as the existing key/admin overrides.
#### 2c. Startup construction
[`src/main.c`](../src/main.c): after loading config + applying CLI/env overrides,
construct a single `nostr_signer_t* g_signer`:
- `local``nostr_signer_local(cfg->keys.private_key)`.
- `nsigner_unix``nostr_signer_nsigner_unix(socket_name, role, timeout_ms)`.
- (future) `nsigner_tcp` / `nsigner_serial` / `nsigner_fds` analogously.
Then derive the agent pubkey via `nostr_signer_get_public_key(g_signer, ...)` instead of
`nostr_ec_public_key_from_private_key(cfg->keys.private_key, ...)`. In `local` mode this
yields the same bytes; in remote mode it is the first n_signer round-trip and **doubles
as the mandatory startup connectivity check** (Phase 4): failure here is fatal and loud.
Hold `g_signer` alongside `g_cfg` / `g_pool` for the process lifetime; free on shutdown.
Exit criteria: didactyl runs with a `nostr_signer_t*` in `local` mode by default, and
the operator can choose `nsigner_unix` via wizard, CLI, or config. No call sites migrated
yet (Phase 3). This is a safe, reviewable checkpoint — in `local` mode behavior is
identical; in `nsigner_unix` mode the agent starts but signing still uses the local path
until Phase 3 lands (so Phase 2 remote mode is a connectivity proof, not full separation).
### Phase 3 — Migrate call sites to `*_with_signer` (enables real separation)
Goal: route every signing/encryption/AUTH operation through `g_signer`. In `local` mode
this is still output-equivalent; in `nsigner_unix` mode the nsec is no longer in the
agent process.
Migrate in this order (highest value / lowest risk first):
1. **Relay pool AUTH** — replace
`nostr_relay_pool_set_auth(g_pool, g_cfg->keys.private_key, 1)` with
`nostr_relay_pool_set_auth_with_signer(g_pool, g_signer, 1)`. This is the single
change that delegates the deep-event-loop AUTH signing.
2. **Event signing**`nostr_create_and_sign_event(...)`
`nostr_create_and_sign_event_with_signer(...)` at all sites (posts, kind 30078
config publish, startup events, etc.). Search: `nostr_create_and_sign_event` in
`src/`.
3. **NIP-44 encrypt/decrypt** — the DM/memory/task/config/block-list sites. These call
`nostr_nip44_encrypt/decrypt(cfg->keys.private_key, peer, ...)`. Replace with
`nostr_signer_nip44_encrypt/decrypt(g_signer, peer_hex, ...)`. Note the signer API
takes hex pubkeys and returns heap strings via `char**` out-params, so each call site
needs a small adaptation (hex-encode the peer key, free the out-string).
4. **NIP-04 encrypt/decrypt** — same pattern as NIP-44 for the legacy NIP-04 DM sites.
5. **NIP-17 gift wraps**`nostr_nip17_send_dm` / `nostr_nip17_receive_dm`
`*_with_signer`. (The seal is signed with the agent key via the signer; the gift-wrap
ephemeral key stays local — that is correct and does not leak the nsec.)
6. **NIP-60/61 cashu**`nostr_nip60_create_*_event` / `nostr_nip61_create_*_event`
`*_with_signer` in [`src/cashu_wallet.c`](../src/cashu_wallet.c).
7. **Blossom**`blossom_create_auth_header` / `blossom_upload` / `blossom_delete`
`*_with_signer` in [`src/tools/tool_blossom.c`](../src/tools/tool_blossom.c).
After each group, build + smoke test in `local` mode (output-equivalent) before
testing in `nsigner_unix` mode against a running `n_signer`.
Exit criteria: every signing/encryption/AUTH op flows through `g_signer`. With
`signer.mode = "nsigner_unix"`, the agent process holds no nsec.
### Phase 4 — Reliability & failure handling (critical, do before enabling remote by default)
The user's stated concern: if the agent loses signing ability, it cannot even DM its
admin about the failure. This must be addressed before remote mode is anything but
opt-in.
Design:
- **Startup connectivity check is mandatory.** `nostr_signer_get_public_key()` is called
at startup for every mode. In remote mode, failure here is fatal and loud (agent
refuses to start, prints a clear error). Better to fail to start than to start unable
to sign.
- **Runtime signing failure** — classify by error:
- `approval_denied` / `policy_denied` / `unknown_role` → not a transient error; surface
to agent log and admin context, do not retry blindly.
- transport/IO error (n_signer crashed, socket gone) → the nsigner transport has a
`reconnect` hook; the client retries once with reconnect, then returns an error.
- **Admin notification path.** Because DMs themselves require signing, a signing outage
is a catch-22 for "DM the admin". Mitigations, in order of preference:
1. **Health-gate before sending.** Before attempting an admin DM, do a cheap
`nostr_signer_get_public_key()` ping. If it fails, fall back to a **local,
keyless** notification channel: stderr/log + HTTP API health endpoint
([`src/http_api.c`](../src/http_api.c)) exposes a `signer_unhealthy` flag. The admin
monitors the HTTP health endpoint (or process supervisor) rather than relying on a
DM that requires the broken signer.
2. **Optional emergency local key.** A config-gated `signer.emergency_local_nsec`
used *only* to sign admin DMs when the remote signer is unreachable. This is a
deliberate policy tradeoff (it re-introduces a key in-process, scoped to admin
alerts only) and should be off by default. Document the tradeoff clearly.
3. **Process supervisor.** systemd/`didactyl` service restarts on signer health
failure; the supervisor's logs are the out-of-band channel.
- **Recommendation for v1:** ship (1) + (3). Leave (2) as a documented opt-in for
operators who prioritize alert delivery over strict key separation. This keeps the
default trust model clean while making the failure observable out-of-band.
Exit criteria: a signing outage is detectable out-of-band (HTTP health + logs +
supervisor), and the agent does not silently hang. Remote mode is still opt-in.
#### Phase 4 implementation status (items 1820) — COMPLETE
Items 18, 19, and 20 are implemented as follows. Behavior is backward compatible
and remote mode remains opt-in.
**Item 18 — Runtime signer health classification & tracking**
- New module [`src/signer_health.{h,c}`](../src/signer_health.h) holds a
process-global, mutex-protected health state: `unknown | healthy | unhealthy`,
the configured signer mode snapshot, the last error reason string, and the
last error / last ok unix timestamps.
- [`src/main.c`](../src/main.c) `construct_signer()` records the mode at startup
and records `ok` on a successful connectivity check (`get_public_key`) or
`failure` (with the nostr error code) on construction/connectivity failure.
The fatal+loud startup behavior is preserved; error messages now explicitly
include `mode=`, `socket=`, `role=`, `timeout_ms=`, and `rc=` so the operator
knows exactly which signer context failed.
- The migrated signer call paths in [`src/nostr_handler.c`](../src/nostr_handler.c)
(NIP-44 self encrypt/decrypt, NIP-04 incoming DM decrypt, NIP-04 outgoing DM
encrypt) call `signer_health_record_ok()` on success and
`signer_health_record_failure(rc, "<verb>")` on failure. Classification maps
nostr error codes to short labels: `transport/IO` (IO/network), `crypto/auth`,
`resource`, `invalid-input`, `unknown`. This is deliberately minimal — no broad
rewrite of the tool/agent/cashu/block-list signer sites; the central DM and
self-config paths are instrumented, which is where an outage first surfaces.
**Item 19 — Out-of-band health surface (HTTP + logs + supervisor)**
- [`src/http_api.c`](../src/http_api.c) `handle_status()` (the `GET /api/status`
endpoint) now adds the following fields to the JSON response:
- `signer_mode` — the configured signer mode (`local` / `nsigner_unix` / `nsigner_tcp`).
- `signer_healthy``"true"` / `"false"` / `"unknown"`.
- `signer_health_state``healthy` / `unhealthy` / `unknown`.
- `signer_last_error` — human-readable `<classification>: <detail> (rc=<n>)`, or `""`.
- `signer_last_error_ts` — unix timestamp of the last unhealthy transition, or `null`.
- `signer_last_ok_ts` — unix timestamp of the last healthy observation, or `null`.
An operator (or supervisor / monitoring agent) can poll `/api/status` to detect a
signing outage without requiring a signed admin DM to come back.
- `signer_health_record_failure()` and `signer_health_record_ok()` each emit a
one-line stderr warning on a health **transition** (healthy -> unhealthy, or
unhealthy -> healthy), including the mode and reason. Repeated failures within
the same unhealthy state do not spam the log.
**Item 20 — Optional `emergency_local_nsec` (admin-DM delivery tradeoff)**
- New config field `signer.emergency_local_nsec` (string, empty default) in
[`src/config.h`](../src/config.h) `signer_config_t`, parsed in
[`src/config.c`](../src/config.c) `parse_signer_config()`.
- **No active fallback behavior is wired yet.** The field is parsed, stored, and
documented only — a feature-flag/placeholder so operators can pre-stage the
value. The actual "sign a minimal admin-alert DM with the emergency key when
the remote signer is unreachable" path is deferred until the Phase 4 health
surface (item 19) is proven in production.
- **Tradeoff (documented here and in the config header comment):** off by default.
When eventually enabled, it reintroduces the nsec into the agent process
*only* for admin-alert fallback DMs. This is a deliberate operator-accepted
tradeoff: better to leak the nsec briefly to notify the admin than to fail
silently. Operators who prioritize strict key separation leave it empty and
rely on the HTTP health endpoint + supervisor logs (item 19) as the
out-of-band alert channel.
**Validation**
- `make clean && make` builds cleanly with the new `signer_health.c` source.
- `./didactyl --help` and `./didactyl --version` unchanged in surface.
- `GET /api/status` in local mode returns the new `signer_mode` / `signer_healthy`
/ `signer_health_state` / `signer_last_error` / `signer_last_error_ts` /
`signer_last_ok_ts` fields (local mode reports `signer_healthy=true` after the
startup connectivity check).
### Phase 5 (deferred) — Embedded n_signer spawn
Goal: one self-contained didactyl binary that spawns an n_signer in a separate window
at startup, for operators who want key separation without running a second process
manually.
Deferred because of the reliability concern above and because it couples didactyl's
process model to n_signer's TUI/terminal-attached trust model. Revisit after Phase 4's
health/observability story is proven in production with an external n_signer.
Sketch (not for this round): didactyl forks `n_signer --mnemonic-fd N --socket-name <pinned>`
in a new terminal (xterm/foot/etc.), passes the mnemonic over a pipe fd, pins the
abstract socket name, and constructs `nostr_signer_nsigner_unix(<pinned name>, ...)`.
The pinned socket name avoids discovery races. The trust anchor is still the
terminal-attached n_signer process; didactyl is just a supervised spawner.
---
## Open decisions (resolved)
1. **Where does the abstraction live?** Inside `nostr_core_lib`. It is the single
chokepoint, it solves the relay-AUTH blocker, and it is reusable. ✓ (already done
upstream)
2. **How is the n_signer client code sourced into nostr_core_lib?** Already decided
upstream: the client (framing + auth envelope + transports) lives in
`nostr_core_lib` itself, guarded by `NOSTR_ENABLE_NSIGNER_CLIENT`. No vendoring of
n_signer's repo into nostr_core_lib; n_signer keeps depending on nostr_core_lib for
leaf crypto. ✓
3. **Runtime failure handling.** See Phase 4: out-of-band health (HTTP + logs +
supervisor) by default; optional emergency-local-nsec as documented opt-in. ✓
---
## Risks & notes
- **NIP set in `Makefile` vs `build.sh --nips=all` in Dockerfile.** Both must include
the NIPs didactyl uses. The signer core (`nostr_signer.c`, `nsigner_*.c`) is compiled
unconditionally by upstream `build.sh`, so the nsigner client is available in both
build paths. Verify after sync.
- **Static link footprint.** nsigner client + transports add a small amount of object
code (unix/tcp/serial/fd transports). Negligible vs. the existing websocket/curl/openssl
surface. Serial transport pulls in `<termios.h>` — already POSIX, fine for musl.
- **Output equivalence.** Upstream's local backend is asserted equivalent by
`test_event_creation_equivalence_with_signer`. Phase 1 smoke test should still
verify a known event signs to the same id as before.
- **`cfg->keys.private_key` lifetime.** In remote mode this buffer is zeroed/unused.
Keep the field for `local` mode and for the optional emergency key; do not remove it.
- **Hex pubkey plumbing.** The signer's encrypt/decrypt verbs take hex pubkeys and
return heap strings. Several didactyl sites currently pass raw 32-byte keys. Each
migrated site needs a small hex-encode + free adaptation. Mechanical but touches
many files — Phase 3 step 3/4 is the bulk of the work.

View File

@@ -0,0 +1,58 @@
# Remove Dead DM-History Helper Functions in `agent.c`
## Background
While investigating how Didactyl maintains continuity across a DM "chat session", two functions in [`src/agent.c`](../src/agent.c) were found to be compiled-but-unreferenced, marked with `__attribute__((unused))` to suppress compiler warnings:
- [`append_recent_admin_dm_history`](../src/agent.c:1065)
- [`build_recent_admin_dm_history_messages`](../src/agent.c:1800) (wraps the above)
These were part of an older design where the agent automatically injected the last N admin DM turns into every LLM call. The current architecture is **skill-driven**: DM history only reaches the LLM when an adopted, triggered skill explicitly pulls it in via the `{{dm_history}}` / `{{nostr_dm_history(...)}}` template variables or the `nostr_dm_history` tool (see [`tool_agent.c`](../src/tools/tool_agent.c:284) and [`tools_schema.c`](../src/tools/tools_schema.c:1606)). The dead functions are now a source of confusion for anyone reading the code to understand chat-session behavior.
## Goal
Remove the dead functions and any symbols used exclusively by them, without changing runtime behavior.
## Scope Analysis (verified before planning)
A repo-wide search for each symbol confirmed the following:
| Symbol | Only callers | Disposition |
|---|---|---|
| [`append_recent_admin_dm_history`](../src/agent.c:1065) | called by `build_recent_admin_dm_history_messages` (also dead) | **delete** |
| [`build_recent_admin_dm_history_messages`](../src/agent.c:1800) | no callers | **delete** |
| [`AGENT_HISTORY_TURNS`](../src/agent.c:38) | referenced only inside the dead `append_recent_admin_dm_history` | **delete** |
| [`AGENT_HISTORY_QUERY_LIMIT`](../src/agent.c:39) | defined but zero references repo-wide | **delete** |
| [`append_simple_message`](../src/agent.c:187) | many live callers throughout `agent.c` | **keep** |
| [`nostr_handler_get_dm_history_json`](../src/nostr_handler.c:4384) | live via [`tool_agent.c`](../src/tools/tool_agent.c:318) | **keep** |
No non-source references (Makefile, tests, docs) depend on these symbols.
## Risks
Very low. Both functions carry `__attribute__((unused))` so they are not linked into any runtime path. The only failure modes are accidental deletion of something still live, which the scope analysis above rules out.
## Verification Strategy
1. Clean build with `make` — must succeed with no new warnings.
2. Existing tests under [`tests/`](../tests/) pass (`python tests/run_tests.py` or the project's usual invocation).
3. Manual sanity check: start an agent, send a DM, confirm normal reply — no regression, since the deleted code was never on the hot path.
## Mermaid: before/after
```mermaid
flowchart LR
subgraph Before
A1[agent.c dead funcs] -. unused attr .- B1[compiler silences warning]
A1 --> C1[reader assumes auto DM history replay]
C1 --> D1[confusion about session behavior]
end
subgraph After
A2[agent.c clean] --> E2[skill-driven history only]
E2 --> F2[intent matches code]
end
```
## Follow-on (out of scope for this change)
The documentation in [`docs/CONTEXT.md`](../docs/CONTEXT.md) already describes the skill-driven assembly model correctly, but neither that file nor [`docs/SKILLS.md`](../docs/SKILLS.md) explicitly states "DM history is not automatic — it only appears when a skill references it." A brief clarifying paragraph could be added in a separate change.

View File

@@ -0,0 +1,285 @@
# Startup Failure Admin DM Notification
> **STATUS UPDATE (follow-up phase):** The base feature (send a failure DM) is
> implemented and verified on VM410. However, because the failure happens inside the
> systemd `Restart=on-failure` loop (`RestartSec=10`), the admin now receives a *new*
> failure DM roughly every ~25 seconds, indefinitely (observed in the live message box).
> This follow-up adds **throttling/de-duplication** so the failure DM is sent **once per
> failure type until the next successful startup**, and makes the message **more
> descriptive** (per-relay connect state + the event kinds that were needed).
> See the "Follow-up: Throttling + Descriptive Failure DM" section at the end.
# Startup Failure Admin DM Notification (original plan)
## Goal
When the agent fails to start, send a best-effort encrypted DM to the administrator
describing which startup step failed and why, so the operator learns about the failure
without having to SSH in and read `journalctl`.
This directly addresses the real-world incident on VM410 where both `didactyl.service`
and `simon.service` were stuck restart-looping at startup step 14
(`Subscribe self-skill cache: failed (no skill events found after EOSE)`) and silently
stopped answering DMs.
## Background / Code References
- Startup is a linear checklist in [`main()`](src/main.c:1012). Each step uses helpers:
- [`startup_step_begin()`](src/main.c:303)
- [`startup_step_ok()`](src/main.c:309)
- [`startup_step_fail()`](src/main.c:320)
- On any fatal failure, the current pattern is:
`startup_step_fail(...)` -> `fprintf(stderr, ...)` -> cleanup calls -> `return 1;`
(e.g. the step-14 self-skill abort at [`src/main.c:1520`](src/main.c:1520)).
- The success path already sends an admin "started up" DM at
[`src/main.c:1663`](src/main.c:1663) via
[`nostr_handler_send_dm_auto()`](src/nostr_handler.c:3264).
- DM delivery requires (see [`nostr_handler_send_dm_with_role()`](src/nostr_handler.c:3133)):
- `g_cfg` and `g_pool` set (relay pool initialized),
- at least one **connected** relay (otherwise the kind-4 event is dropped:
"kind 4 event not queued: no connected relays" at [`src/nostr_handler.c:3203`](src/nostr_handler.c:3203)),
- a valid `cfg.admin.pubkey` (validated at step 4, [`src/main.c:1310`](src/main.c:1310)),
- the private key derived (always done before the checklist).
### Delivery-window reality
A failure DM is only *deliverable* from roughly step 11 onward (relay pool created +
relays connected + admin known). The step-14 failure we actually hit is inside that
window, so it will be delivered. Earlier failures (bad nsec, missing admin, LLM config,
no relay connection) have no working channel; per decision, those are **logged only**
(best-effort, no blocking retries).
## Design Decision (confirmed)
**Best-effort only.** Attempt the failure DM whenever relays + admin are available; if
the relay pool isn't connected or admin pubkey is unknown, skip the DM and rely on
existing stderr/journal logging. No blocking retry loop, no self-healing of the
underlying failure (that can be a separate plan).
## Approach
Add a single helper that builds and sends the failure DM, then call it from every fatal
startup-abort site (the points that currently do `startup_step_fail(...) ... return 1;`).
### 1. New helper in [`src/main.c`](src/main.c)
Add a static function near the other startup helpers (after
[`startup_step_fail()`](src/main.c:320)):
```c
static void notify_admin_startup_failure(const didactyl_config_t* cfg,
int step,
const char* label,
const char* detail);
```
Behavior:
- Guard clauses (skip + DEBUG_WARN if any precondition is missing):
- `cfg == NULL` or `cfg->admin.pubkey[0] == '\0'` -> log "admin unknown; cannot notify".
- `nostr_handler_connected_relay_count() <= 0` -> log "no connected relay; cannot notify".
- Build a concise human-readable message, e.g.:
```
<DisplayName> FAILED to start at <YYYY-MM-DD HH:MM:SS>.
Startup step [14] Subscribe self-skill cache failed: no skill events found after EOSE.
Version <X>. Connected relays: <n>/<m>. The agent is NOT online and will not answer DMs until fixed.
```
- Reuse `nostr_handler_get_startup_display_name()` and `DIDACTYL_VERSION` exactly like
the success DM at [`src/main.c:1645`](src/main.c:1645) for naming/version consistency.
- Include `step`, `label`, and `detail` so each failure site is self-describing.
- Send via `nostr_handler_send_dm_auto(cfg->admin.pubkey, msg)`; if it returns non-zero,
`DEBUG_WARN` that the failure DM could not be delivered (do not change the exit code).
- Pump the poll loop briefly after sending so the async publish can flush before process
exit: call `nostr_handler_poll(...)` a few times (e.g. ~300--500 ms total) so the
queued kind-4 event is actually written to the relay sockets before cleanup/`return 1`.
(Without this, async publish may be discarded on immediate exit.)
### 2. Wire the helper into fatal abort sites
For each fatal `startup_step_fail(...)` that ends in `return 1;`, insert a call to
`notify_admin_startup_failure(&cfg, <step>, "<label>", "<detail>")` immediately after the
`startup_step_fail(...)` line and before the cleanup/`return 1`.
Priority sites (inside the deliverable window — relay pool up + admin known):
- Step 11 — discover self relay list failures
([`src/main.c:1420`](src/main.c:1420), [`src/main.c:1437`](src/main.c:1437)).
- Step 14 — self-skill cache failures (the incident we hit):
- subscribe failed ([`src/main.c:1481`](src/main.c:1481)),
- EOSE timeout ([`src/main.c:1496`](src/main.c:1496)),
- no skill events after EOSE ([`src/main.c:1521`](src/main.c:1521)).
- Step 15 — Subscribe DMs failed ([`src/main.c:1552`](src/main.c:1552)).
Earlier-window sites (relay/admin may not be ready — helper will self-skip and just log,
but we still call it uniformly for completeness):
- Step 1/3/4/5/6/7/8/9 fatal aborts. The helper's guard clauses make these safe no-ops
when delivery isn't possible.
Keep the existing `fprintf(stderr, ...)` and cleanup unchanged; the DM is purely additive
and must never alter the exit code or cleanup ordering.
### 3. Message size / safety
- Use a fixed stack buffer (e.g. `char msg[768];`) like the success DM at
[`src/main.c:1644`](src/main.c:1644).
- `snprintf` with truncation is acceptable; `detail` strings are short and controlled.
## Out of Scope
- No blocking retry / wait-for-relay loop (explicitly declined).
- No auto-remediation of the step-14 self-skill cause (e.g. auto-publishing the default
skill). Tracked separately if desired.
- No change to `deploy_lt.sh` post-deploy health checks (could be a follow-up: have the
deploy script verify each service reaches `READY` after restart).
## Verification
1. Build the static binary (`build_static.sh`) and confirm no warnings.
2. Local reproduction of step-14 failure: run an `--nsec`-only agent for an identity that
has connected relays but **no** published skill events, confirm:
- startup still aborts with exit code 1 (unchanged behavior),
- the admin receives a DM naming step 14 and the "no skill events found after EOSE"
detail.
3. Negative case: kill relay connectivity (or use an unreachable relay) and confirm the
helper logs "no connected relay; cannot notify" and does not crash or hang.
4. Confirm the success-path startup DM at [`src/main.c:1663`](src/main.c:1663) is
unaffected.
5. Deploy to VM410, restart `didactyl.service` / `simon.service`, and confirm the admin
npub receives the failure DM while the skill events are still missing; then publish a
skill and confirm normal `READY` + startup DM resumes.
---
# Follow-up: Throttling + Descriptive Failure DM
## Problems observed in production
1. **DM flood.** With `Restart=on-failure` / `RestartSec=10`, the step-14 failure recurs
on every restart and the agent reaches the deliverable window each time, so the admin
gets a fresh failure DM every ~25s indefinitely (confirmed in the live message box).
2. **Insufficient detail.** The current message names the step + detail, but not which
relays were attempted, whether each connected, nor which event kinds were required.
## Decisions (confirmed with user)
- **Throttle semantics:** send exactly once per failure type (keyed by step) until the
agent next starts successfully. The marker is cleared on `READY`. No periodic
reminders. A different failing step is a different "type" and notifies once.
- **Descriptive content:** include the attempted relay list with per-relay connect state,
and the event kinds that step 14 needs (31123 / 31124 skill events; 10123 adoption list).
## Part A -- Throttle / de-duplicate via on-disk marker
### Marker file location (systemd-sandbox safe)
- The unit runs with `WorkingDirectory=/home/<user>` and (hardened variant)
`ReadWritePaths=/home/<user>`, so only the agent home is writable.
- `cfg.tools.shell.working_directory` defaults to `"."` (see
[`config.c`](src/config.c:1459)), which resolves to the home dir at runtime.
- Use a hidden marker in the working directory: `./.didactyl_startup_failure`.
- For `didactyl` -> `/home/didactyl/.didactyl_startup_failure`
- For `simon` -> `/home/simon/.didactyl_startup_failure`
- Both inside the writable `ReadWritePaths`, so writes succeed under the sandbox.
- Resolve the directory the same way the local-file tools do: prefer
`cfg->tools.shell.working_directory` when non-empty, else `"."`
(mirror [`tool_local.c`](src/tools/tool_local.c:49)).
### Marker contents
Plain text, one record, easy to parse and inspect manually:
- `step=14`
- `label=Subscribe self-skill cache`
- `detail=no skill events found after EOSE`
- `last_sent_epoch=1781314692`
(Only `step` is strictly needed for the de-dup key; the rest aids debugging.)
### New helpers in [`src/main.c`](src/main.c)
Add small static helpers near
[`notify_admin_startup_failure()`](src/main.c:331):
- `startup_failure_marker_path(cfg, out, out_size)` -- builds
`<workdir>/.didactyl_startup_failure`.
- `startup_failure_already_notified(cfg, step)` -- returns 1 if the marker exists AND its
`step=` matches the current `step` (suppress); 0 otherwise (allow). Missing/unreadable
marker -> 0 (allow).
- `startup_failure_marker_write(cfg, step, label, detail)` -- writes/overwrites the marker
after an attempted send.
- `startup_failure_marker_clear(cfg)` -- `remove()` the marker; ignore ENOENT.
### Wiring
- In [`notify_admin_startup_failure()`](src/main.c:331): after the existing guard
clauses (config/admin/relay), check `startup_failure_already_notified(cfg, step)`.
If it returns 1, log a DEBUG_INFO suppression line and return without sending.
- On a successful send, call `startup_failure_marker_write(cfg, step, label, detail)`.
- If the same step keeps failing, only the first restart in the episode sends a DM;
subsequent restarts find the matching marker and stay silent.
- If a different step fails later, the `step=` mismatch allows exactly one new DM and
rewrites the marker with the new step.
- On the success path, clear the marker so the next failure episode notifies again. Add
`startup_failure_marker_clear(&cfg);` next to the READY success DM at
[`src/main.c:1663`](src/main.c:1663).
### Edge cases
- Marker write failure (e.g. read-only FS): log DEBUG_WARN and continue. Worst case we
fall back to current behavior (may re-send on next restart) -- acceptable, never fatal.
- Two services share the binary but use different home dirs, so markers never collide.
## Part B -- Descriptive failure message
Enhance the message built in
[`notify_admin_startup_failure()`](src/main.c:331) to append:
1. **Attempted relays + per-relay state.** Add a compact accessor to the nostr handler:
- New `nostr_handler_relay_state_summary(void)` in
[`nostr_handler.c`](src/nostr_handler.c) / [`nostr_handler.h`](src/nostr_handler.h)
returning a caller-freed compact string like
`relay.laantungir.net=connected; relay.damus.io=connected; relay.primal.net=connecting`.
- Implement by reusing the existing loop over `g_cfg->relays[]` +
`nostr_relay_pool_get_relay_status()` + `relay_status_str()` (patterns at
[`src/nostr_handler.c:3183`](src/nostr_handler.c:3183) and
[`src/nostr_handler.c:419`](src/nostr_handler.c:419)).
- Preferred over embedding raw JSON from
[`nostr_handler_relay_status_json()`](src/nostr_handler.c:3971) to keep the DM short.
2. **Needed event kinds (step-specific).** For step 14 append a fixed clause naming the
required events: kind 31123/31124 (skills) and kind 10123 (adoption list). Implement as
a small `startup_step_needed_events(step)` lookup in [`src/main.c`](src/main.c) that
returns a clause for known steps (14, 11, ...) and empty for others.
### Resulting message shape (example)
- `Didactyl FAILED to start at 2026-06-13 10:38:13.`
- `Startup step [14] Subscribe self-skill cache failed: no skill events found after EOSE.`
- `Version v0.2.48. Connected relays: 3/3.`
- `Relays: relay.laantungir.net=connected; relay.damus.io=connected; relay.primal.net=connected.`
- `Needed events: kind 31123/31124 (skills) and kind 10123 (adoption list) for this agent's pubkey.`
- `The agent is NOT online and will not answer DMs until fixed.`
Keep within the existing `failure_dm` buffer (bump to ~1536 if needed); `snprintf`
truncation remains safe.
## Implementation order
1. Add `nostr_handler_relay_state_summary()` to handler `.c`/`.h`.
2. Add marker helpers + `startup_step_needed_events()` to [`src/main.c`](src/main.c).
3. Update [`notify_admin_startup_failure()`](src/main.c:331): de-dup check, richer
message, marker write on send.
4. Add `startup_failure_marker_clear(&cfg)` on the READY success path
([`src/main.c:1663`](src/main.c:1663)).
5. Build (`make`), then `build_static.sh`, deploy, verify.
## Verification (follow-up)
1. **Throttle:** reproduce step-14 failure; confirm exactly one DM on the first failing
restart and no further DMs across subsequent restart-loop iterations (journal shows a
suppression line).
2. **Clear-on-success:** publish a skill so startup reaches `READY`; confirm marker is
removed and the normal startup DM is sent.
3. **Re-arm:** break startup again and confirm a single new DM is delivered.
4. **Descriptive content:** confirm the DM includes the per-relay state line and the
needed-events clause.
5. **Sandbox write:** on VM410 confirm the marker is created at
`/home/didactyl/.didactyl_startup_failure` (and `/home/simon/...`) without permission
errors under the systemd sandbox.

1
schemas.json Normal file

File diff suppressed because one or more lines are too long

View File

@@ -35,8 +35,6 @@ static pthread_mutex_t g_context_part_names_mutex = PTHREAD_MUTEX_INITIALIZER;
#define AGENT_DEBOUNCE_WINDOW_SECONDS 5
#define AGENT_DEBOUNCE_CACHE_SIZE 256
#define AGENT_HISTORY_TURNS 12
#define AGENT_HISTORY_QUERY_LIMIT 200
#define AGENT_ADOPTED_SKILLS_CACHE_TTL_SECONDS 300
#define AGENT_ADOPTED_SKILLS_MAX 24
#define AGENT_ADOPTED_SKILL_CONTENT_MAX_CHARS 1800
@@ -681,7 +679,21 @@ static char* build_slash_help_all_json(void) {
int adopted_count = 0;
if (adoption_events && cJSON_IsArray(adoption_events) && cJSON_GetArraySize(adoption_events) > 0) {
cJSON* ev0 = cJSON_GetArrayItem(adoption_events, 0);
cJSON* ev0 = NULL;
double best_created = -1.0;
int an = cJSON_GetArraySize(adoption_events);
for (int ai = 0; ai < an; ai++) {
cJSON* ev = cJSON_GetArrayItem(adoption_events, ai);
if (!ev || !cJSON_IsObject(ev)) {
continue;
}
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(ev, "created_at");
double created = (created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0.0;
if (!ev0 || created > best_created) {
ev0 = ev;
best_created = created;
}
}
cJSON* tags = ev0 ? cJSON_GetObjectItemCaseSensitive(ev0, "tags") : NULL;
if (tags && cJSON_IsArray(tags)) {
int tn = cJSON_GetArraySize(tags);
@@ -1048,73 +1060,6 @@ static __attribute__((unused)) char* build_sender_verification_text(didactyl_sen
}
static __attribute__((unused)) int append_recent_admin_dm_history(cJSON* messages, const char* current_message) {
if (!messages || !g_cfg) {
return -1;
}
char* history_json = nostr_handler_get_dm_history_json(g_cfg->admin.pubkey, AGENT_HISTORY_TURNS);
if (!history_json) {
return 0;
}
cJSON* items = cJSON_Parse(history_json);
free(history_json);
if (!items || !cJSON_IsArray(items)) {
cJSON_Delete(items);
return 0;
}
const char* last_appended_role = NULL;
const char* last_appended_content = NULL;
int n = cJSON_GetArraySize(items);
for (int i = 0; i < n; i++) {
cJSON* item = cJSON_GetArrayItem(items, i);
cJSON* role = item ? cJSON_GetObjectItemCaseSensitive(item, "role") : NULL;
cJSON* content = item ? cJSON_GetObjectItemCaseSensitive(item, "content") : NULL;
cJSON* created_at = item ? cJSON_GetObjectItemCaseSensitive(item, "created_at") : NULL;
if (!role || !content || !cJSON_IsString(role) || !cJSON_IsString(content) ||
!role->valuestring || !content->valuestring) {
continue;
}
const char* role_s = role->valuestring;
const char* content_s = content->valuestring;
int role_is_user = (strcmp(role_s, "user") == 0);
if (!role_is_user && strcmp(role_s, "assistant") != 0) {
continue;
}
if (i == n - 1 && role_is_user && current_message && strcmp(content_s, current_message) == 0) {
continue;
}
if (last_appended_role && last_appended_content &&
strcmp(last_appended_role, role_s) == 0 &&
strcmp(last_appended_content, content_s) == 0) {
continue;
}
if (append_simple_message(messages, role_s, content_s) != 0) {
cJSON_Delete(items);
return -1;
}
cJSON* appended = cJSON_GetArrayItem(messages, cJSON_GetArraySize(messages) - 1);
if (appended && cJSON_IsObject(appended) && created_at && cJSON_IsNumber(created_at)) {
cJSON_AddNumberToObject(appended, "_ts", created_at->valuedouble);
}
last_appended_role = role_s;
last_appended_content = content_s;
}
cJSON_Delete(items);
return 0;
}
static cJSON* find_tag_value_string_local(cJSON* tags, const char* key) {
if (!tags || !key || !cJSON_IsArray(tags)) {
return NULL;
@@ -1449,7 +1394,29 @@ static int refresh_adopted_skills_cache_if_needed(void) {
free(adoption_json);
if (adoption_events && cJSON_IsArray(adoption_events) && cJSON_GetArraySize(adoption_events) > 0) {
cJSON* list_event = cJSON_GetArrayItem(adoption_events, 0);
cJSON* list_event = NULL;
double list_event_created_at = -1.0;
int adoption_n = cJSON_GetArraySize(adoption_events);
for (int ai = 0; ai < adoption_n; ai++) {
cJSON* ev = cJSON_GetArrayItem(adoption_events, ai);
if (!ev || !cJSON_IsObject(ev)) {
continue;
}
cJSON* ev_pubkey = cJSON_GetObjectItemCaseSensitive(ev, "pubkey");
if (!ev_pubkey || !cJSON_IsString(ev_pubkey) || !ev_pubkey->valuestring ||
strcmp(ev_pubkey->valuestring, g_cfg->keys.public_key_hex) != 0) {
continue;
}
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(ev, "created_at");
double created = (created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0.0;
if (!list_event || created > list_event_created_at) {
list_event = ev;
list_event_created_at = created;
}
}
cJSON* list_tags = list_event ? cJSON_GetObjectItemCaseSensitive(list_event, "tags") : NULL;
if (list_tags && cJSON_IsArray(list_tags)) {
@@ -1761,16 +1728,8 @@ static __attribute__((unused)) int append_adopted_skills_context(cJSON* messages
return rc;
}
static __attribute__((unused)) cJSON* build_recent_admin_dm_history_messages(const char* current_message) {
cJSON* messages = cJSON_CreateArray();
if (!messages) {
return NULL;
}
if (append_recent_admin_dm_history(messages, current_message) != 0) {
cJSON_Delete(messages);
return NULL;
}
return messages;
void agent_set_signer(nostr_signer_t* signer) {
tools_set_signer(&g_tools_ctx, signer);
}
int agent_init(didactyl_config_t* config) {
@@ -2182,9 +2141,11 @@ void agent_on_message(const char* sender_pubkey_hex,
int max_turns = g_cfg->tools.max_turns > 0 ? g_cfg->tools.max_turns : 40;
int stall_repeat_threshold = g_cfg->tools.stall_repeat_threshold > 1 ? g_cfg->tools.stall_repeat_threshold : 3;
int max_context_bytes = g_cfg->tools.max_context_bytes >= 4096 ? g_cfg->tools.max_context_bytes : (128 * 1024);
uint64_t last_tool_fp = 0;
int repeated_tool_turns = 0;
int exited_on_stall = 0;
int exited_on_context_limit = 0;
int stall_due_to_length = 0;
char* final_answer_owned = NULL;
int turns_run = 0;
@@ -2196,6 +2157,17 @@ void agent_on_message(const char* sender_pubkey_hex,
break;
}
size_t messages_json_len = strlen(messages_json);
if ((int)messages_json_len > max_context_bytes) {
DEBUG_WARN("[didactyl] DM tool loop context limit exceeded: bytes=%zu max_context_bytes=%d turn=%d",
messages_json_len,
max_context_bytes,
turns_run);
exited_on_context_limit = 1;
free(messages_json);
break;
}
llm_response_t resp;
int rc = llm_chat_with_tools_messages(messages_json, tools_json, "auto", &resp);
free(messages_json);
@@ -2275,28 +2247,35 @@ void agent_on_message(const char* sender_pubkey_hex,
llm_response_free(&resp);
}
if (!final_answer_owned) {
if (!final_answer_owned && !exited_on_context_limit) {
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);
size_t messages_json_len = strlen(messages_json);
if ((int)messages_json_len <= max_context_bytes) {
llm_response_t final_resp;
int final_rc = llm_chat_with_tools_messages(messages_json, tools_json, "none", &final_resp);
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);
}
llm_response_free(&final_resp);
} else {
exited_on_context_limit = 1;
}
free(messages_json);
}
}
int exhausted_on_max_turns = (!final_answer_owned && !exited_on_stall && turns_run >= max_turns);
int exhausted_on_max_turns = (!final_answer_owned && !exited_on_stall && !exited_on_context_limit && 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 reached the tool-turn limit before getting a final response from the model.");
final_answer_owned = strdup(exited_on_context_limit
? "I paused because the working context became too large while using tools. Please narrow the scope and ask me to continue from a smaller context."
: (exited_on_stall
? "I stopped repeated tool calls after detecting a loop and could not produce a final summary."
: "I reached the tool-turn limit before getting a final response from the model."));
}
if (exhausted_on_max_turns) {
@@ -2313,17 +2292,25 @@ void agent_on_message(const char* sender_pubkey_hex,
const char* final_answer = final_answer_owned ? final_answer_owned : "I reached the tool-turn limit before getting a final response from the model.";
if (exited_on_stall || exhausted_on_max_turns) {
if (exited_on_stall || exhausted_on_max_turns || exited_on_context_limit) {
notify_admin_limit_diagnostic("dm_agent_loop",
exited_on_stall ? "stall_repetition_detected" : "max_turns_exhausted",
exited_on_context_limit
? "max_context_bytes_exceeded"
: (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,
exited_on_context_limit
? "tool_context_growth"
: ((exited_on_stall && stall_due_to_length) ? "max_tokens_truncation" : NULL),
exited_on_context_limit
? "Reduce tool-loop breadth or lower max_turns; context exceeded max_context_bytes."
: ((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",

View File

@@ -9,6 +9,10 @@
struct trigger_manager;
int agent_init(didactyl_config_t* config);
/* Wire a process-lifetime signer handle (non-owning) into the agent's tools
* context so NIP-04/44 encrypt/decrypt tool call sites route through the
* signer. Must be called after agent_init. Caller retains ownership. */
void agent_set_signer(nostr_signer_t* signer);
void agent_set_trigger_manager(struct trigger_manager* trigger_manager);
void agent_on_trigger(const char* skill_d_tag,
const char* skill_content,

View File

@@ -19,6 +19,13 @@
#define CASHU_WALLET_QUERY_TIMEOUT_MS 6000
#define CASHU_WALLET_MAX_SPLIT_PARTS 64
/* Optional process-lifetime signer for NIP-60/NIP-61 cashu event creation.
* Owned by main.c; non-owning here. When present, event creation is routed
* through the *_with_signer variants so the raw private key stays out of the
* agent process in remote-signer modes. When NULL, the legacy raw-key path is
* used (local-mode compatibility fallback). */
static nostr_signer_t* g_cashu_signer = NULL;
typedef struct {
char event_id[65];
nostr_nip60_token_data_t token;
@@ -121,7 +128,12 @@ static int publish_from_signed_event_template(cJSON* ev_template, char out_event
}
static int publish_wallet_event_and_store_locked(const nostr_nip60_wallet_data_t* wallet_data, char out_event_id[65]) {
cJSON* ev = nostr_nip60_create_wallet_event(wallet_data, g_wallet.cfg->keys.private_key, time(NULL));
cJSON* ev = NULL;
if (g_cashu_signer) {
ev = nostr_nip60_create_wallet_event_with_signer(wallet_data, g_cashu_signer, time(NULL));
} else {
ev = nostr_nip60_create_wallet_event(wallet_data, g_wallet.cfg->keys.private_key, time(NULL));
}
if (!ev) return -1;
int rc = publish_from_signed_event_template(ev, out_event_id);
@@ -156,7 +168,12 @@ static int publish_wallet_event_and_store_locked(const nostr_nip60_wallet_data_t
static int publish_token_event_and_store_locked(nostr_nip60_token_data_t* token_data, char out_event_id[65]) {
if (!token_data) return -1;
cJSON* ev = nostr_nip60_create_token_event(token_data, g_wallet.cfg->keys.private_key, time(NULL));
cJSON* ev = NULL;
if (g_cashu_signer) {
ev = nostr_nip60_create_token_event_with_signer(token_data, g_cashu_signer, time(NULL));
} else {
ev = nostr_nip60_create_token_event(token_data, g_wallet.cfg->keys.private_key, time(NULL));
}
if (!ev) return -1;
char event_id[65] = {0};
@@ -194,7 +211,12 @@ static int publish_history_event(nostr_nip60_direction_t direction,
history.refs = &ref;
history.ref_count = (ref.event_id[0] != '\0') ? 1 : 0;
cJSON* ev = nostr_nip60_create_history_event(&history, g_wallet.cfg->keys.private_key, time(NULL));
cJSON* ev = NULL;
if (g_cashu_signer) {
ev = nostr_nip60_create_history_event_with_signer(&history, g_cashu_signer, time(NULL));
} else {
ev = nostr_nip60_create_history_event(&history, g_wallet.cfg->keys.private_key, time(NULL));
}
if (!ev) return -1;
int rc = publish_from_signed_event_template(ev, NULL);
@@ -203,7 +225,12 @@ static int publish_history_event(nostr_nip60_direction_t direction,
}
static int publish_token_deletion_event(const char* event_id) {
cJSON* del = nostr_nip60_create_token_deletion(event_id, g_wallet.cfg->keys.private_key, time(NULL));
cJSON* del = NULL;
if (g_cashu_signer) {
del = nostr_nip60_create_token_deletion_with_signer(event_id, g_cashu_signer, time(NULL));
} else {
del = nostr_nip60_create_token_deletion(event_id, g_wallet.cfg->keys.private_key, time(NULL));
}
if (!del) return -1;
int rc = publish_from_signed_event_template(del, NULL);
cJSON_Delete(del);
@@ -408,6 +435,15 @@ int cashu_wallet_init(didactyl_config_t* cfg) {
return 0;
}
void cashu_wallet_set_signer(nostr_signer_t* signer) {
/* Non-owning: the signer handle is constructed and freed by main.c.
* Stored under the wallet mutex for visibility/tearing safety even
* though the handle itself is process-lifetime and immutable. */
pthread_mutex_lock(&g_wallet.mutex);
g_cashu_signer = signer;
pthread_mutex_unlock(&g_wallet.mutex);
}
void cashu_wallet_cleanup(void) {
if (!g_wallet.initialized) return;
@@ -2755,7 +2791,12 @@ int cashu_wallet_mints_set(const char** wallet_mints,
pthread_mutex_unlock(&g_wallet.mutex);
if (rc != 0) return -1;
cJSON* ev = nostr_nip61_create_nutzap_info_event(&info, g_wallet.cfg->keys.private_key, time(NULL));
cJSON* ev = NULL;
if (g_cashu_signer) {
ev = nostr_nip61_create_nutzap_info_event_with_signer(&info, g_cashu_signer, time(NULL));
} else {
ev = nostr_nip61_create_nutzap_info_event(&info, g_wallet.cfg->keys.private_key, time(NULL));
}
nostr_nip61_free_nutzap_info(&info);
if (!ev) return -1;

View File

@@ -5,8 +5,10 @@
#include "config.h"
#include "cjson/cJSON.h"
#include "../nostr_core_lib/nostr_core/nostr_signer.h"
int cashu_wallet_init(didactyl_config_t* cfg);
void cashu_wallet_set_signer(nostr_signer_t* signer);
void cashu_wallet_cleanup(void);
int cashu_wallet_load_from_relays(void);

View File

@@ -214,6 +214,97 @@ static int decode_pubkey_hex_or_npub(const char* in, char out_hex[65]) {
return -1;
}
/* Returns 1 if mode is a known signer mode, 0 otherwise. */
static int signer_mode_is_known(const char* mode) {
if (!mode || mode[0] == '\0') {
return 0;
}
return strcmp(mode, "local") == 0 ||
strcmp(mode, "nsigner_unix") == 0 ||
strcmp(mode, "nsigner_tcp") == 0;
}
/* Returns 1 if mode is a remote (nsigner_*) mode that does not require an
* in-process nsec, 0 otherwise. */
static int signer_mode_is_remote(const char* mode) {
if (!mode || mode[0] == '\0') {
return 0;
}
return strcmp(mode, "nsigner_unix") == 0 ||
strcmp(mode, "nsigner_tcp") == 0;
}
static int parse_signer_config(cJSON* root, didactyl_config_t* config) {
cJSON* signer = cJSON_GetObjectItemCaseSensitive(root, "signer");
if (!signer || !cJSON_IsObject(signer)) {
/* Missing signer block: defaults already applied by caller. */
return 0;
}
if (copy_json_string(signer, "mode", config->signer.mode,
sizeof(config->signer.mode), 0) != 0) {
config_set_error("signer.mode must be a string when provided");
return -1;
}
if (config->signer.mode[0] != '\0' && !signer_mode_is_known(config->signer.mode)) {
config_set_error("signer.mode '%s' is not a known signer mode "
"(expected: local, nsigner_unix, nsigner_tcp)",
config->signer.mode);
return -1;
}
if (copy_json_string(signer, "socket_name", config->signer.socket_name,
sizeof(config->signer.socket_name), 0) != 0) {
config_set_error("signer.socket_name must be a string when provided");
return -1;
}
if (copy_json_string(signer, "role", config->signer.role,
sizeof(config->signer.role), 0) != 0) {
config_set_error("signer.role must be a string when provided");
return -1;
}
cJSON* timeout = cJSON_GetObjectItemCaseSensitive(signer, "timeout_ms");
if (timeout && cJSON_IsNumber(timeout)) {
int t = (int)timeout->valuedouble;
if (t > 0) {
config->signer.timeout_ms = t;
}
}
if (copy_json_string(signer, "auth_privkey_hex", config->signer.auth_privkey_hex,
sizeof(config->signer.auth_privkey_hex), 0) != 0) {
config_set_error("signer.auth_privkey_hex must be a string when provided");
return -1;
}
/* Optional tcp host/port inside the signer block (alternative to --signer-tcp). */
if (copy_json_string(signer, "tcp_host", config->signer.tcp_host,
sizeof(config->signer.tcp_host), 0) != 0) {
config_set_error("signer.tcp_host must be a string when provided");
return -1;
}
cJSON* tcp_port = cJSON_GetObjectItemCaseSensitive(signer, "tcp_port");
if (tcp_port && cJSON_IsNumber(tcp_port)) {
int p = (int)tcp_port->valuedouble;
if (p > 0 && p <= 65535) {
config->signer.tcp_port = p;
}
}
/* Phase 4 item 20: optional emergency local nsec for admin-alert fallback.
* Parsed and stored only; no active fallback behavior is wired yet. */
if (copy_json_string(signer, "emergency_local_nsec",
config->signer.emergency_local_nsec,
sizeof(config->signer.emergency_local_nsec), 0) != 0) {
config_set_error("signer.emergency_local_nsec must be a string when provided");
return -1;
}
return 0;
}
static int parse_tools_config(cJSON* root, didactyl_config_t* config) {
cJSON* tools = cJSON_GetObjectItemCaseSensitive(root, "tools");
if (!tools || !cJSON_IsObject(tools)) {
@@ -226,6 +317,7 @@ static int parse_tools_config(cJSON* root, didactyl_config_t* config) {
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* max_context_bytes = cJSON_GetObjectItemCaseSensitive(tools, "max_context_bytes");
cJSON* local_http_fetch_default_timeout_seconds =
cJSON_GetObjectItemCaseSensitive(tools, "local_http_fetch_default_timeout_seconds");
cJSON* local_http_fetch_max_timeout_seconds =
@@ -252,6 +344,9 @@ static int parse_tools_config(cJSON* root, didactyl_config_t* config) {
if (stall_repeat_threshold && cJSON_IsNumber(stall_repeat_threshold)) {
config->tools.stall_repeat_threshold = (int)stall_repeat_threshold->valuedouble;
}
if (max_context_bytes && cJSON_IsNumber(max_context_bytes)) {
config->tools.max_context_bytes = (int)max_context_bytes->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;
@@ -311,6 +406,9 @@ static int parse_tools_config(cJSON* root, didactyl_config_t* config) {
if (config->tools.stall_repeat_threshold < 2) {
config->tools.stall_repeat_threshold = 3;
}
if (config->tools.max_context_bytes < 4096) {
config->tools.max_context_bytes = 128 * 1024;
}
if (config->tools.local_http_fetch_default_timeout_seconds < 1) {
config->tools.local_http_fetch_default_timeout_seconds = 20;
}
@@ -1441,6 +1539,7 @@ int config_load(const char* path, didactyl_config_t* config) {
config->tools.api_default_max_turns = 8;
config->tools.api_max_turns_ceiling = 32;
config->tools.stall_repeat_threshold = 3;
config->tools.max_context_bytes = 128 * 1024;
config->tools.local_http_fetch_default_timeout_seconds = 20;
config->tools.local_http_fetch_max_timeout_seconds = 120;
config->tools.blossom_max_upload_bytes = 16 * 1024 * 1024;
@@ -1483,6 +1582,18 @@ int config_load(const char* path, didactyl_config_t* config) {
config->cashu_wallet.auto_load = 1;
config->cashu_wallet.mint_timeout_seconds = 30;
/* Signer provider defaults: local mode, backward compatible. */
snprintf(config->signer.mode, sizeof(config->signer.mode), "%s", "local");
config->signer.socket_name[0] = '\0';
snprintf(config->signer.role, sizeof(config->signer.role), "%s", "main");
config->signer.timeout_ms = 15000;
config->signer.auth_privkey_hex[0] = '\0';
config->signer.tcp_host[0] = '\0';
config->signer.tcp_port = 0;
/* Phase 4 item 20: emergency local nsec placeholder. Off by default;
* no active fallback behavior yet (documentation/feature-flag only). */
config->signer.emergency_local_nsec[0] = '\0';
char* raw_buf = NULL;
size_t raw_len = 0;
if (read_file_to_buffer(path, &raw_buf, &raw_len) != 0) {
@@ -1617,7 +1728,15 @@ int config_load(const char* path, didactyl_config_t* config) {
goto cleanup;
}
if (config->keys.nsec[0] != '\0') {
if (parse_signer_config(root, config) != 0) {
/* parse_signer_config sets a specific error message. */
goto cleanup;
}
/* Only decode the raw private key in local mode. In remote (nsigner_*)
* modes the agent process never holds the nsec; the pubkey is learned
* from the signer at startup via nostr_signer_get_public_key(). */
if (!signer_mode_is_remote(config->signer.mode) && 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;

View File

@@ -8,6 +8,11 @@
#define OW_MAX_URL_LEN 256
#define OW_MAX_KEY_LEN 256
#define OW_MAX_MODEL_LEN 128
#define OW_MAX_SIGNER_MODE_LEN 32
#define OW_MAX_SIGNER_SOCKET_LEN 128
#define OW_MAX_SIGNER_ROLE_LEN 32
#define OW_MAX_SIGNER_HOST_LEN 128
#define OW_MAX_SIGNER_AUTH_HEX_LEN 65
#define OW_MAX_STRANGER_RESPONSE_LEN 512
@@ -51,6 +56,7 @@ typedef struct {
int api_default_max_turns;
int api_max_turns_ceiling;
int stall_repeat_threshold;
int max_context_bytes;
int local_http_fetch_default_timeout_seconds;
int local_http_fetch_max_timeout_seconds;
shell_tools_config_t shell;
@@ -115,6 +121,45 @@ typedef struct {
int mint_timeout_seconds;
} cashu_wallet_config_t;
/* Signer provider configuration.
*
* mode selects how signing/encryption operations are routed:
* "local" - raw 32-byte key held in cfg.keys.private_key (default,
* backward compatible, output-equivalent to legacy path).
* "nsigner_unix" - delegate to a running n_signer over an AF_UNIX abstract
* socket. The agent process holds no nsec.
* "nsigner_tcp" - delegate to a running n_signer over TCP (host:port).
* Requires auth_privkey_hex for the kind-27235 auth envelope.
*
* Missing signer block behaves as mode="local" using keys.nsec.
* In any nsigner_* mode, keys.nsec is optional and ignored; the agent pubkey
* is learned from the signer via nostr_signer_get_public_key().
*/
typedef struct {
char mode[OW_MAX_SIGNER_MODE_LEN]; /* "local" | "nsigner_unix" | "nsigner_tcp" */
char socket_name[OW_MAX_SIGNER_SOCKET_LEN]; /* nsigner_unix: abstract socket name (without @); "" = auto-discover */
char role[OW_MAX_SIGNER_ROLE_LEN]; /* n_signer role selector (default "main") */
int timeout_ms; /* per-call timeout (default 15000) */
char auth_privkey_hex[OW_MAX_SIGNER_AUTH_HEX_LEN]; /* optional, TCP auth envelope only */
/* nsigner_tcp parsed host/port (populated from --signer-tcp or config) */
char tcp_host[OW_MAX_SIGNER_HOST_LEN];
int tcp_port;
/* Optional emergency local nsec for admin-alert fallback (Phase 4 item 20).
*
* OFF by default (empty string). When populated AND a remote signer is
* unreachable, a future phase may use this in-process key ONLY to sign a
* minimal admin alert DM reporting the signer outage. This reintroduces
* the nsec into the agent process for that one purpose, which is a
* deliberate operator-accepted tradeoff: better to leak the nsec briefly
* to notify the admin than to fail silently.
*
* CURRENT STATUS: parsed and stored only. No active fallback behavior is
* implemented yet (feature flag / documentation placeholder). The field
* exists so operators can pre-stage the value; the fallback path is
* deferred until the supervisor/health surface (item 19) is proven. */
char emergency_local_nsec[OW_MAX_KEY_LEN]; /* "" = disabled (default) */
} signer_config_t;
typedef struct {
agent_keys_t keys;
admin_config_t admin;
@@ -128,6 +173,7 @@ typedef struct {
triggers_config_t triggers;
api_config_t api;
cashu_wallet_config_t cashu_wallet;
signer_config_t signer;
startup_event_t* startup_events;
int startup_event_count;
encrypted_event_t* encrypted_events;

View File

@@ -17,6 +17,7 @@
#include "cjson/cJSON.h"
#include "debug.h"
#include "mongoose.h"
#include "signer_health.h"
static http_api_context_t g_api_ctx;
static int g_api_initialized = 0;
@@ -815,7 +816,21 @@ static char* build_slash_help_all_json_local(void) {
int adopted_count = 0;
if (adoption_events && cJSON_IsArray(adoption_events) && cJSON_GetArraySize(adoption_events) > 0) {
cJSON* ev0 = cJSON_GetArrayItem(adoption_events, 0);
cJSON* ev0 = NULL;
double best_created = -1.0;
int an = cJSON_GetArraySize(adoption_events);
for (int ai = 0; ai < an; ai++) {
cJSON* ev = cJSON_GetArrayItem(adoption_events, ai);
if (!ev || !cJSON_IsObject(ev)) {
continue;
}
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(ev, "created_at");
double created = (created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0.0;
if (!ev0 || created > best_created) {
ev0 = ev;
best_created = created;
}
}
cJSON* tags = ev0 ? cJSON_GetObjectItemCaseSensitive(ev0, "tags") : NULL;
if (tags && cJSON_IsArray(tags)) {
int tn = cJSON_GetArraySize(tags);
@@ -1214,6 +1229,39 @@ static void handle_status(struct mg_connection* c) {
if (g_api_ctx.cfg) {
cJSON_AddStringToObject(root, "pubkey", g_api_ctx.cfg->keys.public_key_hex);
cJSON_AddNumberToObject(root, "relay_count", g_api_ctx.cfg->relay_count);
/* Phase 4 item 19: out-of-band signer health surface. Expose the
* configured signer mode and runtime health classification so an
* operator can detect a signing outage from the HTTP status endpoint
* without requiring a signed admin DM to come back. */
cJSON_AddStringToObject(root, "signer_mode",
g_api_ctx.cfg->signer.mode[0] ? g_api_ctx.cfg->signer.mode : "local");
}
/* Signer runtime health (process-global, lock-protected snapshot). */
signer_health_snapshot_t hs;
if (signer_health_snapshot(&hs) == 0) {
const char* state_str = "unknown";
if (hs.state == SIGNER_HEALTH_HEALTHY) {
state_str = "healthy";
} else if (hs.state == SIGNER_HEALTH_UNHEALTHY) {
state_str = "unhealthy";
}
cJSON_AddStringToObject(root, "signer_healthy",
hs.state == SIGNER_HEALTH_HEALTHY ? "true" :
hs.state == SIGNER_HEALTH_UNHEALTHY ? "false" : "unknown");
cJSON_AddStringToObject(root, "signer_health_state", state_str);
cJSON_AddStringToObject(root, "signer_last_error",
hs.last_reason[0] ? hs.last_reason : "");
if (hs.last_error_ts > 0) {
cJSON_AddNumberToObject(root, "signer_last_error_ts", (double)hs.last_error_ts);
} else {
cJSON_AddNullToObject(root, "signer_last_error_ts");
}
if (hs.last_ok_ts > 0) {
cJSON_AddNumberToObject(root, "signer_last_ok_ts", (double)hs.last_ok_ts);
} else {
cJSON_AddNullToObject(root, "signer_last_ok_ts");
}
}
cJSON_AddNumberToObject(root, "connected_relays", nostr_handler_connected_relay_count());

File diff suppressed because it is too large Load Diff

View File

@@ -12,8 +12,8 @@
// Using DIDACTYL_ prefix to avoid conflicts with nostr_core_lib VERSION macros
#define DIDACTYL_VERSION_MAJOR 0
#define DIDACTYL_VERSION_MINOR 2
#define DIDACTYL_VERSION_PATCH 35
#define DIDACTYL_VERSION "v0.2.35"
#define DIDACTYL_VERSION_PATCH 53
#define DIDACTYL_VERSION "v0.2.53"
// Agent metadata
#define DIDACTYL_NAME "Didactyl"

View File

@@ -10,6 +10,10 @@
#include "debug.h"
#include "../../nostr_core_lib/nostr_core/nostr_core.h"
/* Optional process-lifetime signer for NIP-44 encrypt/decrypt of private
* block-list content. Owned by main.c; non-owning here. */
static nostr_signer_t* g_block_signer = NULL;
typedef struct {
didactyl_config_t* cfg;
int initialized;
@@ -186,22 +190,43 @@ static int decrypt_private_tags_array(const char* encrypted_content, cJSON** out
return *out_array ? 0 : -1;
}
size_t cap = strlen(encrypted_content) + 4096;
char* plaintext = (char*)calloc(1, cap);
if (!plaintext) return -1;
/* Phase 3 item 13: route NIP-44 decrypt through the process signer when
* available so remote signer modes keep the nsec out of the agent. The
* signer verb returns a heap string via out-param; free it after parse.
* Falls back to the legacy raw-key path when no signer is set. */
const char* plain_src = NULL;
char* plain_to_free = NULL;
char* plaintext = NULL;
int rc = nostr_nip44_decrypt(g_block.cfg->keys.private_key,
g_block.cfg->keys.public_key,
encrypted_content,
plaintext,
cap);
if (rc != 0) {
free(plaintext);
return -1;
if (g_block_signer) {
int rc = nostr_signer_nip44_decrypt(g_block_signer,
g_block.cfg->keys.public_key_hex,
encrypted_content,
&plaintext);
if (rc != NOSTR_SUCCESS || !plaintext) {
return -1;
}
plain_src = plaintext;
plain_to_free = plaintext;
} else {
size_t cap = strlen(encrypted_content) + 4096;
plaintext = (char*)calloc(1, cap);
if (!plaintext) return -1;
int rc = nostr_nip44_decrypt(g_block.cfg->keys.private_key,
g_block.cfg->keys.public_key,
encrypted_content,
plaintext,
cap);
if (rc != 0) {
free(plaintext);
return -1;
}
plain_src = plaintext;
plain_to_free = plaintext;
}
cJSON* arr = cJSON_Parse(plaintext);
free(plaintext);
cJSON* arr = cJSON_Parse(plain_src);
free(plain_to_free);
if (!arr || !cJSON_IsArray(arr)) {
cJSON_Delete(arr);
return -1;
@@ -218,8 +243,25 @@ static int encrypt_private_tags_array(cJSON* private_tags_array, char** out_cont
char* plain = cJSON_PrintUnformatted(private_tags_array);
if (!plain) return -1;
/* Phase 3 item 13: route NIP-44 encrypt through the process signer when
* available. The signer verb returns a heap string via out-param. Falls
* back to the legacy raw-key path when no signer is set. */
char* cipher = NULL;
if (g_block_signer) {
int rc = nostr_signer_nip44_encrypt(g_block_signer,
g_block.cfg->keys.public_key_hex,
plain,
&cipher);
free(plain);
if (rc != NOSTR_SUCCESS || !cipher) {
return -1;
}
*out_content = cipher;
return 0;
}
size_t cap = strlen(plain) * 4 + 4096;
char* cipher = (char*)calloc(1, cap);
cipher = (char*)calloc(1, cap);
if (!cipher) {
free(plain);
return -1;
@@ -311,6 +353,12 @@ static int publish_kind10000(cJSON* public_tags, cJSON* private_tags, char* out_
return 0;
}
void nostr_block_list_set_signer(nostr_signer_t* signer) {
pthread_mutex_lock(&g_block.mutex);
g_block_signer = signer;
pthread_mutex_unlock(&g_block.mutex);
}
int nostr_block_list_init(didactyl_config_t* cfg) {
if (!cfg) return -1;
@@ -365,6 +413,7 @@ void nostr_block_list_cleanup(void) {
g_block.cfg = NULL;
g_block.loaded = 0;
g_block.initialized = 0;
g_block_signer = NULL;
pthread_mutex_unlock(&g_block.mutex);
}

View File

@@ -3,11 +3,19 @@
#include "config.h"
#include "cjson/cJSON.h"
#include "../nostr_core_lib/nostr_core/nostr_signer.h"
int nostr_block_list_init(didactyl_config_t* cfg);
int nostr_block_list_load_from_relays(void);
void nostr_block_list_cleanup(void);
/* Wire a process-lifetime signer handle (non-owning) so NIP-44 encrypt/decrypt
* of the private block-list content routes through the signer verbs in remote
* signer modes. Falls back to the legacy raw-key path when NULL. The caller
* must keep the signer alive for the module's lifetime and free it after
* nostr_block_list_cleanup. */
void nostr_block_list_set_signer(nostr_signer_t* signer);
int nostr_block_list_is_pubkey_blocked(const char* pubkey_hex);
int nostr_block_list_is_event_blocked(const char* event_id_hex);
int nostr_block_list_is_hashtag_blocked(const char* hashtag);

View File

@@ -15,6 +15,7 @@
#include "nostr_block_list.h"
#include "cashu_wallet.h"
#include "agent.h"
#include "signer_health.h"
/*
* Older nostr_core_lib versions only expose:
@@ -34,6 +35,8 @@
static didactyl_config_t* g_cfg = NULL;
static nostr_relay_pool_t* g_pool = NULL;
/* Optional process-lifetime signer for relay pool AUTH. Owned by main.c. */
static nostr_signer_t* g_auth_signer = NULL;
static dm_callback_t g_dm_callback = NULL;
static void* g_dm_user_data = NULL;
static int g_poll_counter = 0;
@@ -1048,6 +1051,26 @@ static int nip44_encrypt_self_local(const char* plaintext, char** out_ciphertext
}
const char* plain = plaintext ? plaintext : "";
/* Phase 3 item 13: route self-encrypt through the process signer when
* available so remote signer modes keep the nsec out of the agent. The
* signer verb returns a heap string via out-param. Falls back to the
* legacy raw-key path when no signer is set (local mode / pre-Phase-3). */
if (g_auth_signer) {
char* signer_out = NULL;
int rc = nostr_signer_nip44_encrypt(g_auth_signer,
g_cfg->keys.public_key_hex,
plain,
&signer_out);
if (rc != NOSTR_SUCCESS || !signer_out) {
signer_health_record_failure(rc, "nip44_encrypt(self)");
return -1;
}
signer_health_record_ok();
*out_ciphertext = signer_out;
return 0;
}
size_t out_cap = (strlen(plain) * 4U) + 1024U;
char* ciphertext = (char*)malloc(out_cap);
if (!ciphertext) {
@@ -1073,6 +1096,23 @@ static int nip44_decrypt_self_local(const char* ciphertext, char** out_plaintext
return -1;
}
/* Phase 3 item 13: route self-decrypt through the process signer when
* available. Falls back to the legacy raw-key path when no signer is set. */
if (g_auth_signer) {
char* signer_out = NULL;
int rc = nostr_signer_nip44_decrypt(g_auth_signer,
g_cfg->keys.public_key_hex,
ciphertext,
&signer_out);
if (rc != NOSTR_SUCCESS || !signer_out) {
signer_health_record_failure(rc, "nip44_decrypt(self)");
return -1;
}
signer_health_record_ok();
*out_plaintext = signer_out;
return 0;
}
size_t out_cap = strlen(ciphertext) + 1024U;
char* plaintext = (char*)malloc(out_cap);
if (!plaintext) {
@@ -1510,6 +1550,7 @@ static void register_trigger_from_self_skill_event(cJSON* event) {
static void self_skill_cache_upsert_event_locked(cJSON* event) {
if (!event || !cJSON_IsObject(event)) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: event missing or not object");
return;
}
@@ -1517,34 +1558,51 @@ static void self_skill_cache_upsert_event_locked(cJSON* event) {
cJSON* pubkey = cJSON_GetObjectItemCaseSensitive(event, "pubkey");
cJSON* tags = cJSON_GetObjectItemCaseSensitive(event, "tags");
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(event, "created_at");
cJSON* ev_id = cJSON_GetObjectItemCaseSensitive(event, "id");
int kind_val = (kind && cJSON_IsNumber(kind)) ? (int)kind->valuedouble : -1;
double created = (created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0.0;
DEBUG_INFO("[didactyl] self-skill upsert candidate: kind=%d author=%.16s... id=%.16s... created_at=%.0f",
kind_val,
(pubkey && cJSON_IsString(pubkey) && pubkey->valuestring) ? pubkey->valuestring : "?",
(ev_id && cJSON_IsString(ev_id) && ev_id->valuestring) ? ev_id->valuestring : "?",
created);
if (!kind || !cJSON_IsNumber(kind) ||
!pubkey || !cJSON_IsString(pubkey) || !pubkey->valuestring ||
!tags || !cJSON_IsArray(tags)) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: missing required kind/pubkey/tags");
return;
}
int kind_val = (int)kind->valuedouble;
if (kind_val != 31123 && kind_val != 31124 && kind_val != 10123) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: kind not in {31123,31124,10123}");
return;
}
if (!g_cfg) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: config unavailable");
return;
}
int is_agent_author = (strcmp(pubkey->valuestring, g_cfg->keys.public_key_hex) == 0);
int is_admin_author = (g_cfg->admin.pubkey[0] != '\0' && strcmp(pubkey->valuestring, g_cfg->admin.pubkey) == 0);
if (!is_agent_author && !is_admin_author) {
return;
if (kind_val == 10123) {
if (!is_agent_author) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: kind=10123 author is not self");
return;
}
}
if (is_admin_author && kind_val != 31123) {
if (is_admin_author && kind_val == 31124) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: admin cannot own private skill (31124)");
return;
}
const char* d_tag = find_tag_value_local(tags, "d");
if ((kind_val == 31123 || kind_val == 31124) && (!d_tag || d_tag[0] == '\0')) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: parameterized kind missing d-tag");
return;
}
@@ -1552,12 +1610,11 @@ static void self_skill_cache_upsert_event_locked(cJSON* event) {
cJSON_Delete(g_self_skill_events);
g_self_skill_events = cJSON_CreateArray();
if (!g_self_skill_events) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: failed to create cache array");
return;
}
}
double created = (created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0.0;
int n = cJSON_GetArraySize(g_self_skill_events);
for (int i = 0; i < n; i++) {
cJSON* existing = cJSON_GetArrayItem(g_self_skill_events, i);
@@ -1589,23 +1646,56 @@ static void self_skill_cache_upsert_event_locked(cJSON* event) {
cJSON* ex_created_at = cJSON_GetObjectItemCaseSensitive(existing, "created_at");
double ex_created = (ex_created_at && cJSON_IsNumber(ex_created_at)) ? ex_created_at->valuedouble : 0.0;
if (created < ex_created) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: stale (existing created_at=%.0f >= new created_at=%.0f)",
ex_created,
created);
return;
}
cJSON* dup = cJSON_Duplicate(event, 1);
if (!dup) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: failed to duplicate event");
return;
}
cJSON_ReplaceItemInArray(g_self_skill_events, i, dup);
DEBUG_INFO("[didactyl] self-skill upsert accepted: replaced existing (old created_at=%.0f)", ex_created);
if (kind_val == 10123) {
int a_count = 0;
cJSON* t;
cJSON_ArrayForEach(t, tags) {
if (cJSON_IsArray(t) && cJSON_GetArraySize(t) >= 2) {
cJSON* t0 = cJSON_GetArrayItem(t, 0);
if (t0 && cJSON_IsString(t0) && t0->valuestring && strcmp(t0->valuestring, "a") == 0) {
a_count++;
}
}
}
DEBUG_INFO("[didactyl] kind 10123 accepted with %d 'a' tags", a_count);
}
return;
}
cJSON* dup = cJSON_Duplicate(event, 1);
if (!dup) {
DEBUG_INFO("[didactyl] self-skill upsert rejected: failed to duplicate event");
return;
}
cJSON_AddItemToArray(g_self_skill_events, dup);
DEBUG_INFO("[didactyl] self-skill upsert accepted: new entry added");
if (kind_val == 10123) {
int a_count = 0;
cJSON* t;
cJSON_ArrayForEach(t, tags) {
if (cJSON_IsArray(t) && cJSON_GetArraySize(t) >= 2) {
cJSON* t0 = cJSON_GetArrayItem(t, 0);
if (t0 && cJSON_IsString(t0) && t0->valuestring && strcmp(t0->valuestring, "a") == 0) {
a_count++;
}
}
}
DEBUG_INFO("[didactyl] kind 10123 accepted with %d 'a' tags", a_count);
}
}
static int hex_to_pubkey(const char* hex, unsigned char out_pubkey[32]) {
@@ -1868,19 +1958,38 @@ static void on_event(cJSON* event, const char* relay_url, void* user_data) {
return;
}
decrypted = (char*)malloc(NOSTR_NIP04_MAX_PLAINTEXT_SIZE);
if (!decrypted) {
fprintf(stderr, "[didactyl] failed to allocate DM decrypt buffer\n");
return;
}
decrypted[0] = '\0';
trace_event_json("received encrypted DM event:", event);
if (nostr_nip04_decrypt(g_cfg->keys.private_key, sender_pubkey, content->valuestring, decrypted, NOSTR_NIP04_MAX_PLAINTEXT_SIZE) != NOSTR_SUCCESS) {
fprintf(stdout, "[didactyl] failed to decrypt incoming DM from %.16s...\n", sender_pubkey_hex);
free(decrypted);
return;
/* Phase 3 item 13: route NIP-04 decrypt through the process signer
* when available so remote signer modes keep the nsec out of the
* agent. The signer verb returns a heap string via out-param. Falls
* back to the legacy raw-key path when no signer is set. */
if (g_auth_signer) {
char* signer_out = NULL;
int dec_rc = nostr_signer_nip04_decrypt(g_auth_signer,
sender_pubkey_hex,
content->valuestring,
&signer_out);
if (dec_rc != NOSTR_SUCCESS || !signer_out) {
signer_health_record_failure(dec_rc, "nip04_decrypt(incoming DM)");
fprintf(stdout, "[didactyl] failed to decrypt incoming DM from %.16s...\n", sender_pubkey_hex);
return;
}
signer_health_record_ok();
decrypted = signer_out;
} else {
decrypted = (char*)malloc(NOSTR_NIP04_MAX_PLAINTEXT_SIZE);
if (!decrypted) {
fprintf(stderr, "[didactyl] failed to allocate DM decrypt buffer\n");
return;
}
decrypted[0] = '\0';
if (nostr_nip04_decrypt(g_cfg->keys.private_key, sender_pubkey, content->valuestring, decrypted, NOSTR_NIP04_MAX_PLAINTEXT_SIZE) != NOSTR_SUCCESS) {
fprintf(stdout, "[didactyl] failed to decrypt incoming DM from %.16s...\n", sender_pubkey_hex);
free(decrypted);
return;
}
}
trace_plaintext_dm("received decrypted DM content:", decrypted);
@@ -1891,7 +2000,16 @@ static void on_event(cJSON* event, const char* relay_url, void* user_data) {
return;
}
cJSON* rumor = nostr_nip17_receive_dm(event, g_cfg->keys.private_key);
/* Phase 3 item 14: prefer signer-aware NIP-17 unwrap when a process
* signer is available; fall back to the legacy raw-key path in local
* mode / pre-Phase-3. Gift-wrap event ownership is unchanged: the
* returned rumor cJSON is owned by us and freed below. */
cJSON* rumor = NULL;
if (g_auth_signer) {
rumor = nostr_nip17_receive_dm_with_signer(event, g_auth_signer);
} else {
rumor = nostr_nip17_receive_dm(event, g_cfg->keys.private_key);
}
if (!rumor) {
DEBUG_TRACE("[didactyl] DEBUG on_event: failed to unwrap/decrypt NIP-17 gift wrap %.16s...",
event_id_hex ? event_id_hex : "<no-id>");
@@ -2470,6 +2588,10 @@ static void on_wallet_event(cJSON* event, const char* relay_url, void* user_data
(void)cashu_wallet_load_from_relays();
}
void nostr_handler_set_signer(nostr_signer_t* signer) {
g_auth_signer = signer;
}
int nostr_handler_init(didactyl_config_t* config) {
if (!config) {
return -1;
@@ -2512,16 +2634,28 @@ int nostr_handler_init(didactyl_config_t* config) {
nostr_pool_reconnect_config_t reconnect = *nostr_pool_reconnect_config_default();
reconnect.enable_auto_reconnect = 1;
reconnect.ping_interval_seconds = 20;
reconnect.pong_timeout_seconds = 10;
reconnect.pong_timeout_seconds = 30;
g_pool = nostr_relay_pool_create(&reconnect);
if (!g_pool) {
return -1;
}
if (nostr_relay_pool_set_auth(g_pool, g_cfg->keys.private_key, 1) != NOSTR_SUCCESS) {
fprintf(stderr, "[didactyl] failed to enable relay pool auth\n");
return -1;
/* Relay pool NIP-42 AUTH. When a process-lifetime signer is available
* (set via nostr_handler_set_signer), route AUTH signing through it so
* remote signer modes can keep the nsec out of the agent process. In
* local mode the signer wraps the same raw key, so behavior is identical.
* Falls back to the legacy raw-key path when no signer is set. */
if (g_auth_signer) {
if (nostr_relay_pool_set_auth_with_signer(g_pool, g_auth_signer, 1) != NOSTR_SUCCESS) {
fprintf(stderr, "[didactyl] failed to enable relay pool auth (signer path)\n");
return -1;
}
} else {
if (nostr_relay_pool_set_auth(g_pool, g_cfg->keys.private_key, 1) != NOSTR_SUCCESS) {
fprintf(stderr, "[didactyl] failed to enable relay pool auth\n");
return -1;
}
}
for (int i = 0; i < g_cfg->relay_count; i++) {
@@ -2773,6 +2907,10 @@ int nostr_handler_subscribe_self_skills(void) {
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddNumberToObject(filter, "limit", 300);
char* filter_str = cJSON_PrintUnformatted(filter);
DEBUG_INFO("[didactyl] self-skill subscription filter: %s", filter_str ? filter_str : "(null)");
free(filter_str);
pthread_mutex_lock(&g_subscription_mutex);
managed_subscriptions_init_defaults();
if (managed_subscription_register_locked(MANAGED_SUB_SELF_SKILLS,
@@ -3090,16 +3228,33 @@ int nostr_handler_send_dm_with_role(const char* recipient_pubkey_hex,
trace_plaintext_dm("sending plaintext DM content:", message);
char* encrypted = (char*)malloc(NOSTR_NIP04_MAX_ENCRYPTED_SIZE);
if (!encrypted) {
fprintf(stderr, "[didactyl] failed to allocate DM encrypt buffer\n");
return -1;
}
encrypted[0] = '\0';
/* Phase 3 item 13: route NIP-04 encrypt through the process signer when
* available so remote signer modes keep the nsec out of the agent. The
* signer verb returns a heap string via out-param. Falls back to the
* legacy raw-key path when no signer is set. */
char* encrypted = NULL;
if (g_auth_signer) {
int enc_rc = nostr_signer_nip04_encrypt(g_auth_signer,
recipient_pubkey_hex,
message,
&encrypted);
if (enc_rc != NOSTR_SUCCESS || !encrypted) {
signer_health_record_failure(enc_rc, "nip04_encrypt(outgoing DM)");
return -1;
}
signer_health_record_ok();
} else {
encrypted = (char*)malloc(NOSTR_NIP04_MAX_ENCRYPTED_SIZE);
if (!encrypted) {
fprintf(stderr, "[didactyl] failed to allocate DM encrypt buffer\n");
return -1;
}
encrypted[0] = '\0';
if (nostr_nip04_encrypt(g_cfg->keys.private_key, recipient_pubkey, message, encrypted, NOSTR_NIP04_MAX_ENCRYPTED_SIZE) != NOSTR_SUCCESS) {
free(encrypted);
return -1;
if (nostr_nip04_encrypt(g_cfg->keys.private_key, recipient_pubkey, message, encrypted, NOSTR_NIP04_MAX_ENCRYPTED_SIZE) != NOSTR_SUCCESS) {
free(encrypted);
return -1;
}
}
cJSON* tags = create_dm_tags_for_recipient(recipient_pubkey_hex);
@@ -3108,7 +3263,17 @@ int nostr_handler_send_dm_with_role(const char* recipient_pubkey_hex,
return -1;
}
cJSON* event = nostr_create_and_sign_event(4, encrypted, tags, g_cfg->keys.private_key, time(NULL));
/* Phase 3 item 12: route kind-4 DM event signing through the process
* signer handle when available so remote signer modes can keep the nsec
* out of the agent process. Falls back to the legacy raw-key path when
* no signer is set (local mode / pre-Phase-2 binaries) so behavior is
* unchanged. */
cJSON* event = NULL;
if (g_auth_signer) {
event = nostr_create_and_sign_event_with_signer(4, encrypted, tags, g_auth_signer, time(NULL));
} else {
event = nostr_create_and_sign_event(4, encrypted, tags, g_cfg->keys.private_key, time(NULL));
}
cJSON_Delete(tags);
free(encrypted);
if (!event) {
@@ -3247,7 +3412,17 @@ static int publish_kind_event_to_relays(int kind,
}
}
cJSON* event = nostr_create_and_sign_event(kind, content_to_publish, tags_copy, g_cfg->keys.private_key, time(NULL));
/* Phase 3 item 12: route generic kind event signing through the process
* signer handle when available (covers kind 30078 config publish, kind
* 31124 private skill events, startup adoption events, etc.). Falls back
* to the legacy raw-key path when no signer is set so local mode is
* unchanged. */
cJSON* event = NULL;
if (g_auth_signer) {
event = nostr_create_and_sign_event_with_signer(kind, content_to_publish, tags_copy, g_auth_signer, time(NULL));
} else {
event = nostr_create_and_sign_event(kind, content_to_publish, tags_copy, g_cfg->keys.private_key, time(NULL));
}
if (tags_copy) {
cJSON_Delete(tags_copy);
}
@@ -3694,6 +3869,180 @@ char* nostr_handler_get_self_skill_events_json(void) {
return json ? json : strdup("[]");
}
int nostr_handler_refresh_self_skill_cache_from_relays(int timeout_ms) {
if (!g_cfg || !g_pool) {
return -1;
}
int effective_timeout_ms = timeout_ms > 0 ? timeout_ms : 5000;
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 -1;
}
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(31123));
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(31124));
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(10123));
cJSON_AddItemToObject(filter, "kinds", kinds);
cJSON_AddItemToArray(authors, cJSON_CreateString(g_cfg->keys.public_key_hex));
cJSON_AddItemToObject(filter, "authors", authors);
cJSON_AddNumberToObject(filter, "limit", 500);
char* events_json = nostr_handler_query_json(filter, effective_timeout_ms);
cJSON_Delete(filter);
if (!events_json) {
return -1;
}
cJSON* events = cJSON_Parse(events_json);
free(events_json);
if (!events || !cJSON_IsArray(events)) {
cJSON_Delete(events);
return -1;
}
cJSON* adopted_authors = cJSON_CreateObject();
if (adopted_authors) {
cJSON* latest_self_adoption = NULL;
double latest_self_adoption_created = -1.0;
int n0 = cJSON_GetArraySize(events);
for (int i = 0; i < n0; i++) {
cJSON* ev = cJSON_GetArrayItem(events, i);
if (!ev || !cJSON_IsObject(ev)) {
continue;
}
cJSON* kind = cJSON_GetObjectItemCaseSensitive(ev, "kind");
cJSON* pubkey = cJSON_GetObjectItemCaseSensitive(ev, "pubkey");
if (!kind || !cJSON_IsNumber(kind) || (int)kind->valuedouble != 10123 ||
!pubkey || !cJSON_IsString(pubkey) || !pubkey->valuestring ||
strcmp(pubkey->valuestring, g_cfg->keys.public_key_hex) != 0) {
continue;
}
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(ev, "created_at");
double created = (created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0.0;
if (!latest_self_adoption || created > latest_self_adoption_created) {
latest_self_adoption = ev;
latest_self_adoption_created = created;
}
}
if (latest_self_adoption) {
cJSON* tags = cJSON_GetObjectItemCaseSensitive(latest_self_adoption, "tags");
if (tags && cJSON_IsArray(tags)) {
int tn = cJSON_GetArraySize(tags);
for (int ti = 0; ti < tn; ti++) {
cJSON* tag = cJSON_GetArrayItem(tags, ti);
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 || strcmp(k->valuestring, "a") != 0) {
continue;
}
int adopted_kind = 0;
char adopted_pubkey[65] = {0};
char adopted_d_tag[65] = {0};
if (parse_skill_address_local(v->valuestring, &adopted_kind, adopted_pubkey, adopted_d_tag) != 0) {
continue;
}
if (adopted_pubkey[0] == '\0') {
continue;
}
if (!cJSON_GetObjectItemCaseSensitive(adopted_authors, adopted_pubkey)) {
cJSON_AddBoolToObject(adopted_authors, adopted_pubkey, 1);
}
}
}
}
int adopted_author_count = 0;
cJSON* adopted_it = NULL;
cJSON_ArrayForEach(adopted_it, adopted_authors) {
adopted_author_count++;
}
if (adopted_author_count > 0) {
cJSON* adopted_filter = cJSON_CreateObject();
cJSON* adopted_kinds = cJSON_CreateArray();
cJSON* adopted_author_arr = cJSON_CreateArray();
if (adopted_filter && adopted_kinds && adopted_author_arr) {
cJSON_AddItemToArray(adopted_kinds, cJSON_CreateNumber(31123));
cJSON_AddItemToArray(adopted_kinds, cJSON_CreateNumber(31124));
cJSON_AddItemToObject(adopted_filter, "kinds", adopted_kinds);
cJSON_ArrayForEach(adopted_it, adopted_authors) {
if (adopted_it->string && adopted_it->string[0] != '\0') {
cJSON_AddItemToArray(adopted_author_arr, cJSON_CreateString(adopted_it->string));
}
}
cJSON_AddItemToObject(adopted_filter, "authors", adopted_author_arr);
cJSON_AddNumberToObject(adopted_filter, "limit", 1000);
char* adopted_json = nostr_handler_query_json(adopted_filter, effective_timeout_ms);
if (adopted_json) {
cJSON* adopted_events = cJSON_Parse(adopted_json);
free(adopted_json);
if (adopted_events && cJSON_IsArray(adopted_events)) {
int an = cJSON_GetArraySize(adopted_events);
for (int ai = 0; ai < an; ai++) {
cJSON* ev = cJSON_GetArrayItem(adopted_events, ai);
cJSON* dup = ev ? cJSON_Duplicate(ev, 1) : NULL;
if (dup) {
cJSON_AddItemToArray(events, dup);
}
}
}
cJSON_Delete(adopted_events);
}
} else {
cJSON_Delete(adopted_filter);
cJSON_Delete(adopted_kinds);
cJSON_Delete(adopted_author_arr);
}
cJSON_Delete(adopted_filter);
}
}
cJSON_Delete(adopted_authors);
int merged = 0;
pthread_mutex_lock(&g_self_skill_mutex);
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");
int kind_val = (kind && cJSON_IsNumber(kind)) ? (int)kind->valuedouble : -1;
if (kind_val == 31124) {
(void)normalize_private_skill_event_local(ev);
}
self_skill_cache_upsert_event_locked(ev);
merged++;
}
pthread_mutex_unlock(&g_self_skill_mutex);
cJSON_Delete(events);
agent_invalidate_adopted_skills_cache();
DEBUG_INFO("[didactyl] skill_refresh relay reload merged %d self-skill/adoption events", merged);
return 0;
}
int nostr_handler_is_event_in_self_cache(const char* event_id_hex) {
if (!event_id_hex || strlen(event_id_hex) != 64U) {
return 0;
@@ -3740,6 +4089,50 @@ int nostr_handler_connected_relay_count(void) {
return connected;
}
char* nostr_handler_relay_state_summary(void) {
if (!g_cfg || !g_pool || g_cfg->relay_count <= 0 || !g_cfg->relays) {
return NULL;
}
size_t total = 1;
for (int i = 0; i < g_cfg->relay_count; i++) {
const char* relay = (g_cfg->relays[i] && g_cfg->relays[i][0] != '\0') ? g_cfg->relays[i] : "<unknown>";
const char* status = relay_status_str(nostr_relay_pool_get_relay_status(g_pool, relay));
total += strlen(relay) + 1 + strlen(status) + 2;
}
char* out = (char*)malloc(total);
if (!out) {
return NULL;
}
out[0] = '\0';
size_t used = 0;
for (int i = 0; i < g_cfg->relay_count; i++) {
const char* relay = (g_cfg->relays[i] && g_cfg->relays[i][0] != '\0') ? g_cfg->relays[i] : "<unknown>";
const char* status = relay_status_str(nostr_relay_pool_get_relay_status(g_pool, relay));
int n = snprintf(out + used,
total - used,
"%s%s=%s",
(i == 0) ? "" : "; ",
relay,
status);
if (n < 0) {
free(out);
return NULL;
}
size_t written = (size_t)n;
if (written >= (total - used)) {
used = total - 1;
break;
}
used += written;
}
return out;
}
char* nostr_handler_relay_status_json(void) {
if (!g_pool) {
return NULL;
@@ -4087,14 +4480,29 @@ int nostr_handler_send_dm_nip17_with_role(const char* recipient_pubkey_hex,
return -1;
}
/* Phase 3 item 14: prefer signer-aware NIP-17 gift-wrap creation when a
* process signer is available; fall back to the legacy raw-key path in
* local mode / pre-Phase-3. Gift-wrap ownership is unchanged: each
* non-NULL entry in gift_wraps[] is freed by cJSON_Delete below. */
cJSON* gift_wraps[NIP17_MAX_GIFT_WRAPS] = {0};
int gift_count = nostr_nip17_send_dm(chat_event,
int gift_count = 0;
if (g_auth_signer) {
gift_count = nostr_nip17_send_dm_with_signer(chat_event,
recipients,
1,
g_auth_signer,
gift_wraps,
NIP17_MAX_GIFT_WRAPS,
0);
} else {
gift_count = nostr_nip17_send_dm(chat_event,
recipients,
1,
g_cfg->keys.private_key,
gift_wraps,
NIP17_MAX_GIFT_WRAPS,
0);
}
cJSON_Delete(chat_event);
if (gift_count <= 0) {
DEBUG_WARN("[didactyl] NIP-17 send aborted: gift_wrap creation failed for %.16s...",
@@ -4658,6 +5066,7 @@ void nostr_handler_cleanup(void) {
g_pool = NULL;
g_cfg = NULL;
g_auth_signer = NULL;
g_dm_callback = NULL;
g_dm_user_data = NULL;
memset(g_seen_dm_ids, 0, sizeof(g_seen_dm_ids));

View File

@@ -40,6 +40,15 @@ typedef struct {
typedef void (*nostr_self_skill_eose_cb_t)(int event_count, void* user_data);
int nostr_handler_init(didactyl_config_t* config);
/* Optional: provide a process-lifetime signer handle for relay pool AUTH.
* When set, nostr_handler_init routes NIP-42 AUTH through the signer via
* nostr_relay_pool_set_auth_with_signer instead of the raw private-key path.
* The caller retains ownership of the signer and must free it after
* nostr_handler_cleanup. If not called, the legacy raw-key AUTH path is used
* (backward compatible). */
void nostr_handler_set_signer(nostr_signer_t* signer);
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);
@@ -77,9 +86,11 @@ int nostr_handler_validate_self_skill_cache(int* out_skill_count, int* out_adopt
void nostr_handler_refresh_relay_statuses(void);
int nostr_handler_sync_relays_from_config(void);
char* nostr_handler_get_self_skill_events_json(void);
int nostr_handler_refresh_self_skill_cache_from_relays(int timeout_ms);
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_relay_state_summary(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);

View File

@@ -276,6 +276,7 @@ static void config_set_defaults(didactyl_config_t* cfg) {
cfg->tools.api_default_max_turns = 8;
cfg->tools.api_max_turns_ceiling = 32;
cfg->tools.stall_repeat_threshold = 3;
cfg->tools.max_context_bytes = 128 * 1024;
cfg->tools.local_http_fetch_default_timeout_seconds = 20;
cfg->tools.local_http_fetch_max_timeout_seconds = 120;
cfg->tools.blossom_max_upload_bytes = 16 * 1024 * 1024;
@@ -315,6 +316,13 @@ static void config_set_defaults(didactyl_config_t* cfg) {
snprintf(cfg->llm.base_url, sizeof(cfg->llm.base_url), "%s", "https://api.openai.com/v1");
cfg->llm.max_tokens = 512;
cfg->llm.temperature = 0.7;
/* Signer provider defaults: local mode, backward compatible.
* Without these, apply_signer_overrides() in main.c rejects an empty
* signer.mode after the wizard returns BOOTSTRAP for local paths. */
snprintf(cfg->signer.mode, sizeof(cfg->signer.mode), "%s", "local");
snprintf(cfg->signer.role, sizeof(cfg->signer.role), "%s", "main");
cfg->signer.timeout_ms = 15000;
}
static void free_relays_only(didactyl_config_t* cfg) {
@@ -993,6 +1001,15 @@ static int fetch_and_decrypt_self_config_wizard(const didactyl_config_t* cfg, co
return -1;
}
/* Phase 3 item 13: DEFERRED — the setup wizard runs before any
* process-lifetime signer is constructed. In local mode (the only mode
* the wizard persists keys for) the nsec is held directly by the wizard,
* so the raw-key path is correct and output-equivalent. The nsigner_unix
* wizard path only does an ephemeral connectivity check and frees its
* signer immediately; it does not recall/persist encrypted user-settings.
* Migrating this site would require threading an ephemeral signer through
* the wizard for no separation benefit, so it is intentionally left on
* the legacy raw-key path. */
int dec_rc = nostr_nip44_decrypt(cfg->keys.private_key,
cfg->keys.public_key,
content->valuestring,
@@ -1140,6 +1157,10 @@ static int publish_encrypted_self_config_wizard(const didactyl_config_t* cfg,
char* ciphertext = (char*)malloc(cipher_cap);
if (!ciphertext) return -1;
/* Phase 3 item 13: DEFERRED — see the matching note in the wizard's
* fetch_self_config_plaintext. The wizard holds the nsec directly in
* local mode and has no process-lifetime signer, so the raw-key path is
* correct here. */
int enc_rc = nostr_nip44_encrypt(cfg->keys.private_key,
cfg->keys.public_key,
content_json,
@@ -1207,6 +1228,15 @@ static int persist_runtime_config_to_nostr_wizard(const didactyl_config_t* cfg)
cJSON_AddNumberToObject(didactyl, "max_turns", cfg->tools.max_turns > 0 ? cfg->tools.max_turns : 40);
cJSON_AddItemToObject(user_settings, "didactyl", didactyl);
cJSON* signer = cJSON_CreateObject();
if (signer) {
cJSON_AddStringToObject(signer, "mode", cfg->signer.mode);
cJSON_AddStringToObject(signer, "socket_name", cfg->signer.socket_name);
cJSON_AddStringToObject(signer, "role", cfg->signer.role);
cJSON_AddNumberToObject(signer, "timeout_ms", cfg->signer.timeout_ms);
cJSON_AddItemToObject(user_settings, "signer", signer);
}
char* settings_json = cJSON_PrintUnformatted(user_settings);
cJSON_Delete(user_settings);
if (!settings_json) return -1;
@@ -1908,7 +1938,10 @@ static int write_sudoers_file(const char* service_user) {
}
static int install_system_service_with_dedicated_user(const didactyl_config_t* cfg, const char* agent_name) {
if (!cfg || cfg->keys.nsec[0] == '\0') return -1;
/* local mode requires an nsec to embed in ExecStart; remote signer modes
do not hold the nsec and instead pass --signer flags. */
if (!cfg) return -1;
if (strcmp(cfg->signer.mode, "local") == 0 && cfg->keys.nsec[0] == '\0') return -1;
if (geteuid() != 0) {
fprintf(stderr, " Requesting sudo authentication for system install...\n");
@@ -2006,6 +2039,33 @@ static int install_system_service_with_dedicated_user(const didactyl_config_t* c
snprintf(env_line, sizeof(env_line), "Environment=SSL_CERT_FILE=%s\\n", ca_bundle);
}
/* Build the key/signer argument tail for ExecStart.
* - local mode: embeds the nsec directly (legacy behavior).
* - nsigner_unix mode: passes --signer/--signer-socket/--signer-role/--signer-timeout
* so the service process reconstructs the remote signer without holding the nsec.
* - nsigner_tcp mode: passes --signer-tcp host:port plus role/timeout.
* The agent pubkey, admin, LLM and relays are recovered from Nostr at boot. */
char key_args[768] = {0};
if (strcmp(cfg->signer.mode, "nsigner_unix") == 0) {
snprintf(key_args, sizeof(key_args),
"--signer nsigner_unix --signer-role %s --signer-timeout %d%s%s",
cfg->signer.role[0] ? cfg->signer.role : "main",
cfg->signer.timeout_ms > 0 ? cfg->signer.timeout_ms : 15000,
cfg->signer.socket_name[0] ? " --signer-socket " : "",
cfg->signer.socket_name[0] ? cfg->signer.socket_name : "");
} else if (strcmp(cfg->signer.mode, "nsigner_tcp") == 0) {
char host_port[OW_MAX_SIGNER_HOST_LEN + 16] = {0};
snprintf(host_port, sizeof(host_port), "%s:%d", cfg->signer.tcp_host, cfg->signer.tcp_port);
snprintf(key_args, sizeof(key_args),
"--signer-tcp %s --signer-role %s --signer-timeout %d",
host_port,
cfg->signer.role[0] ? cfg->signer.role : "main",
cfg->signer.timeout_ms > 0 ? cfg->signer.timeout_ms : 15000);
} else {
/* local mode (default): embed the nsec directly in ExecStart. */
snprintf(key_args, sizeof(key_args), "--nsec %s", cfg->keys.nsec);
}
char service_content[8192] = {0};
int svc_len = snprintf(service_content,
sizeof(service_content),
@@ -2014,11 +2074,13 @@ static int install_system_service_with_dedicated_user(const didactyl_config_t* c
"After=network-online.target\n"
"Wants=network-online.target\n\n"
"[Service]\n"
"Type=simple\n"
"Type=notify\n"
"NotifyAccess=main\n"
"WatchdogSec=120\n"
"User=%s\n"
"Group=%s\n"
"WorkingDirectory=%s\n"
"ExecStart=%s --nsec %s --debug 3\n"
"ExecStart=%s --debug 3 %s\n"
"%s"
"SyslogIdentifier=%s\n"
"NoNewPrivileges=false\n"
@@ -2037,7 +2099,7 @@ static int install_system_service_with_dedicated_user(const didactyl_config_t* c
service_user,
home,
bin_path,
cfg->keys.nsec,
key_args,
env_line,
service_user,
home);
@@ -2073,7 +2135,11 @@ static int install_system_service_with_dedicated_user(const didactyl_config_t* c
fprintf(stderr, " User: %s\n", service_user);
fprintf(stderr, " Home: %s\n", home);
fprintf(stderr, " Binary: %s\n", bin_path);
fprintf(stderr, " Nsec: embedded directly in ExecStart\n");
if (strcmp(cfg->signer.mode, "local") == 0) {
fprintf(stderr, " Nsec: embedded directly in ExecStart\n");
} else {
fprintf(stderr, " Signer: %s (nsec held by n_signer, not the agent)\n", cfg->signer.mode);
}
fprintf(stderr, " Sudoers: /etc/sudoers.d/%s\n", service_user);
fprintf(stderr, " Unit: %s\n", service_path);
fprintf(stderr, "\n Useful commands:\n");
@@ -2115,10 +2181,11 @@ static int new_agent_identity_step(didactyl_config_t* cfg) {
render_wizard_page_header("Step 2 of 7", "New Agent Setup -- Identity");
print_option('g', "enerate a new Nostr keypair");
print_option('p', "rovide an existing nsec");
print_option('s', "ign with a running n_signer");
print_option('b', "ack");
print_option('q', "uit");
wizard_option_t opts[] = {{'g', ""}, {'p', ""}, {'b', ""}, {'q', ""}};
char c = read_menu_choice(opts, 4);
wizard_option_t opts[] = {{'g', ""}, {'p', ""}, {'s', ""}, {'b', ""}, {'q', ""}};
char c = read_menu_choice(opts, 5);
if (c == 'q') return -1;
if (c == 'b') return 1;
@@ -2168,6 +2235,38 @@ static int new_agent_identity_step(didactyl_config_t* cfg) {
}
}
if (c == 's') {
snprintf(cfg->signer.mode, sizeof(cfg->signer.mode), "%s", "nsigner_unix");
if (read_line_prompt(" Socket name (empty for auto-discovery): ", cfg->signer.socket_name, sizeof(cfg->signer.socket_name)) != 0) return -1;
if (read_line_prompt(" Role [main]: ", cfg->signer.role, sizeof(cfg->signer.role)) != 0) return -1;
if (cfg->signer.role[0] == '\0') snprintf(cfg->signer.role, sizeof(cfg->signer.role), "%s", "main");
char timeout_buf[32] = {0};
if (read_line_prompt(" Timeout ms [15000]: ", timeout_buf, sizeof(timeout_buf)) != 0) return -1;
cfg->signer.timeout_ms = (timeout_buf[0] != '\0') ? atoi(timeout_buf) : 15000;
if (cfg->signer.timeout_ms <= 0) cfg->signer.timeout_ms = 15000;
fprintf(stderr, " Checking connectivity to n_signer...\n");
#if defined(NOSTR_ENABLE_NSIGNER_CLIENT)
nostr_signer_t* signer = nostr_signer_nsigner_unix(cfg->signer.socket_name[0] ? cfg->signer.socket_name : NULL,
cfg->signer.role,
cfg->signer.timeout_ms);
if (!signer) {
fprintf(stderr, "%sFailed to initialize n_signer client.%s\n", ANSI_RED, ANSI_RESET);
continue;
}
if (nostr_signer_get_public_key(signer, cfg->keys.public_key_hex) != 0) {
fprintf(stderr, "%sFailed to retrieve public key from n_signer.%s\n", ANSI_RED, ANSI_RESET);
nostr_signer_free(signer);
continue;
}
nostr_signer_free(signer);
fprintf(stderr, "%sConnectivity check: OK. Pubkey: %s%s\n", ANSI_YELLOW, cfg->keys.public_key_hex, ANSI_RESET);
#else
fprintf(stderr, "%sThis build was compiled without n_signer client support (NOSTR_ENABLE_NSIGNER_CLIENT). Connectivity check skipped; the agent will fail at startup in this mode.%s\n",
ANSI_RED, ANSI_RESET);
#endif
}
return 0;
}
}

132
src/signer_health.c Normal file
View File

@@ -0,0 +1,132 @@
#define _POSIX_C_SOURCE 200809L
#include "signer_health.h"
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include "../nostr_core_lib/nostr_core/nostr_common.h"
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static signer_health_state_t g_state = SIGNER_HEALTH_UNKNOWN;
static char g_mode[32] = {0};
static char g_last_reason[SIGNER_HEALTH_REASON_LEN] = {0};
static time_t g_last_error_ts = 0;
static time_t g_last_ok_ts = 0;
void signer_health_set_mode(const char* mode) {
pthread_mutex_lock(&g_lock);
if (mode && mode[0]) {
snprintf(g_mode, sizeof(g_mode), "%s", mode);
} else {
g_mode[0] = '\0';
}
pthread_mutex_unlock(&g_lock);
}
void signer_health_reset(void) {
pthread_mutex_lock(&g_lock);
g_state = SIGNER_HEALTH_UNKNOWN;
g_mode[0] = '\0';
g_last_reason[0] = '\0';
g_last_error_ts = 0;
g_last_ok_ts = 0;
pthread_mutex_unlock(&g_lock);
}
/* Classify a nostr error code into a short category label used both for
* the health reason string and for log clarity. The categories map to
* the failure modes called out in Phase 4 item 18:
* transport/IO - network or socket failure talking to n_signer
* auth/policy - n_signer rejected the request (auth envelope, policy)
* crypto - the signer performed work but the crypto op failed
* (e.g. decrypt of malformed ciphertext). This is NOT
* necessarily a signer outage, but we still record it
* so the operator can see recent signer activity.
* unknown - anything else.
*
* Note: nostr_core_lib does not currently expose dedicated nsigner
* transport/auth error codes; remote signer failures surface as
* NOSTR_ERROR_IO_FAILED / NOSTR_ERROR_NETWORK_FAILED (transport) or
* NOSTR_ERROR_CRYPTO_FAILED (the nsigner client maps server-side
* rejections to crypto-failed when it cannot be more specific). We
* treat IO/network as the strong "signer unreachable" signal. */
static const char* classify_rc(int rc) {
if (rc == NOSTR_ERROR_IO_FAILED || rc == NOSTR_ERROR_NETWORK_FAILED) {
return "transport/IO";
}
if (rc == NOSTR_ERROR_CRYPTO_FAILED) {
return "crypto/auth";
}
if (rc == NOSTR_ERROR_MEMORY_FAILED) {
return "resource";
}
if (rc == NOSTR_ERROR_INVALID_INPUT) {
return "invalid-input";
}
return "unknown";
}
void signer_health_record_ok(void) {
int transitioned_from_unhealthy = 0;
pthread_mutex_lock(&g_lock);
time_t now = time(NULL);
if (g_state == SIGNER_HEALTH_UNHEALTHY) {
transitioned_from_unhealthy = 1;
}
g_state = SIGNER_HEALTH_HEALTHY;
g_last_ok_ts = now;
/* Keep last_reason/last_error_ts so the operator can see the most
* recent prior failure even after recovery. */
pthread_mutex_unlock(&g_lock);
if (transitioned_from_unhealthy) {
fprintf(stderr,
"[didactyl] signer health transition: unhealthy -> healthy (mode=%s)\n",
g_mode[0] ? g_mode : "local");
}
}
void signer_health_record_failure(int nostr_rc, const char* detail) {
int transitioned_from_healthy = 0;
char reason[SIGNER_HEALTH_REASON_LEN];
const char* cls = classify_rc(nostr_rc);
if (detail && detail[0]) {
snprintf(reason, sizeof(reason), "%s: %s (rc=%d)", cls, detail, nostr_rc);
} else {
snprintf(reason, sizeof(reason), "%s (rc=%d)", cls, nostr_rc);
}
pthread_mutex_lock(&g_lock);
time_t now = time(NULL);
if (g_state == SIGNER_HEALTH_HEALTHY) {
transitioned_from_healthy = 1;
}
g_state = SIGNER_HEALTH_UNHEALTHY;
snprintf(g_last_reason, sizeof(g_last_reason), "%s", reason);
g_last_error_ts = now;
pthread_mutex_unlock(&g_lock);
if (transitioned_from_healthy) {
fprintf(stderr,
"[didactyl] signer health transition: healthy -> unhealthy "
"(mode=%s, reason=%s)\n",
g_mode[0] ? g_mode : "local",
reason);
}
}
int signer_health_snapshot(signer_health_snapshot_t* out) {
if (!out) {
return -1;
}
pthread_mutex_lock(&g_lock);
out->state = g_state;
snprintf(out->mode, sizeof(out->mode), "%s", g_mode);
snprintf(out->last_reason, sizeof(out->last_reason), "%s", g_last_reason);
out->last_error_ts = g_last_error_ts;
out->last_ok_ts = g_last_ok_ts;
pthread_mutex_unlock(&g_lock);
return 0;
}

59
src/signer_health.h Normal file
View File

@@ -0,0 +1,59 @@
#ifndef DIDACTYL_SIGNER_HEALTH_H
#define DIDACTYL_SIGNER_HEALTH_H
#include <time.h>
/* Signer runtime health tracking (Phase 4 item 18/19).
*
* Lightweight process-global state recording whether the active signer
* provider (local or remote n_signer) is currently considered healthy,
* along with the last error reason and timestamp. This is surfaced via
* the HTTP /api/status endpoint so an operator can detect a signing
* outage out-of-band (without requiring a signed admin DM to come back).
*
* The state is intentionally minimal and lock-protected; it is updated
* from central signer call paths (nostr_handler self-encrypt/decrypt,
* DM encrypt/decrypt, main.c startup connectivity check). It is NOT a
* full health-check daemon: it reflects the outcome of the last signer
* operation that was attempted.
*/
typedef enum {
SIGNER_HEALTH_UNKNOWN = 0, /* no signer operation attempted yet */
SIGNER_HEALTH_HEALTHY = 1,
SIGNER_HEALTH_UNHEALTHY = 2
} signer_health_state_t;
#define SIGNER_HEALTH_REASON_LEN 256
typedef struct {
signer_health_state_t state;
char mode[32]; /* snapshot of cfg.signer.mode */
char last_reason[SIGNER_HEALTH_REASON_LEN]; /* human-readable last error */
time_t last_error_ts; /* unix ts of last unhealthy transition */
time_t last_ok_ts; /* unix ts of last healthy observation */
} signer_health_snapshot_t;
/* Record the configured signer mode at startup. Call once after the
* signer is constructed. Safe to call multiple times. */
void signer_health_set_mode(const char* mode);
/* Mark the signer healthy and record a successful operation timestamp.
* Emits a one-line warning if this is a transition from unhealthy -> healthy. */
void signer_health_record_ok(void);
/* Mark the signer unhealthy with a reason string and the nostr error code
* (from nostr_common.h). The reason is formatted as "<classification>: <detail>".
* Emits a one-line warning if this is a transition from healthy -> unhealthy.
* Pass rc=0 only if you do not have a nostr error code (the detail string
* should then fully describe the failure). */
void signer_health_record_failure(int nostr_rc, const char* detail);
/* Thread-safe snapshot copy for the HTTP status endpoint. Returns 0 on
* success, -1 if out is NULL. */
int signer_health_snapshot(signer_health_snapshot_t* out);
/* Reset state (used by tests / reinit). */
void signer_health_reset(void);
#endif /* DIDACTYL_SIGNER_HEALTH_H */

View File

@@ -117,12 +117,26 @@ char* execute_blossom_upload(tools_context_t* ctx, const char* args_json) {
}
blossom_blob_descriptor_t d;
int rc = blossom_upload_file(server->valuestring,
/* Phase 3 item 16: route the Blossom upload auth/signature through the
* process signer when wired into the tools context so remote signer modes
* keep the nsec out of the agent. Falls back to the legacy raw-key path
* when the signer is NULL (local mode / pre-Phase-3). */
int rc;
if (ctx->signer) {
rc = blossom_upload_file_with_signer(server->valuestring,
full_path,
(content_type && cJSON_IsString(content_type) && content_type->valuestring) ? content_type->valuestring : NULL,
ctx->signer,
30,
&d);
} else {
rc = blossom_upload_file(server->valuestring,
full_path,
(content_type && cJSON_IsString(content_type) && content_type->valuestring) ? content_type->valuestring : NULL,
ctx->cfg->keys.private_key,
30,
&d);
}
cJSON_Delete(args);
if (rc != NOSTR_SUCCESS) return json_error_local("blossom_upload failed");
@@ -235,7 +249,16 @@ char* execute_blossom_delete(tools_context_t* ctx, const char* args_json) {
return json_error_local("blossom_delete requires an https:// server URL");
}
int rc = blossom_delete(server->valuestring, sha->valuestring, ctx->cfg->keys.private_key, 15);
/* Phase 3 item 16: route the Blossom delete auth/signature through the
* process signer when wired into the tools context so remote signer modes
* keep the nsec out of the agent. Falls back to the legacy raw-key path
* when the signer is NULL (local mode / pre-Phase-3). */
int rc;
if (ctx->signer) {
rc = blossom_delete_with_signer(server->valuestring, sha->valuestring, ctx->signer, 15);
} else {
rc = blossom_delete(server->valuestring, sha->valuestring, ctx->cfg->keys.private_key, 15);
}
cJSON_Delete(args);
if (rc != NOSTR_SUCCESS) return json_error_local("blossom_delete failed");

View File

@@ -37,6 +37,20 @@ static int nip44_encrypt_self_local(tools_context_t* ctx, const char* plaintext,
if (!ctx || !ctx->cfg || !out_ciphertext) return -1;
const char* plain = plaintext ? plaintext : "";
/* Phase 3 item 13: route self-encrypt through the process signer when
* wired into the tools context. Falls back to the legacy raw-key path. */
if (ctx->signer) {
char* signer_out = NULL;
int rc = nostr_signer_nip44_encrypt(ctx->signer,
ctx->cfg->keys.public_key_hex,
plain,
&signer_out);
if (rc != NOSTR_SUCCESS || !signer_out) return -1;
*out_ciphertext = signer_out;
return 0;
}
size_t out_cap = (strlen(plain) * 4U) + 1024U;
char* ciphertext = (char*)malloc(out_cap);
if (!ciphertext) return -1;
@@ -58,6 +72,19 @@ static int nip44_encrypt_self_local(tools_context_t* ctx, const char* plaintext,
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;
/* Phase 3 item 13: route self-decrypt through the process signer when
* wired into the tools context. Falls back to the legacy raw-key path. */
if (ctx->signer) {
char* signer_out = NULL;
int rc = nostr_signer_nip44_decrypt(ctx->signer,
ctx->cfg->keys.public_key_hex,
ciphertext,
&signer_out);
if (rc != NOSTR_SUCCESS || !signer_out) return -1;
*out_plaintext = signer_out;
return 0;
}
size_t out_cap = strlen(ciphertext) + 1024U;
char* plaintext = (char*)malloc(out_cap);
if (!plaintext) return -1;

Some files were not shown because too many files have changed in this diff Show More