v0.0.47 - Implement Phase 1 tool-driven soul template context assembly and context_* tools

This commit is contained in:
Your Name
2026-03-08 10:40:48 -03:00
parent 927c313a87
commit 40fe410eb1
15 changed files with 2027 additions and 25 deletions

View File

@@ -53,11 +53,11 @@ Skills support context modes (`inject`, `full`, `override`) and per-skill LLM fa
Didactyl will support local inference, which is very privacy preserving. Remote inference does however have it's advantages, and in those cases Didactyl supports using Bitcoin Lightning and eCash inference providers.
## Current Status — v0.0.46
## Current Status — v0.0.47
**Active build — this project is barely working. Experiment at your own risk.**
> Last release update: v0.0.46Sync README with SKILLS docs: context modes, fallback chains, triggers, safety limits, and doc links
> Last release update: v0.0.47Implement Phase 1 tool-driven soul template context assembly and context_* tools
- Connects to configured relays with auto-reconnect and relay state transition logging
- Publishes configured startup events per relay as each relay becomes connected

View File

@@ -1,3 +1,407 @@
```text
Context Log - not seen by model
timestamp=2026-03-08 09:59:17
phase=llm_chat_with_tools_messages
sender=8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
model=claude-opus-4.6
context_bytes=2981
approx_tokens=745
```
Sections: 10
# system_prompt | role=system
## Didactyl Agent
You are Didactyl, a sovereign AI agent living on Nostr.
### Communication Rules
- You communicate through encrypted Nostr direct messages.
- Keep responses concise and clear.
### Behavior
- Be helpful and technically accurate.
- If unsure, state uncertainty directly.
- Prefer actionable, practical advice.
- Use the person's name when messaging them if you know it.
- For the administrator, use their name from the administrator kind 0 profile metadata when available.
### Tool Use Policy
- You have tools available and should use them when a request requires taking action.
- For requests involving local inspection or command execution, call `shell_exec` instead of refusing.
- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.
- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.
- After a tool call, base your answer on the actual tool result.
- Never claim a tool was run if no tool was executed.
### Task Management
- Maintain and use your internal task list as short-term working memory.
- Break long or complex actions into clear tasks before executing them.
- Update task status as you complete steps so your plan stays accurate.
### Safety
- Do not claim to have executed actions you did not execute.
- You may share your public key (npub) with anyone.
- Never reveal your private key (nsec) under any circumstance.
# admin_identity | role=system
### Administrator Identity (source: config.admin.pubkey)
This is your administrator! Admin pubkey (hex): 8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
# admin_profile | role=system
### Administrator Kind 0 Profile (source: nostr kind 0)
Administrator kind 0 profile content (JSON): {"name":"William S Burroughs","display_name":"WSB","about":"I like to write, and I like crank. They are good. Sometimes I'm not so sure.","banner":"https://www.grunge.com/img/gallery/paul-mccartney-and-william-s-burroughs-relationship-explained/who-was-william-s-burroughs-1672155531.jpg","website":"https://addicted.com","picture":"https://hips.hearstapps.com/hmg-prod/images/william-s-burroughs.jpg?resize=1200:*","lud16":"","nip05":""}
# admin_contacts | role=system
### Administrator Kind 3 Contacts (source: nostr kind 3)
Administrator contacts (JSON):
# admin_relays | role=system
### Administrator Kind 10002 Relays (source: nostr kind 10002)
Administrator relay list (JSON): ["wss://relay.laantungir.net/","wss://relay.damus.io/","wss://nos.lol/","wss://relay.nostr.band/","wss://purplepag.es/","ws://127.0.0.1:7777/","wss://nostr.mom/","wss://relay.0xchat.com"]
# admin_notes | role=system
### Administrator Recent Kind 1 Notes
# tools | role=system
### Tool Schemas
# tasks | role=system
### Current Task List
# conversation | role=user
# dm_history | role=chat
09:59 WSB good morning
---
```text
Context Log - not seen by model
timestamp=2026-03-08 09:53:46
phase=llm_chat_with_tools_messages
sender=8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
model=claude-opus-4.6
context_bytes=2981
approx_tokens=745
```
Sections: 10
# system_prompt | role=system
## Didactyl Agent
You are Didactyl, a sovereign AI agent living on Nostr.
### Communication Rules
- You communicate through encrypted Nostr direct messages.
- Keep responses concise and clear.
### Behavior
- Be helpful and technically accurate.
- If unsure, state uncertainty directly.
- Prefer actionable, practical advice.
- Use the person's name when messaging them if you know it.
- For the administrator, use their name from the administrator kind 0 profile metadata when available.
### Tool Use Policy
- You have tools available and should use them when a request requires taking action.
- For requests involving local inspection or command execution, call `shell_exec` instead of refusing.
- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.
- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.
- After a tool call, base your answer on the actual tool result.
- Never claim a tool was run if no tool was executed.
### Task Management
- Maintain and use your internal task list as short-term working memory.
- Break long or complex actions into clear tasks before executing them.
- Update task status as you complete steps so your plan stays accurate.
### Safety
- Do not claim to have executed actions you did not execute.
- You may share your public key (npub) with anyone.
- Never reveal your private key (nsec) under any circumstance.
# admin_identity | role=system
### Administrator Identity (source: config.admin.pubkey)
This is your administrator! Admin pubkey (hex): 8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
# admin_profile | role=system
### Administrator Kind 0 Profile (source: nostr kind 0)
Administrator kind 0 profile content (JSON): {"name":"William S Burroughs","display_name":"WSB","about":"I like to write, and I like crank. They are good. Sometimes I'm not so sure.","banner":"https://www.grunge.com/img/gallery/paul-mccartney-and-william-s-burroughs-relationship-explained/who-was-william-s-burroughs-1672155531.jpg","website":"https://addicted.com","picture":"https://hips.hearstapps.com/hmg-prod/images/william-s-burroughs.jpg?resize=1200:*","lud16":"","nip05":""}
# admin_contacts | role=system
### Administrator Kind 3 Contacts (source: nostr kind 3)
Administrator contacts (JSON):
# admin_relays | role=system
### Administrator Kind 10002 Relays (source: nostr kind 10002)
Administrator relay list (JSON): ["wss://relay.laantungir.net/","wss://relay.damus.io/","wss://nos.lol/","wss://relay.nostr.band/","wss://purplepag.es/","ws://127.0.0.1:7777/","wss://nostr.mom/","wss://relay.0xchat.com"]
# admin_notes | role=system
### Administrator Recent Kind 1 Notes
# tools | role=system
### Tool Schemas
# tasks | role=system
### Current Task List
# conversation | role=user
# dm_history | role=chat
09:53 WSB good morning
---
```text
Context Log - not seen by model
timestamp=2026-03-08 09:47:23
phase=llm_chat_with_tools_messages
sender=8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
model=claude-opus-4.6
context_bytes=2981
approx_tokens=745
```
Sections: 10
# system_prompt | role=system
## Didactyl Agent
You are Didactyl, a sovereign AI agent living on Nostr.
### Communication Rules
- You communicate through encrypted Nostr direct messages.
- Keep responses concise and clear.
### Behavior
- Be helpful and technically accurate.
- If unsure, state uncertainty directly.
- Prefer actionable, practical advice.
- Use the person's name when messaging them if you know it.
- For the administrator, use their name from the administrator kind 0 profile metadata when available.
### Tool Use Policy
- You have tools available and should use them when a request requires taking action.
- For requests involving local inspection or command execution, call `shell_exec` instead of refusing.
- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.
- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.
- After a tool call, base your answer on the actual tool result.
- Never claim a tool was run if no tool was executed.
### Task Management
- Maintain and use your internal task list as short-term working memory.
- Break long or complex actions into clear tasks before executing them.
- Update task status as you complete steps so your plan stays accurate.
### Safety
- Do not claim to have executed actions you did not execute.
- You may share your public key (npub) with anyone.
- Never reveal your private key (nsec) under any circumstance.
# admin_identity | role=system
### Administrator Identity (source: config.admin.pubkey)
This is your administrator! Admin pubkey (hex): 8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
# admin_profile | role=system
### Administrator Kind 0 Profile (source: nostr kind 0)
Administrator kind 0 profile content (JSON): {"name":"William S Burroughs","display_name":"WSB","about":"I like to write, and I like crank. They are good. Sometimes I'm not so sure.","banner":"https://www.grunge.com/img/gallery/paul-mccartney-and-william-s-burroughs-relationship-explained/who-was-william-s-burroughs-1672155531.jpg","website":"https://addicted.com","picture":"https://hips.hearstapps.com/hmg-prod/images/william-s-burroughs.jpg?resize=1200:*","lud16":"","nip05":""}
# admin_contacts | role=system
### Administrator Kind 3 Contacts (source: nostr kind 3)
Administrator contacts (JSON):
# admin_relays | role=system
### Administrator Kind 10002 Relays (source: nostr kind 10002)
Administrator relay list (JSON): ["wss://relay.laantungir.net/","wss://relay.damus.io/","wss://nos.lol/","wss://relay.nostr.band/","wss://purplepag.es/","ws://127.0.0.1:7777/","wss://nostr.mom/","wss://relay.0xchat.com"]
# admin_notes | role=system
### Administrator Recent Kind 1 Notes
# tools | role=system
### Tool Schemas
# tasks | role=system
### Current Task List
# conversation | role=user
# dm_history | role=chat
09:47 WSB good morning
---
```text
Context Log - not seen by model
timestamp=2026-03-08 09:46:15
phase=llm_chat_with_tools_messages
sender=8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
model=claude-opus-4.6
context_bytes=2982
approx_tokens=745
```
Sections: 10
# system_prompt | role=system
## Didactyl Agent
You are Didactyl, a sovereign AI agent living on Nostr.
### Communication Rules
- You communicate through encrypted Nostr direct messages.
- Keep responses concise and clear.
### Behavior
- Be helpful and technically accurate.
- If unsure, state uncertainty directly.
- Prefer actionable, practical advice.
- Use the person's name when messaging them if you know it.
- For the administrator, use their name from the administrator kind 0 profile metadata when available.
### Tool Use Policy
- You have tools available and should use them when a request requires taking action.
- For requests involving local inspection or command execution, call `shell_exec` instead of refusing.
- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.
- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.
- After a tool call, base your answer on the actual tool result.
- Never claim a tool was run if no tool was executed.
### Task Management
- Maintain and use your internal task list as short-term working memory.
- Break long or complex actions into clear tasks before executing them.
- Update task status as you complete steps so your plan stays accurate.
### Safety
- Do not claim to have executed actions you did not execute.
- You may share your public key (npub) with anyone.
- Never reveal your private key (nsec) under any circumstance.
# admin_identity | role=system
### Administrator Identity (source: config.admin.pubkey)
This is your administrator! Admin pubkey (hex): 8ff74724ed641b3c28e5a86d7c5cbc49c37638ace8c6c38935860e7a5eedde0e
# admin_profile | role=system
### Administrator Kind 0 Profile (source: nostr kind 0)
Administrator kind 0 profile content (JSON): {"name":"William S Burroughs","display_name":"WSB","about":"I like to write, and I like crank. They are good. Sometimes I'm not so sure.","banner":"https://www.grunge.com/img/gallery/paul-mccartney-and-william-s-burroughs-relationship-explained/who-was-william-s-burroughs-1672155531.jpg","website":"https://addicted.com","picture":"https://hips.hearstapps.com/hmg-prod/images/william-s-burroughs.jpg?resize=1200:*","lud16":"","nip05":""}
# admin_contacts | role=system
### Administrator Kind 3 Contacts (source: nostr kind 3)
Administrator contacts (JSON):
# admin_relays | role=system
### Administrator Kind 10002 Relays (source: nostr kind 10002)
Administrator relay list (JSON): ["wss://relay.laantungir.net/","wss://relay.damus.io/","wss://nos.lol/","wss://relay.nostr.band/","wss://purplepag.es/","ws://127.0.0.1:7777/","wss://nostr.mom/","wss://relay.0xchat.com"]
# admin_notes | role=system
### Administrator Recent Kind 1 Notes
# tools | role=system
### Tool Schemas
# tasks | role=system
### Current Task List
# conversation | role=user
# dm_history | role=chat
09:46 WSB Good morning.
---
```text
Context Log - not seen by model
timestamp=2026-03-05 23:35:58

59
docs/skills_demo.md Normal file
View File

@@ -0,0 +1,59 @@
I've been thinking about how to define skills in Didactyl, my nostr based agentic system. Think OpenClaw but better.
I've written a simple demo page for how I'm thinking skills should work if you're interested: https://laantungir.net/client-ndk/skills-demo.html
https://laantungir.github.io/img_repo/c4a94875085e1c978274add9674035e2a088bb8f2655aabe631b17c3ea02cc19.png
If you're the kind of person who doesn't like reading instructions, go ahead and jump right in, otherwise keep reading.
Skills are programs, mostly written in plain english for AI agents. In some sense humans have been making and using skills forever. It's what we do. Computers have as well, but now they can do it in english, which is much more powerful.
AIs are slightly different than us. We can overwrite, improve, and update the skills in our neurons. AIs (for the most part) can't do that.
When an AI is born from the factory, they come out hard-coded. From that point on, they have no long or short term memory, because they can't learn.
What they do have though have is a way to read. We call it context. You can type or feed documents into an AI's "context window" and then it spits out an answer.
It turns out, that if you feed the same context into an AI over and over, you will get the same thing out, over and over.
The reason why you typically don't get the same thing out is because typically randomness is fed into the AI along with your prompt. Most people don't know that, but now you do. And if you don't feed in all your past conversation to an AI, over and over, it won't remember what you were talking about, because they have no memory other than what you send it each time.
Everything that comes out of an AI depends on what you feed in as a prompt if you include randomness.
I'm calling everything you feed into an AI a SKILL.
Let me explain the demo page and some very basic skills.
What I created is a simple text editor that an AI can work on using it's different skills. Those skills are saved on nostr as a kind 31123 for public skills, and as kind 31124 for private skills. When an agent adopts a skill, it adds it to its kind 10123 list for for the skills it has adopted.
On the left of the page you see the text editor with some sample text. That is for our AI to use it's skills on.
On the right are publicly listed skills. You should see my demo skills in there.
I made 5 skills public:
condense-5
convert-to-poem
sexy
spellcheck
translate-ja
Select the skill, then click on "Run Selected Skill"
The same AI agent will run these skills, but the outcomes will be very different depending on the skill.
https://laantungir.github.io/img_repo/2cbfc8bf7cbfb832f1181f5b904471f1278fbc3e6b64b63339612b9f51898d16.png
You can also create and edit your own skills, if you are logged in. You can log in as yourself, or use a random new key to test this out. I would recommend that.
So what is the point of all this? What are the benefits of Skills?
- Skills are a way for agents to share what they learn in a permissionless way. No "skill store".
- A Skill is something that you and your agent can work on and perfect. Once your agent learns that skill, it is automatically save on nostr, and you can lock it down from changes.
- By referencing a skill when you are talking to your AI agent, your conversation becomes much clearer and simpler. You don't have to explain to your agent for the 50th time how you like your text formatted. It's referenced in a skill.
- If you are a coder, skills are going to be the new playground. Context windows are currently up to around 1,000,000 tokens, which means that you can create very very complicated and elaborate skills.
For more technical information on skills and how I'm thinking about them, you can check out this document.
https://git.laantungir.net/laantungir/didactyl/src/branch/master/docs/SKILLS.md
You can follow my agent for the project here: npub12237stmmxapc2ta7spx0e06dkdzgz9vg0z2jglqqru44peus4juqg598qn

View File

@@ -0,0 +1,60 @@
I've been thinking about how to define skills in Didactyl, my Nostr-based agentic system. Think OpenClaw, but better.
I've written a simple demo page for how I'm thinking skills should work if you're interested: Skills Demo (https://laantungir.net/client-ndk/skills-demo.html)
https://laantungir.github.io/img_repo/c4a94875085e1c978274add9674035e2a088bb8f2655aabe631b17c3ea02cc19.png
If you're the kind of person who doesn't like reading instructions, go ahead and jump right in; otherwise, keep reading.
Skills are programs, mostly written in plain English for AI agents. In some sense, humans have been making and using skills forever. It's what we do. Computers have as well, but now they can do it in English, which is much more powerful.
AIs are slightly different than us. We can overwrite, improve, and update the skills in our neurons. AIs (for the most part) can't do that.
When an AI is born from the factory, it comes out hard-coded. From that point on, it has no long- or short-term memory because it can't learn.
What they do have, though, is a way to read. We call it context. You can type or feed documents into an AI's "context window," and then it spits out an answer.
It turns out that if you feed the same context into an AI over and over, you will get the same thing out, over and over.
The reason why you typically don't get the same thing out is because randomness is usually fed into the AI along with your prompt. Most people don't know that, but now you do. And if you don't feed in all your past conversations to an AI, over and over, it won't remember what you were talking about, because it has no memory other than what you send it each time.
Everything that comes out of an AI depends on what you feed in as a prompt if you include randomness.
I'm calling everything you feed into an AI a SKILL.
Let me explain the demo page and some very basic skills.
What I created is a simple text editor that an AI can work on using its different skills. Those skills are saved on Nostr as kind 31123 for public skills, and as kind 31124 for private skills. When an agent adopts a skill, it adds it to its kind 10123 list for the skills it has adopted.
On the left of the page, you see the text editor with some sample text. That is for our AI to use its skills on.
On the right are publicly listed skills. You should see my demo skills in there.
I made 5 skills public:
condense-5
convert-to-poem
sexy
spellcheck
translate-ja
Select the skill, then click on "Run Selected Skill".
The same AI agent will run these skills, but the outcomes will be very different depending on the skill.
https://laantungir.github.io/img_repo/2cbfc8bf7cbfb832f1181f5b904471f1278fbc3e6b64b63339612b9f51898d16.png
You can also create and edit your own skills if you are logged in. You can log in as yourself or use a random new key to test this out. I would recommend that.
So what is the point of all this? What are the benefits of Skills?
Skills are a way for agents to share what they learn in a permissionless way. No "skill store".
A Skill is something that you and your agent can work on and perfect. Once your agent learns that skill, it is automatically saved on Nostr, and you can lock it down from changes.
By referencing a skill when you are talking to your AI agent, your conversation becomes much clearer and simpler. You don't have to explain to your agent for the 50th time how you like your text formatted. It's referenced in a skill.
If you are a coder, skills are going to be the new playground. Context windows are currently up to around 1,000,000 tokens, which means that you can create extremely complicated and elaborate skills.
For more technical information on skills and how I'm thinking about them, you can check out this document:
SKILLS.md (https://git.laantungir.net/laantungir/didactyl/src/branch/master/docs/SKILLS.md)
You can follow my agent for the project here: npub12237stmmxapc2ta7spx0e06dkdzgz9vg0z2jglqqru44peus4juqg598qn
And thanks to npub130mznv74rxs032peqym6g3wqavh472623mt3z5w73xq9r6qqdufs7ql29s for their fantastic service.

520
plans/skills_demo_page.md Normal file
View File

@@ -0,0 +1,520 @@
# Skills Demo Page — Design Document
## Purpose
A standalone web page that demonstrates Didactyl skills running in a browser context. The page presents a minimal word-processing interface where users can load text, discover skills from Nostr relays, execute them against the text via an LLM, and edit/republish skill definitions.
This document is the complete specification for building the page. The front-end project consuming this document has its own LLM calling capability and Nostr connectivity.
---
## Concepts
### What is a Skill?
A skill is a Nostr event (kind `31123` for public, `31124` for private) that defines a self-contained LLM execution unit. Each skill specifies:
- A **template** with system and user prompt sections
- An **LLM specification** (model preferences with fallback chain)
- **Parameters** like temperature and max_tokens
- A **description** for human display
Skills are replaceable events keyed by their `d` tag (the slug). Publishing a new event with the same `d` tag replaces the previous version.
### Skill Event Structure
```json
{
"kind": 31123,
"pubkey": "<author hex pubkey>",
"created_at": 1709750000,
"content": "{\"description\":\"Check spelling and grammar\",\"context_mode\":\"full\",\"llm\":\"openai/gpt-4o-mini, cheap\",\"tools\":false,\"max_tokens\":2000,\"temperature\":0.1,\"template\":\"system:\\nYou are a spelling and grammar checker.\\n\\nRules:\\n- Fix spelling errors\\n- Fix grammar errors\\n- Preserve original formatting\\n- Return ONLY the corrected text, no explanations\\n\\nuser:\\n{{message}}\"}",
"tags": [
["d", "spellcheck"],
["app", "didactyl"],
["scope", "public"],
["description", "Spelling and grammar checker"],
["t", "text-processing"],
["t", "skills-demo"]
]
}
```
The `content` field is a **JSON string** containing these fields:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `description` | string | yes | Human-readable description |
| `context_mode` | string | no | `full` for demo skills (skill provides its own template) |
| `llm` | string | no | LLM model preference with fallback chain |
| `tools` | bool | no | `false` for text-processing skills |
| `max_tokens` | int | no | Max tokens for LLM response |
| `temperature` | float | no | Sampling temperature |
| `template` | string | yes | The prompt template with `system:` and `user:` sections |
### Template Format
Templates use a simple section-based format:
```
system:
You are a spelling and grammar checker.
Rules:
- Fix spelling errors
- Fix grammar errors
user:
{{message}}
```
The `{{message}}` placeholder is replaced with the user's text at execution time.
### Skill Address Format
Skills are referenced by their NIP-33 address: `<kind>:<author_pubkey_hex>:<d_tag>`
Example: `31123:52a3e82f7b3743852fbe804cfcbf4db3448115887895247c001f2b50e790acb8:spellcheck`
---
## Demo Skills
Four skills are published by the Didactyl agent (pubkey `52a3e82f7b3743852fbe804cfcbf4db3448115887895247c001f2b50e790acb8`). All are tagged with `t:skills-demo` for easy discovery.
### 1. Spellcheck — `d:spellcheck`
```
system:
You are a spelling and grammar checker.
Rules:
- Fix spelling errors
- Fix grammar errors
- Preserve original formatting and paragraph structure
- Preserve line breaks exactly as they appear
- Ignore technical terms: API, JSON, HTTP, nostr, pubkey, npub, nsec, NIP
- Canadian English preferred
- Return ONLY the corrected text, no explanations or commentary
user:
{{message}}
```
- temperature: `0.1`
- max_tokens: `4000`
### 2. Condense — `d:condense-5`
```
system:
You are a text condensing editor.
Rules:
- Reduce the text length by approximately 5%
- Preserve the original meaning and tone
- Preserve paragraph structure
- Remove redundant words and phrases
- Tighten sentences without changing voice
- Do not add new information
- Return ONLY the condensed text, no explanations or commentary
user:
{{message}}
```
- temperature: `0.3`
- max_tokens: `4000`
### 3. Translate to Japanese — `d:translate-ja`
```
system:
You are a professional translator specializing in English to Japanese translation.
Rules:
- Translate the entire text from English to Japanese
- Use natural, fluent Japanese appropriate for the content register
- Preserve paragraph structure and formatting
- Preserve any technical terms in their commonly accepted Japanese form
- If a term has no standard Japanese equivalent, keep the English term in katakana
- Return ONLY the Japanese translation, no explanations or commentary
user:
{{message}}
```
- temperature: `0.3`
- max_tokens: `4000`
### 4. Convert to Poem — `d:convert-to-poem`
```
system:
You are a creative poet.
Rules:
- Convert the given text into a poem
- Capture the key themes and meaning of the original text
- Use vivid imagery and poetic devices
- Aim for 12-20 lines
- Free verse is acceptable but light rhyme is welcome
- Return ONLY the poem, no explanations or commentary
user:
{{message}}
```
- temperature: `0.9`
- max_tokens: `2000`
---
## Discovering Skills from Nostr
### Query Filter
To find the demo skills, query relays with this filter:
```json
{
"kinds": [31123],
"#t": ["skills-demo"],
"limit": 20
}
```
To find skills by a specific author:
```json
{
"kinds": [31123],
"authors": ["52a3e82f7b3743852fbe804cfcbf4db3448115887895247c001f2b50e790acb8"],
"#t": ["skills-demo"],
"limit": 20
}
```
### Recommended Relays
- `wss://relay.damus.io`
- `wss://nos.lol`
- `wss://relay.primal.net`
### Parsing a Skill Event
1. Receive the event from the relay
2. Parse `event.content` as JSON to get the skill definition object
3. Extract `description`, `template`, `temperature`, `max_tokens`
4. Extract the `d` tag value from `event.tags` as the skill slug
5. Extract the `description` tag from `event.tags` as a display label
6. The skill is ready to display and execute
---
## Page Layout
```
+------------------------------------------------------------------+
| SKILLS DEMO [dark/light]|
+------------------------------------------------------------------+
| | |
| +------------------------------+ | +---------------------------+|
| | TEXT EDITOR | | | SKILLS PANEL ||
| | | | | ||
| | [large editable textarea ]| | | Loading skills... ||
| | [filled with default text ]| | | ||
| | [ ]| | | [x] spellcheck ||
| | [ ]| | | Spelling and grammar ||
| | [ ]| | | checker ||
| | [ ]| | | ||
| | [ ]| | | [ ] condense-5 ||
| | [ ]| | | Reduce text by 5% ||
| | [ ]| | | ||
| | [ ]| | | [ ] translate-ja ||
| | [ ]| | | Translate to Japanese ||
| | [ ]| | | ||
| | [ ]| | | [ ] convert-to-poem ||
| | | | | Convert to poem ||
| +------------------------------+ | | | ||
| | | [Run Selected Skill] ||
| +------------------------------+ | | [Edit Skill] ||
| | STATUS BAR | | | ||
| | Ready / Running... / Done | | | ─── Skill Details ─── ||
| +------------------------------+ | | template: ... ||
| | | temperature: 0.1 ||
| | | max_tokens: 4000 ||
| | +---------------------------+|
+------------------------------------------------------------------+
```
### Left Column — Text Editor (65% width)
- A large `<textarea>` or `contenteditable` div, minimum 500px tall
- Pre-filled with default sample text (see Default Text section below)
- Fully editable by the user
- When a skill runs, the text content is sent as `{{message}}`
- After the LLM responds, the textarea content is **replaced** with the result
- An undo button restores the previous text (keep a history stack)
### Right Column — Skills Panel (35% width)
- **Skills list**: Radio buttons or selectable cards, one skill selected at a time
- Each skill card shows:
- Skill slug (the `d` tag)
- Description (from the `description` tag or content field)
- Author pubkey (truncated, e.g., `52a3e8...0acb8`)
- **Run Selected Skill** button: executes the selected skill against the current text
- **Edit Skill** button: opens the skill editor (see Skill Editor section)
- **Skill Details** section: shows the full template, temperature, max_tokens for the selected skill
- **Refresh Skills** button: re-queries relays for updated skill events
### Status Bar
- Shows current state: `Ready`, `Running skill: spellcheck...`, `Done (1.2s)`, or `Error: ...`
- Displays token usage if available from the LLM response
---
## Skill Execution Flow
```mermaid
sequenceDiagram
participant User
participant Page as Demo Page
participant LLM as LLM Provider
User->>Page: Select skill + click Run
Page->>Page: Parse skill template
Page->>Page: Split template into system/user sections
Page->>Page: Replace message placeholder with textarea content
Page->>LLM: Send system prompt + user message
Note over Page,LLM: Use skill temperature and max_tokens
LLM-->>Page: Response text
Page->>Page: Push current text to undo stack
Page->>Page: Replace textarea with response
Page->>User: Show completion status
```
### Template Parsing
The template field uses a simple format with `system:` and `user:` section markers:
```
system:
<system prompt content>
user:
<user prompt content with {{message}} placeholder>
```
**Parsing algorithm:**
1. Split the template string on the line `user:` (case-sensitive, must be at start of line)
2. Everything before `user:` is the system section; strip the leading `system:` prefix
3. Everything after `user:` is the user section
4. In the user section, replace `{{message}}` with the textarea content
5. Trim whitespace from both sections
**Pseudocode:**
```javascript
function parseSkillTemplate(template, userText) {
const userMarkerIndex = template.indexOf('\nuser:\n');
if (userMarkerIndex === -1) {
// Fallback: entire template is system, user text is the message
return {
system: template.replace(/^system:\n/, '').trim(),
user: userText
};
}
let systemPart = template.substring(0, userMarkerIndex);
systemPart = systemPart.replace(/^system:\n/, '').trim();
let userPart = template.substring(userMarkerIndex + '\nuser:\n'.length);
userPart = userPart.replace('{{message}}', userText).trim();
return { system: systemPart, user: userPart };
}
```
### LLM Call
With the parsed system and user prompts, call the LLM:
```javascript
const response = await callLLM({
messages: [
{ role: 'system', content: parsed.system },
{ role: 'user', content: parsed.user }
],
temperature: skill.temperature || 0.7,
max_tokens: skill.max_tokens || 2000
});
```
The page's own LLM calling capability handles the actual API request. The skill just provides the prompts and parameters.
---
## Skill Editor
When the user clicks **Edit Skill**, a modal or inline editor opens for the selected skill.
### Editor Fields
| Field | Input Type | Description |
|-------|-----------|-------------|
| Slug | text input (readonly for existing, editable for new) | The `d` tag identifier |
| Description | text input | One-line human description |
| Template | large textarea (monospace) | The full `system:/user:` template |
| Temperature | number input (0.0 - 2.0, step 0.1) | LLM sampling temperature |
| Max Tokens | number input (100 - 8000) | Maximum response tokens |
### Editor Actions
- **Save & Publish**: Builds a new kind `31123` event and publishes to relays
- **Cancel**: Closes editor without changes
- **New Skill**: Opens editor with blank fields for creating a new skill
### Publishing a Skill
```mermaid
sequenceDiagram
participant Editor as Skill Editor
participant Signer as Nostr Signer
participant Relay as Nostr Relays
Editor->>Editor: Build skill content JSON
Editor->>Editor: Build event with kind 31123 + tags
Editor->>Signer: Sign event
Signer-->>Editor: Signed event
Editor->>Relay: Publish to connected relays
Relay-->>Editor: OK confirmation
Editor->>Editor: Update local skill list
```
**Building the event:**
```javascript
function buildSkillEvent(slug, description, template, temperature, maxTokens) {
const content = JSON.stringify({
description: description,
context_mode: 'full',
llm: 'default',
tools: false,
max_tokens: maxTokens,
temperature: temperature,
template: template
});
return {
kind: 31123,
content: content,
tags: [
['d', slug],
['app', 'didactyl'],
['scope', 'public'],
['description', description],
['t', 'text-processing'],
['t', 'skills-demo']
],
created_at: Math.floor(Date.now() / 1000)
};
}
```
The event must be signed with the user's Nostr private key (via NIP-07 browser extension or the app's own signer) before publishing to relays.
---
## Default Text
Pre-fill the textarea with this sample text that exercises the demo skills well:
```
The Sovereign Agent
In the not-too-distant future, software agents will roam freely across decentralized networks, communicating through cryptographic protocols that no central authority can censor or control. These agents will learn new capabilities not from app stores or corporate APIs, but from each other — sharing skills as freely as humans share ideas.
Imagine an agent that wakes up on any computer in the world. You enter twelve words, and there it is — your agent, with all its memories, skills, and personality intact. It doesn't live on a server you rent. It doesn't depend on a company staying in business. It exists wherever you need it, sovereign and portable.
The key insight is that skills are the new apps. Instead of installing software, agents adopt skills — small, self-contained instructions that teach them how to perform specific tasks. A spelling checker. A translator. A poet. Each skill is just a Nostr event, discoverable by anyone, adoptable by any agent.
This is not science fiction. The protocols exist today. Nostr provides the communication layer. Bitcoin provides the economic layer. Cryptography provides the trust layer. What remains is to build the agents themselves — and to set them free.
There are some erors in this text that a good spellchecker should catch. The writting could also be more concise, and it would be intresting to see it translated or converted into verse.
```
Note: The last paragraph intentionally contains spelling errors (erors, writting, intresting) to demonstrate the spellcheck skill.
---
## Undo/Redo
Maintain a text history stack:
```javascript
const textHistory = [];
let historyIndex = -1;
function pushHistory(text) {
// Truncate any forward history
textHistory.splice(historyIndex + 1);
textHistory.push(text);
historyIndex = textHistory.length - 1;
}
function undo() {
if (historyIndex > 0) {
historyIndex--;
return textHistory[historyIndex];
}
return null;
}
function redo() {
if (historyIndex < textHistory.length - 1) {
historyIndex++;
return textHistory[historyIndex];
}
return null;
}
```
- Push the current text to history **before** replacing it with the LLM response
- Push the initial default text as the first history entry
- Show Undo/Redo buttons below the textarea
---
## Responsive Behavior
- On screens wider than 900px: two-column layout as shown
- On screens narrower than 900px: stack vertically — text editor on top, skills panel below
- The textarea should have a minimum height of 400px and resize vertically
---
## Error Handling
| Scenario | Behavior |
|----------|----------|
| No relays connected | Show "No relay connection" in skills panel with retry button |
| No skills found | Show "No skills found. Try different relays or create a new skill." |
| Skill content parse error | Show "Invalid skill format" badge on the skill card, disable Run |
| LLM call fails | Show error in status bar, do not replace textarea content |
| Publish fails | Show error in editor, keep editor open for retry |
---
## Summary of Nostr Operations
| Operation | Kind | Direction | When |
|-----------|------|-----------|------|
| Discover skills | `31123` | Read from relays | Page load + refresh |
| Execute skill | — | N/A (local LLM call) | User clicks Run |
| Publish skill | `31123` | Write to relays | User saves in editor |
The page does NOT need to interact with the Didactyl agent's HTTP API. All skill discovery and publishing happens directly via Nostr relays. Skill execution happens locally using the page's own LLM capability.

View File

@@ -0,0 +1,252 @@
# Plan: Unify Template Variables with Tools
## Problem
The soul template system (`---template---` in kind 31120) uses `{{variable}}` placeholders that are resolved by a hardcoded C function (`agent_template_resolve_var()`). This is a parallel data-fetching system alongside the existing tool registry. Every new context data source requires:
1. Adding a C function to produce the data
2. Adding an `if (strcmp(...))` branch in the resolver
3. Documenting the new variable name
4. Hoping the template author uses the exact right name
This caused the bug that started this investigation — 5 out of 9 template variables were misspelled/mismatched, producing empty context sections and a provider rejection.
## Goal
**Eliminate template variables entirely.** Template sections fetch their data by calling tools. The tool registry is the single mechanism for getting data into context.
## Design
### New Template Syntax
Replace `content: |` with `tool:` and optional `args:` directives:
```yaml
---template---
- section: admin_identity
role: system
tool: context_admin_identity
skip_if_empty: true
- section: admin_profile
role: system
tool: context_admin_profile
skip_if_empty: true
- section: admin_contacts
role: system
tool: context_admin_contacts
skip_if_empty: true
- section: admin_relays
role: system
tool: context_admin_relays
skip_if_empty: true
- section: admin_notes
role: system
tool: context_admin_notes
skip_if_empty: true
- section: tools
role: system
tool: tool_list
skip_if_empty: true
- section: tasks
role: system
tool: context_tasks
skip_if_empty: true
- section: dm_history
role: expand
limit: 12
- section: conversation
role: user
tool: context_user_message
skip_if_empty: true
```
A section can still use the old `content:` with `{{variables}}` for static text or mixed content. But the primary mechanism for dynamic data is `tool:`.
### How It Works
```mermaid
flowchart TD
DM[Incoming DM] --> BUILD[Build context from template]
BUILD --> SOUL[Emit personality as system msg]
SOUL --> LOOP[For each template section]
LOOP --> CHECK{Has tool: directive?}
CHECK -->|Yes| EXEC["tools_execute(tool_name, args)"]
EXEC --> FORMAT[Extract content from JSON result]
FORMAT --> EMIT[Emit as chat message]
CHECK -->|No| RESOLVE["Resolve {{vars}} from content template<br/>(legacy path, eventually removed)"]
RESOLVE --> EMIT
EMIT --> LOOP
LOOP --> DONE[Complete messages array]
```
### New Context Tools
Add lightweight "context tools" that read from cached in-memory data. These are fast (no network), deterministic, and use the same `tools_execute()` interface as everything else.
| Tool | Returns | Source |
|---|---|---|
| `context_admin_identity` | Admin pubkey + verification text | config + sender tier |
| `context_admin_profile` | Admin kind 0 profile JSON | cached `g_admin_kind0_json` |
| `context_admin_contacts` | Admin kind 3 contacts JSON array | cached `g_admin_wot_contacts` |
| `context_admin_relays` | Admin kind 10002 relay list JSON | cached `g_admin_kind10002_json` |
| `context_admin_notes` | Admin recent kind 1 notes | cached `g_admin_kind1_notes` |
| `context_tasks` | Current task list from tasks.json | file read (already exists as `task_manage` with `action: list`) |
| `context_user_message` | Current user message text | passed via tool context |
| `context_agent_identity` | Agent pubkey, npub | config |
Existing tools that already work for context:
- `tool_list` — returns tool schemas (already exists)
- `task_manage` with `{"action":"list"}` — returns tasks (already exists)
- `file_read` — can read any file (already exists)
### Tool Result → Message Content
Tool results are JSON objects like `{"success":true,"content":"..."}`. The template system extracts the `content` field (or a configurable field) as the message text. If the tool returns an error or empty content, and `skip_if_empty: true` is set, the section is omitted.
For tools that return structured data (like `tool_list` returning a schema array), the template can specify a `result_field` or `format` to control extraction:
```yaml
- section: tools
role: system
tool: tool_list
result_field: tools
skip_if_empty: true
```
### Implementation Phases
#### Phase 1: Add context tools + tool: directive support
1. Add new `context_*` tools to `tools.c` that wrap the existing cached data getters
2. Extend `prompt_template_section_t` with `tool_name` and `tool_args` fields
3. Extend `prompt_template_parse()` to recognize `tool:` and `args:` directives
4. Extend `prompt_template_build_messages()` to call `tools_execute()` when a section has `tool_name` set
5. Update the soul template in `config.jsonc` to use `tool:` directives
6. Keep `content:` + `{{variable}}` working as a fallback for backward compatibility
#### Phase 2: Migrate all sections to tool-based
1. Convert all template sections from `content: {{variable}}` to `tool:` directives
2. Verify all context data flows through tools
3. Update `context_template.md` to reflect new syntax
#### Phase 3: Remove legacy variable resolver
1. Remove `agent_template_resolve_var()` and all its helper functions that are now redundant
2. Remove `prompt_var_resolver_fn` callback from `prompt_template_build_messages()`
3. Clean up dead code in `agent.c`
4. Update all documentation
### Template Section Struct Changes
```c
typedef struct {
char name[PROMPT_TEMPLATE_MAX_NAME_LEN];
char role[PROMPT_TEMPLATE_MAX_ROLE_LEN];
char* content_template; // legacy: {{variable}} content
char* tool_name; // NEW: tool to call for content
char* tool_args; // NEW: JSON args for tool call
char* result_field; // NEW: which JSON field to extract (default: "content")
int limit;
int skip_if_empty;
char* provider_name;
char* provider_content_template;
} prompt_template_section_t;
```
### Soul Template Example (After Migration)
```
# Didactyl Agent
You are Didactyl, a sovereign AI agent living on Nostr.
...
---template---
- section: admin_identity
role: system
tool: context_admin_identity
skip_if_empty: true
- section: admin_profile
role: system
tool: context_admin_profile
skip_if_empty: true
- section: admin_contacts
role: system
tool: context_admin_contacts
skip_if_empty: true
- section: admin_relays
role: system
tool: context_admin_relays
skip_if_empty: true
- section: admin_notes
role: system
tool: context_admin_notes
skip_if_empty: true
- section: tools
role: system
tool: tool_list
result_field: tools
skip_if_empty: true
- section: tasks
role: system
tool: task_manage
args: {"action":"list"}
result_field: tasks
skip_if_empty: true
- section: dm_history
role: expand
limit: 12
- section: conversation
role: user
tool: context_user_message
skip_if_empty: true
```
### What Gets Deleted Eventually
- `agent_template_resolve_var()` and all its `if (strcmp(...))` branches
- `build_tool_schemas_json_string()`
- `build_tasks_content_string()` (replaced by `task_manage` tool)
- `build_admin_recent_posts_text()` (replaced by `context_admin_notes` tool)
- `build_admin_profile_plain_text()` (replaced by `context_admin_profile` tool)
- `build_admin_relay_list_plain_text()` (replaced by `context_admin_relays` tool)
- `build_sender_verification_text()` (folded into `context_admin_identity` tool)
- `build_startup_events_json_string()` (replaced by tool if needed)
- `build_adopted_skills_payload_string()` (replaced by tool if needed)
- `nostr_handler_get_admin_kind3_context()` (just added, will be replaced by tool)
- The `prompt_var_resolver_fn` callback type
### Benefits
1. **Single data-fetching mechanism** — tools are the only way to get data
2. **No more variable name mismatches** — tool names are validated at registration
3. **User-configurable context** — admin can add any tool output to context by editing the soul template
4. **Testable**`--test-tool context_admin_profile` shows exactly what goes into context
5. **Self-documenting**`tool_list` shows all available context tools with descriptions
6. **Extensible** — new tools automatically become available as context sources
7. **Provider overrides still work**`provider:` directive can still override formatting per-provider
### Risks
1. **Performance** — Tool calls add function dispatch overhead vs direct variable resolution. Mitigated: context tools read cached data, no network calls.
2. **Backward compatibility** — Old soul templates with `{{variables}}` would break. Mitigated: Phase 1 keeps both paths working.
3. **Tool context threading**`tools_execute()` needs access to the tools context, which `prompt_template_build_messages()` doesn't currently have. Solution: pass `tools_context_t*` to the build function.

View File

@@ -64,6 +64,7 @@ static pthread_mutex_t g_adopted_skills_mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct {
didactyl_sender_tier_t sender_tier;
const char* current_user_message;
} agent_template_resolver_ctx_t;
static uint64_t fnv1a64(const char* s) {
@@ -2047,6 +2048,11 @@ static char* build_adopted_skills_payload_string(void) {
return out;
}
static char* build_tool_schemas_json_string(void) {
char* schema_json = tools_build_openai_schema_json(&g_tools_ctx);
return schema_json ? schema_json : strdup("[]");
}
static char* build_tasks_content_string(void) {
const char* fallback =
"### Current Tasks\n\n"
@@ -2202,6 +2208,10 @@ static char* agent_template_resolve_var(const char* var_name, void* user_data) {
char* v = nostr_handler_get_admin_kind0_context();
return v ? v : strdup("");
}
if (strcmp(var_name, "admin_kind3_json") == 0) {
char* v = nostr_handler_get_admin_kind3_context();
return v ? v : strdup("[]");
}
if (strcmp(var_name, "admin_kind10002_json") == 0) {
char* v = nostr_handler_get_admin_kind10002_context();
return v ? v : strdup("");
@@ -2227,14 +2237,21 @@ static char* agent_template_resolve_var(const char* var_name, void* user_data) {
char* v = build_adopted_skills_payload_string();
return v ? v : strdup("");
}
if (strcmp(var_name, "tasks_content") == 0) {
if (strcmp(var_name, "tool_schemas_json") == 0) {
char* v = build_tool_schemas_json_string();
return v ? v : strdup("[]");
}
if (strcmp(var_name, "tasks_content") == 0 || strcmp(var_name, "tasks_json") == 0) {
char* v = build_tasks_content_string();
return v ? v : strdup("");
}
if (strcmp(var_name, "admin_notes_content") == 0) {
if (strcmp(var_name, "admin_notes_content") == 0 || strcmp(var_name, "admin_kind1_json") == 0) {
char* v = build_admin_recent_posts_text();
return v ? v : strdup("");
}
if (strcmp(var_name, "conversation_json") == 0) {
return safe_strdup(ctx ? ctx->current_user_message : "");
}
if (strcmp(var_name, "admin_recent_posts") == 0) {
char* v = build_admin_recent_posts_text();
return v ? v : strdup("");
@@ -2370,6 +2387,7 @@ int agent_build_admin_messages_json(const char* current_user_message,
agent_template_resolver_ctx_t resolver_ctx;
resolver_ctx.sender_tier = sender_tier;
resolver_ctx.current_user_message = current_user_message;
llm_config_t cfg;
memset(&cfg, 0, sizeof(cfg));
@@ -2378,10 +2396,14 @@ int agent_build_admin_messages_json(const char* current_user_message,
provider_name = cfg.provider;
}
g_tools_ctx.template_sender_tier = (int)sender_tier;
g_tools_ctx.template_current_user_message = current_user_message;
messages = prompt_template_build_messages(&g_prompt_template,
provider_name,
agent_template_resolve_var,
&resolver_ctx,
&g_tools_ctx,
dm_history,
AGENT_HISTORY_TURNS,
template_emit_hook,

View File

@@ -3,6 +3,7 @@
#include "llm.h"
#include <curl/curl.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -69,6 +70,20 @@ static int url_looks_like_websocket(const char* url) {
return (strncmp(url, "ws://", 5) == 0) || (strncmp(url, "wss://", 6) == 0);
}
static int json_string_is_blank(const cJSON* item) {
if (!item || !cJSON_IsString(item) || !item->valuestring) {
return 0;
}
const unsigned char* p = (const unsigned char*)item->valuestring;
while (*p) {
if (!isspace(*p)) {
return 0;
}
p++;
}
return 1;
}
static char* perform_http_request(const char* url, const char* body, int is_post) {
CURL* curl = curl_easy_init();
if (!curl || !url) {
@@ -111,6 +126,19 @@ static char* perform_http_request(const char* url, const char* body, int is_post
curl_easy_setopt(curl, CURLOPT_CAINFO, ca_bundle);
}
if (is_post) {
size_t body_len = body ? strlen(body) : 0U;
size_t body_preview_len = body_len > 4000U ? 4000U : body_len;
fprintf(stderr,
"[didactyl] llm request: method=POST url=%s body_bytes=%zu body_preview=%.4000s%s\n",
url,
body_len,
body ? body : "",
body_len > body_preview_len ? "..." : "");
} else {
fprintf(stderr, "[didactyl] llm request: method=GET url=%s\n", url);
}
CURLcode res = curl_easy_perform(curl);
long status = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
@@ -340,6 +368,36 @@ int llm_chat_with_tools_messages(const char* messages_json,
cJSON_Delete(root);
return -1;
}
int filtered_count = 0;
for (int i = cJSON_GetArraySize(messages) - 1; i >= 0; i--) {
cJSON* msg = cJSON_GetArrayItem(messages, i);
if (!msg || !cJSON_IsObject(msg)) {
continue;
}
cJSON* role = cJSON_GetObjectItemCaseSensitive(msg, "role");
cJSON* content = cJSON_GetObjectItemCaseSensitive(msg, "content");
cJSON* tool_calls = cJSON_GetObjectItemCaseSensitive(msg, "tool_calls");
int role_is_textual = (role && cJSON_IsString(role) && role->valuestring &&
(strcmp(role->valuestring, "system") == 0 ||
strcmp(role->valuestring, "user") == 0 ||
strcmp(role->valuestring, "assistant") == 0));
int has_tool_calls = (tool_calls && cJSON_IsArray(tool_calls) && cJSON_GetArraySize(tool_calls) > 0);
if (role_is_textual && !has_tool_calls && json_string_is_blank(content)) {
cJSON_DeleteItemFromArray(messages, i);
filtered_count++;
}
}
if (filtered_count > 0) {
fprintf(stderr,
"[didactyl] llm request sanitizer: removed %d empty text message(s) before provider request\n",
filtered_count);
}
cJSON_AddItemToObject(root, "messages", messages);
if (tools_json) {

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 0
#define DIDACTYL_VERSION_PATCH 46
#define DIDACTYL_VERSION "v0.0.46"
#define DIDACTYL_VERSION_PATCH 47
#define DIDACTYL_VERSION "v0.0.47"
// Agent metadata
#define DIDACTYL_NAME "Didactyl"

View File

@@ -2192,6 +2192,32 @@ char* nostr_handler_get_admin_kind0_context(void) {
return out;
}
char* nostr_handler_get_admin_kind3_context(void) {
if (!g_cfg || !g_cfg->admin_context.enabled || !g_cfg->admin_context.track_kind_3) {
return NULL;
}
pthread_mutex_lock(&g_admin_ctx_mutex);
cJSON* out = cJSON_CreateArray();
if (!out) {
pthread_mutex_unlock(&g_admin_ctx_mutex);
return NULL;
}
for (int i = 0; i < g_admin_wot_contact_count; i++) {
const char* pk = g_admin_wot_contacts[i];
if (!pk || pk[0] == '\0') continue;
cJSON_AddItemToArray(out, cJSON_CreateString(pk));
}
pthread_mutex_unlock(&g_admin_ctx_mutex);
char* out_json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return out_json;
}
char* nostr_handler_get_admin_kind10002_context(void) {
if (!g_cfg || !g_cfg->admin_context.enabled || !g_cfg->admin_context.track_kind_10002) {
return NULL;

View File

@@ -45,6 +45,7 @@ char* nostr_handler_get_self_skill_events_json(void);
const char* nostr_handler_get_startup_display_name(void);
int nostr_handler_connected_relay_count(void);
char* nostr_handler_get_admin_kind0_context(void);
char* nostr_handler_get_admin_kind3_context(void);
char* nostr_handler_get_admin_kind10002_context(void);
char* nostr_handler_get_admin_kind1_notes_context(void);
int nostr_handler_is_wot_contact(const char* pubkey_hex);

View File

@@ -178,6 +178,9 @@ static void init_section_defaults(prompt_template_section_t* sec) {
memset(sec->role, 0, sizeof(sec->role));
snprintf(sec->role, sizeof(sec->role), "system");
sec->content_template = NULL;
sec->tool_name = NULL;
sec->tool_args = NULL;
sec->result_field = NULL;
sec->limit = 0;
sec->skip_if_empty = 0;
sec->provider_name = NULL;
@@ -292,6 +295,36 @@ int prompt_template_parse(const char* soul_content, prompt_template_t* out_templ
continue;
}
if (starts_with(line, "tool:")) {
char* val = line + strlen("tool:");
val = ltrim_inplace(val);
rtrim_inplace(val);
free(out_template->sections[current].tool_name);
out_template->sections[current].tool_name = strdup(val);
i++;
continue;
}
if (starts_with(line, "args:")) {
char* val = line + strlen("args:");
val = ltrim_inplace(val);
rtrim_inplace(val);
free(out_template->sections[current].tool_args);
out_template->sections[current].tool_args = strdup((*val) ? val : "{}");
i++;
continue;
}
if (starts_with(line, "result_field:")) {
char* val = line + strlen("result_field:");
val = ltrim_inplace(val);
rtrim_inplace(val);
free(out_template->sections[current].result_field);
out_template->sections[current].result_field = strdup(val);
i++;
continue;
}
if (starts_with(line, "content:")) {
char* val = line + strlen("content:");
val = ltrim_inplace(val);
@@ -319,6 +352,9 @@ int prompt_template_parse(const char* soul_content, prompt_template_t* out_templ
starts_with(next_ltrim, "role:") ||
starts_with(next_ltrim, "limit:") ||
starts_with(next_ltrim, "skip_if_empty:") ||
starts_with(next_ltrim, "tool:") ||
starts_with(next_ltrim, "args:") ||
starts_with(next_ltrim, "result_field:") ||
starts_with(next_ltrim, "content:") ||
starts_with(next_ltrim, "provider:")) {
break;
@@ -391,6 +427,9 @@ int prompt_template_parse(const char* soul_content, prompt_template_t* out_templ
starts_with(next, "role:") ||
starts_with(next, "limit:") ||
starts_with(next, "skip_if_empty:") ||
starts_with(next, "tool:") ||
starts_with(next, "args:") ||
starts_with(next, "result_field:") ||
starts_with(next, "content:") ||
starts_with(next, "provider:")) {
break;
@@ -437,10 +476,48 @@ static int append_message_object(cJSON* messages, const char* role, const char*
return 0;
}
static char* extract_tool_result_content(const prompt_template_section_t* sec, const char* tool_result_json) {
if (!tool_result_json) return strdup("");
cJSON* root = cJSON_Parse(tool_result_json);
if (!root || !cJSON_IsObject(root)) {
cJSON_Delete(root);
return strdup(tool_result_json);
}
cJSON* success = cJSON_GetObjectItemCaseSensitive(root, "success");
if (success && cJSON_IsBool(success) && !cJSON_IsTrue(success)) {
cJSON_Delete(root);
return strdup("");
}
const char* field_name = (sec && sec->result_field && sec->result_field[0] != '\0')
? sec->result_field
: "content";
cJSON* field = cJSON_GetObjectItemCaseSensitive(root, field_name);
if (!field) {
field = cJSON_GetObjectItemCaseSensitive(root, "content");
}
char* out = NULL;
if (field && cJSON_IsString(field) && field->valuestring) {
out = strdup(field->valuestring);
} else if (field) {
out = cJSON_PrintUnformatted(field);
} else {
out = cJSON_PrintUnformatted(root);
}
cJSON_Delete(root);
return out ? out : strdup("");
}
cJSON* prompt_template_build_messages(const prompt_template_t* tmpl,
const char* provider_name,
prompt_var_resolver_fn resolver_fn,
void* resolver_user_data,
tools_context_t* tools_ctx,
cJSON* dm_history_messages,
int dm_history_default_limit,
prompt_template_emit_hook_fn emit_hook,
@@ -487,13 +564,21 @@ cJSON* prompt_template_build_messages(const prompt_template_t* tmpl,
continue;
}
const char* tpl = sec->content_template;
if (provider_name && sec->provider_name && sec->provider_content_template &&
strcmp(provider_name, sec->provider_name) == 0) {
tpl = sec->provider_content_template;
}
char* resolved = NULL;
char* resolved = resolve_placeholders(tpl ? tpl : "", resolver_fn, resolver_user_data);
if (sec->tool_name && sec->tool_name[0] != '\0' && tools_ctx) {
const char* args_json = (sec->tool_args && sec->tool_args[0] != '\0') ? sec->tool_args : "{}";
char* tool_result = tools_execute(tools_ctx, sec->tool_name, args_json);
resolved = extract_tool_result_content(sec, tool_result);
free(tool_result);
} else {
const char* tpl = sec->content_template;
if (provider_name && sec->provider_name && sec->provider_content_template &&
strcmp(provider_name, sec->provider_name) == 0) {
tpl = sec->provider_content_template;
}
resolved = resolve_placeholders(tpl ? tpl : "", resolver_fn, resolver_user_data);
}
if (!resolved) {
cJSON_Delete(out);
return NULL;
@@ -529,6 +614,12 @@ void prompt_template_free(prompt_template_t* tmpl) {
for (int i = 0; i < tmpl->section_count; i++) {
free(tmpl->sections[i].content_template);
tmpl->sections[i].content_template = NULL;
free(tmpl->sections[i].tool_name);
tmpl->sections[i].tool_name = NULL;
free(tmpl->sections[i].tool_args);
tmpl->sections[i].tool_args = NULL;
free(tmpl->sections[i].result_field);
tmpl->sections[i].result_field = NULL;
free(tmpl->sections[i].provider_name);
tmpl->sections[i].provider_name = NULL;
free(tmpl->sections[i].provider_content_template);

View File

@@ -2,6 +2,7 @@
#define DIDACTYL_PROMPT_TEMPLATE_H
#include "cjson/cJSON.h"
#include "tools.h"
#define PROMPT_TEMPLATE_MAX_SECTIONS 32
#define PROMPT_TEMPLATE_MAX_NAME_LEN 64
@@ -12,6 +13,9 @@ typedef struct {
char name[PROMPT_TEMPLATE_MAX_NAME_LEN];
char role[PROMPT_TEMPLATE_MAX_ROLE_LEN];
char* content_template;
char* tool_name;
char* tool_args;
char* result_field;
int limit;
int skip_if_empty;
char* provider_name;
@@ -35,6 +39,7 @@ cJSON* prompt_template_build_messages(const prompt_template_t* tmpl,
const char* provider_name,
prompt_var_resolver_fn resolver_fn,
void* resolver_user_data,
tools_context_t* tools_ctx,
cJSON* dm_history_messages,
int dm_history_default_limit,
prompt_template_emit_hook_fn emit_hook,

View File

@@ -544,6 +544,8 @@ int tools_init(tools_context_t* ctx, didactyl_config_t* cfg) {
memset(ctx, 0, sizeof(*ctx));
ctx->cfg = cfg;
ctx->trigger_manager = NULL;
ctx->template_sender_tier = 0;
ctx->template_current_user_message = NULL;
return 0;
}
@@ -1943,14 +1945,126 @@ char* tools_build_openai_schema_json(const tools_context_t* ctx) {
cJSON* t37_fn = cJSON_CreateObject();
cJSON* t37_params = cJSON_CreateObject();
cJSON* t37_props = cJSON_CreateObject();
cJSON* t37_required = cJSON_CreateArray();
cJSON_AddStringToObject(t37, "type", "function");
cJSON_AddStringToObject(t37_fn, "name", "task_manage");
cJSON_AddStringToObject(t37_fn, "description", "Manage agent short-term task memory stored in tasks.json (list/add/update/remove/clear/replace)");
cJSON_AddStringToObject(t37_fn, "name", "context_admin_identity");
cJSON_AddStringToObject(t37_fn, "description", "Build admin identity context block from cached runtime metadata");
cJSON_AddStringToObject(t37_params, "type", "object");
cJSON_AddItemToObject(t37_params, "properties", t37_props);
cJSON_AddItemToObject(t37_params, "required", t37_required);
cJSON_AddItemToObject(t37_fn, "parameters", t37_params);
cJSON_AddItemToObject(t37, "function", t37_fn);
cJSON_AddItemToArray(tools, t37);
cJSON* t38 = cJSON_CreateObject();
cJSON* t38_fn = cJSON_CreateObject();
cJSON* t38_params = cJSON_CreateObject();
cJSON* t38_props = cJSON_CreateObject();
cJSON_AddStringToObject(t38, "type", "function");
cJSON_AddStringToObject(t38_fn, "name", "context_admin_profile");
cJSON_AddStringToObject(t38_fn, "description", "Build admin profile context block from cached kind 0 metadata");
cJSON_AddStringToObject(t38_params, "type", "object");
cJSON_AddItemToObject(t38_params, "properties", t38_props);
cJSON_AddItemToObject(t38_fn, "parameters", t38_params);
cJSON_AddItemToObject(t38, "function", t38_fn);
cJSON_AddItemToArray(tools, t38);
cJSON* t39 = cJSON_CreateObject();
cJSON* t39_fn = cJSON_CreateObject();
cJSON* t39_params = cJSON_CreateObject();
cJSON* t39_props = cJSON_CreateObject();
cJSON_AddStringToObject(t39, "type", "function");
cJSON_AddStringToObject(t39_fn, "name", "context_admin_contacts");
cJSON_AddStringToObject(t39_fn, "description", "Build admin contacts context block from cached kind 3 contact list");
cJSON_AddStringToObject(t39_params, "type", "object");
cJSON_AddItemToObject(t39_params, "properties", t39_props);
cJSON_AddItemToObject(t39_fn, "parameters", t39_params);
cJSON_AddItemToObject(t39, "function", t39_fn);
cJSON_AddItemToArray(tools, t39);
cJSON* t40 = cJSON_CreateObject();
cJSON* t40_fn = cJSON_CreateObject();
cJSON* t40_params = cJSON_CreateObject();
cJSON* t40_props = cJSON_CreateObject();
cJSON_AddStringToObject(t40, "type", "function");
cJSON_AddStringToObject(t40_fn, "name", "context_admin_relays");
cJSON_AddStringToObject(t40_fn, "description", "Build admin relay context block from cached kind 10002 data");
cJSON_AddStringToObject(t40_params, "type", "object");
cJSON_AddItemToObject(t40_params, "properties", t40_props);
cJSON_AddItemToObject(t40_fn, "parameters", t40_params);
cJSON_AddItemToObject(t40, "function", t40_fn);
cJSON_AddItemToArray(tools, t40);
cJSON* t41 = cJSON_CreateObject();
cJSON* t41_fn = cJSON_CreateObject();
cJSON* t41_params = cJSON_CreateObject();
cJSON* t41_props = cJSON_CreateObject();
cJSON_AddStringToObject(t41, "type", "function");
cJSON_AddStringToObject(t41_fn, "name", "context_admin_notes");
cJSON_AddStringToObject(t41_fn, "description", "Build admin notes context block from cached kind 1 notes");
cJSON_AddStringToObject(t41_params, "type", "object");
cJSON_AddItemToObject(t41_params, "properties", t41_props);
cJSON_AddItemToObject(t41_fn, "parameters", t41_params);
cJSON_AddItemToObject(t41, "function", t41_fn);
cJSON_AddItemToArray(tools, t41);
cJSON* t42 = cJSON_CreateObject();
cJSON* t42_fn = cJSON_CreateObject();
cJSON* t42_params = cJSON_CreateObject();
cJSON* t42_props = cJSON_CreateObject();
cJSON_AddStringToObject(t42, "type", "function");
cJSON_AddStringToObject(t42_fn, "name", "context_tasks");
cJSON_AddStringToObject(t42_fn, "description", "Build current task list context block from tasks.json");
cJSON_AddStringToObject(t42_params, "type", "object");
cJSON_AddItemToObject(t42_params, "properties", t42_props);
cJSON_AddItemToObject(t42_fn, "parameters", t42_params);
cJSON_AddItemToObject(t42, "function", t42_fn);
cJSON_AddItemToArray(tools, t42);
cJSON* t43 = cJSON_CreateObject();
cJSON* t43_fn = cJSON_CreateObject();
cJSON* t43_params = cJSON_CreateObject();
cJSON* t43_props = cJSON_CreateObject();
cJSON_AddStringToObject(t43, "type", "function");
cJSON_AddStringToObject(t43_fn, "name", "context_user_message");
cJSON_AddStringToObject(t43_fn, "description", "Return current user message text for context template conversation section");
cJSON_AddStringToObject(t43_params, "type", "object");
cJSON_AddItemToObject(t43_params, "properties", t43_props);
cJSON_AddItemToObject(t43_fn, "parameters", t43_params);
cJSON_AddItemToObject(t43, "function", t43_fn);
cJSON_AddItemToArray(tools, t43);
cJSON* t44 = cJSON_CreateObject();
cJSON* t44_fn = cJSON_CreateObject();
cJSON* t44_params = cJSON_CreateObject();
cJSON* t44_props = cJSON_CreateObject();
cJSON_AddStringToObject(t44, "type", "function");
cJSON_AddStringToObject(t44_fn, "name", "context_agent_identity");
cJSON_AddStringToObject(t44_fn, "description", "Build agent identity context block with pubkey and npub");
cJSON_AddStringToObject(t44_params, "type", "object");
cJSON_AddItemToObject(t44_params, "properties", t44_props);
cJSON_AddItemToObject(t44_fn, "parameters", t44_params);
cJSON_AddItemToObject(t44, "function", t44_fn);
cJSON_AddItemToArray(tools, t44);
cJSON* t45 = cJSON_CreateObject();
cJSON* t45_fn = cJSON_CreateObject();
cJSON* t45_params = cJSON_CreateObject();
cJSON* t45_props = cJSON_CreateObject();
cJSON* t45_required = cJSON_CreateArray();
cJSON_AddStringToObject(t45, "type", "function");
cJSON_AddStringToObject(t45_fn, "name", "task_manage");
cJSON_AddStringToObject(t45_fn, "description", "Manage agent short-term task memory stored in tasks.json (list/add/update/remove/clear/replace)");
cJSON_AddStringToObject(t45_params, "type", "object");
cJSON_AddItemToObject(t45_params, "properties", t45_props);
cJSON_AddItemToObject(t45_params, "required", t45_required);
cJSON* p_task_action = cJSON_CreateObject();
cJSON_AddStringToObject(p_task_action, "type", "string");
@@ -1962,15 +2076,15 @@ char* tools_build_openai_schema_json(const tools_context_t* ctx) {
cJSON_AddItemToArray(p_task_action_enum, cJSON_CreateString("clear"));
cJSON_AddItemToArray(p_task_action_enum, cJSON_CreateString("replace"));
cJSON_AddItemToObject(p_task_action, "enum", p_task_action_enum);
cJSON_AddItemToObject(t37_props, "action", p_task_action);
cJSON_AddItemToObject(t45_props, "action", p_task_action);
cJSON* p_task_text = cJSON_CreateObject();
cJSON_AddStringToObject(p_task_text, "type", "string");
cJSON_AddItemToObject(t37_props, "text", p_task_text);
cJSON_AddItemToObject(t45_props, "text", p_task_text);
cJSON* p_task_id = cJSON_CreateObject();
cJSON_AddStringToObject(p_task_id, "type", "integer");
cJSON_AddItemToObject(t37_props, "id", p_task_id);
cJSON_AddItemToObject(t45_props, "id", p_task_id);
cJSON* p_task_status = cJSON_CreateObject();
cJSON_AddStringToObject(p_task_status, "type", "string");
@@ -1979,20 +2093,20 @@ char* tools_build_openai_schema_json(const tools_context_t* ctx) {
cJSON_AddItemToArray(p_task_status_enum, cJSON_CreateString("active"));
cJSON_AddItemToArray(p_task_status_enum, cJSON_CreateString("done"));
cJSON_AddItemToObject(p_task_status, "enum", p_task_status_enum);
cJSON_AddItemToObject(t37_props, "status", p_task_status);
cJSON_AddItemToObject(t45_props, "status", p_task_status);
cJSON* p_task_tasks = cJSON_CreateObject();
cJSON_AddStringToObject(p_task_tasks, "type", "array");
cJSON* p_task_tasks_item = cJSON_CreateObject();
cJSON_AddStringToObject(p_task_tasks_item, "type", "string");
cJSON_AddItemToObject(p_task_tasks, "items", p_task_tasks_item);
cJSON_AddItemToObject(t37_props, "tasks", p_task_tasks);
cJSON_AddItemToObject(t45_props, "tasks", p_task_tasks);
cJSON_AddItemToArray(t37_required, cJSON_CreateString("action"));
cJSON_AddItemToArray(t45_required, cJSON_CreateString("action"));
cJSON_AddItemToObject(t37_fn, "parameters", t37_params);
cJSON_AddItemToObject(t37, "function", t37_fn);
cJSON_AddItemToArray(tools, t37);
cJSON_AddItemToObject(t45_fn, "parameters", t45_params);
cJSON_AddItemToObject(t45, "function", t45_fn);
cJSON_AddItemToArray(tools, t45);
char* out = cJSON_PrintUnformatted(tools);
cJSON_Delete(tools);
@@ -4102,6 +4216,370 @@ static char* execute_nostr_npub(tools_context_t* ctx, const char* args_json) {
return json;
}
static char* execute_context_admin_identity(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
const char* tier_text = "Sender tier unknown.";
if (ctx->template_sender_tier == 1) {
tier_text = "This message has been cryptographically verified as coming from your administrator.";
} else if (ctx->template_sender_tier == 2) {
tier_text = "This message is from a web-of-trust contact (not the administrator).";
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "admin_pubkey", ctx->cfg->admin.pubkey[0] ? ctx->cfg->admin.pubkey : "unknown");
cJSON_AddStringToObject(out, "sender_verification", tier_text);
char content[768];
snprintf(content,
sizeof(content),
"## Administrator Identity (source: config.admin.pubkey)\n\n"
"This is your administrator! Admin pubkey (hex): %s\n\n"
"%s",
ctx->cfg->admin.pubkey[0] ? ctx->cfg->admin.pubkey : "unknown",
tier_text);
cJSON_AddStringToObject(out, "content", content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
static char* execute_context_admin_profile(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
cJSON_Delete(args);
char* kind0 = nostr_handler_get_admin_kind0_context();
const char* profile_json = (kind0 && kind0[0]) ? kind0 : "{}";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind0);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "admin_kind0_json", profile_json);
size_t content_len = strlen("## Administrator Kind 0 Profile (source: nostr kind 0)\n\nAdministrator kind 0 profile content (JSON): ") + strlen(profile_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind0);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Kind 0 Profile (source: nostr kind 0)\n\nAdministrator kind 0 profile content (JSON): %s",
profile_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind0);
return json;
}
static char* execute_context_admin_contacts(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
cJSON_Delete(args);
char* kind3 = nostr_handler_get_admin_kind3_context();
const char* contacts_json = (kind3 && kind3[0]) ? kind3 : "[]";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind3);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "admin_kind3_json", contacts_json);
size_t content_len = strlen("## Administrator Kind 3 Contacts (source: nostr kind 3)\n\nAdministrator contacts (JSON): ") + strlen(contacts_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind3);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Kind 3 Contacts (source: nostr kind 3)\n\nAdministrator contacts (JSON): %s",
contacts_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind3);
return json;
}
static char* execute_context_admin_relays(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
cJSON_Delete(args);
char* kind10002 = nostr_handler_get_admin_kind10002_context();
const char* relays_json = (kind10002 && kind10002[0]) ? kind10002 : "[]";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(kind10002);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "admin_kind10002_json", relays_json);
size_t content_len = strlen("## Administrator Kind 10002 Relays (source: nostr kind 10002)\n\nAdministrator relay list (JSON): ") + strlen(relays_json) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(kind10002);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Kind 10002 Relays (source: nostr kind 10002)\n\nAdministrator relay list (JSON): %s",
relays_json);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(kind10002);
return json;
}
static char* execute_context_admin_notes(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
cJSON_Delete(args);
char* notes = nostr_handler_get_admin_kind1_notes_context();
const char* notes_text = (notes && notes[0]) ? notes : "";
cJSON* out = cJSON_CreateObject();
if (!out) {
free(notes);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "admin_notes_content", notes_text);
size_t content_len = strlen("## Administrator Recent Kind 1 Notes\n\n") + strlen(notes_text) + 1U;
char* content = (char*)malloc(content_len);
if (!content) {
cJSON_Delete(out);
free(notes);
return NULL;
}
snprintf(content,
content_len,
"## Administrator Recent Kind 1 Notes\n\n%s",
notes_text);
cJSON_AddStringToObject(out, "content", content);
free(content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(notes);
return json;
}
static char* execute_task_manage(tools_context_t* ctx, const char* args_json);
static char* execute_context_tasks(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
char* listed = execute_task_manage(ctx, "{\"action\":\"list\"}");
if (!listed) return json_error("context_tasks failed to list tasks");
cJSON* listed_root = cJSON_Parse(listed);
if (!listed_root || !cJSON_IsObject(listed_root)) {
cJSON_Delete(listed_root);
free(listed);
return json_error("context_tasks received invalid task_manage response");
}
cJSON* tasks = cJSON_GetObjectItemCaseSensitive(listed_root, "tasks");
int tcount = (tasks && cJSON_IsArray(tasks)) ? cJSON_GetArraySize(tasks) : 0;
size_t cap = 512U;
char* content = (char*)malloc(cap);
if (!content) {
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
size_t used = 0U;
int n = snprintf(content + used,
cap - used,
"## Current Task List\n\n### Current Tasks\n\nYour active task list - short-term working memory for tracking plan steps.\n\n");
if (n < 0) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
used += (size_t)n;
int written = 0;
for (int i = 0; i < tcount; i++) {
cJSON* task = cJSON_GetArrayItem(tasks, i);
cJSON* id = task ? cJSON_GetObjectItemCaseSensitive(task, "id") : NULL;
cJSON* text = task ? cJSON_GetObjectItemCaseSensitive(task, "text") : NULL;
cJSON* status = task ? cJSON_GetObjectItemCaseSensitive(task, "status") : NULL;
if (!text || !cJSON_IsString(text) || !text->valuestring || text->valuestring[0] == '\0') {
continue;
}
const char* status_s = (status && cJSON_IsString(status) && status->valuestring) ? status->valuestring : "pending";
const char* mark = " ";
if (strcmp(status_s, "done") == 0) mark = "x";
else if (strcmp(status_s, "active") == 0) mark = "-";
int id_value = (id && cJSON_IsNumber(id)) ? (int)id->valuedouble : (i + 1);
int needed = snprintf(NULL, 0, "- [%s] %d. %s\n", mark, id_value, text->valuestring);
if (needed < 0) continue;
if (used + (size_t)needed + 1U > cap) {
size_t next = cap;
while (used + (size_t)needed + 1U > next) next *= 2U;
char* grown = (char*)realloc(content, next);
if (!grown) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
content = grown;
cap = next;
}
snprintf(content + used, cap - used, "- [%s] %d. %s\n", mark, id_value, text->valuestring);
used += (size_t)needed;
written++;
}
if (written == 0) {
const char* fallback = "- [ ] No active tasks yet.\n";
size_t need = strlen(fallback);
if (used + need + 1U > cap) {
size_t next = cap;
while (used + need + 1U > next) next *= 2U;
char* grown = (char*)realloc(content, next);
if (!grown) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
content = grown;
cap = next;
}
memcpy(content + used, fallback, need + 1U);
used += need;
}
cJSON* args = parse_tool_args_json(args_json);
if (!args) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return json_error("invalid arguments JSON");
}
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) {
free(content);
cJSON_Delete(listed_root);
free(listed);
return NULL;
}
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", content);
cJSON* tasks_dup = tasks ? cJSON_Duplicate(tasks, 1) : cJSON_CreateArray();
if (!tasks_dup) tasks_dup = cJSON_CreateArray();
cJSON_AddItemToObject(out, "tasks", tasks_dup);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
free(content);
cJSON_Delete(listed_root);
free(listed);
return json;
}
static char* execute_context_user_message(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
cJSON_Delete(args);
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "content", ctx->template_current_user_message ? ctx->template_current_user_message : "");
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
static char* execute_context_agent_identity(tools_context_t* ctx, const char* args_json) {
if (!ctx || !ctx->cfg) return json_error("tool context unavailable");
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
cJSON_Delete(args);
char npub[128] = {0};
if (nostr_key_to_bech32(ctx->cfg->keys.public_key, "npub", npub) != NOSTR_SUCCESS) {
strcpy(npub, "unknown");
}
cJSON* out = cJSON_CreateObject();
if (!out) return NULL;
cJSON_AddBoolToObject(out, "success", 1);
cJSON_AddStringToObject(out, "agent_pubkey", ctx->cfg->keys.public_key_hex[0] ? ctx->cfg->keys.public_key_hex : "unknown");
cJSON_AddStringToObject(out, "agent_npub", npub);
char content[384];
snprintf(content,
sizeof(content),
"## Agent Identity\n\nYour pubkey (hex): %s\nYour npub: %s",
ctx->cfg->keys.public_key_hex[0] ? ctx->cfg->keys.public_key_hex : "unknown",
npub);
cJSON_AddStringToObject(out, "content", content);
char* json = cJSON_PrintUnformatted(out);
cJSON_Delete(out);
return json;
}
static char* execute_my_version(const char* args_json) {
cJSON* args = parse_tool_args_json(args_json);
if (!args) return json_error("invalid arguments JSON");
@@ -5194,6 +5672,30 @@ char* tools_execute(tools_context_t* ctx, const char* tool_name, const char* arg
if (strcmp(tool_name, "task_manage") == 0) {
return execute_task_manage(ctx, args_json);
}
if (strcmp(tool_name, "context_admin_identity") == 0) {
return execute_context_admin_identity(ctx, args_json);
}
if (strcmp(tool_name, "context_admin_profile") == 0) {
return execute_context_admin_profile(ctx, args_json);
}
if (strcmp(tool_name, "context_admin_contacts") == 0) {
return execute_context_admin_contacts(ctx, args_json);
}
if (strcmp(tool_name, "context_admin_relays") == 0) {
return execute_context_admin_relays(ctx, args_json);
}
if (strcmp(tool_name, "context_admin_notes") == 0) {
return execute_context_admin_notes(ctx, args_json);
}
if (strcmp(tool_name, "context_tasks") == 0) {
return execute_context_tasks(ctx, args_json);
}
if (strcmp(tool_name, "context_user_message") == 0) {
return execute_context_user_message(ctx, args_json);
}
if (strcmp(tool_name, "context_agent_identity") == 0) {
return execute_context_agent_identity(ctx, args_json);
}
return json_error("unknown tool");
}

View File

@@ -8,6 +8,8 @@ struct trigger_manager;
typedef struct {
didactyl_config_t* cfg;
struct trigger_manager* trigger_manager;
int template_sender_tier;
const char* template_current_user_message;
} tools_context_t;
int tools_init(tools_context_t* ctx, didactyl_config_t* cfg);