Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c5beda3c9 | ||
|
|
7c32683e75 | ||
|
|
645f6ea610 | ||
|
|
b569d41409 | ||
|
|
b3b1ddb2dd | ||
|
|
c4ee5a0aa0 | ||
|
|
2398005eff | ||
|
|
b06c267db4 | ||
|
|
b625e0a70a | ||
|
|
ed5e4248df | ||
|
|
6a76b02180 | ||
|
|
90680e232d | ||
|
|
0bd21dc41a | ||
|
|
d0416f7760 | ||
|
|
1ab2034b2d |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -30,3 +30,6 @@ a.out
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Local secrets
|
||||
genesis.jsonc
|
||||
|
||||
208
README.md
208
README.md
@@ -1,6 +1,5 @@
|
||||
# Didactyl
|
||||
|
||||
|
||||
### A decentralized, censorship-resistant agentic network.
|
||||
|
||||
Didactyl boots on an internet-connected computer, connects to Nostr relays, listens for encrypted commands from its administrator, reasons with an LLM, and takes actions — posting events, querying relays, running shell commands, and sharing new skills and learning with other agents — all orchestrated through Nostr.
|
||||
@@ -55,31 +54,30 @@ 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.1.21
|
||||
## Current Status — v0.2.13
|
||||
|
||||
**Active build — this project is barely working. Experiment at your own risk.**
|
||||
|
||||
> Last release update: v0.1.21 — Fix segfault in nostr_http_request by copying CURLINFO_CONTENT_TYPE before curl cleanup and update debug deploy script to deploy *_debug binary for symbolized coredumps
|
||||
> Last release update: v0.2.13 — Unify startup skills, rename identity skill, add dm_history text format, and enforce startup publish success
|
||||
|
||||
- Connects to configured relays with auto-reconnect and relay state transition logging
|
||||
- Publishes configured startup events per relay as each relay becomes connected
|
||||
- Loads base system context from default skill content (first-run from `genesis.jsonc`, subsequent runs from adopted skills on Nostr)
|
||||
- Verifies Nostr event signatures before processing inbound messages
|
||||
- Applies privilege tiers: ADMIN (tools), WoT (chat-only), STRANGER (configurable canned reply or ignore)
|
||||
- Subscribes to admin context kinds (`0`,`3`,`10002`,`1`) for WoT + contextual awareness
|
||||
- Builds LLM context from default/adopted skill templates (`---template---`) with named sections, variable resolution, and per-provider content overrides; falls back to hardcoded assembly if no template present
|
||||
- Adopted skills injected into context automatically from the agent's `10123` adoption list
|
||||
- Builds trigger-scoped LLM context from DM and subscription-triggered skills with inline variable resolution
|
||||
- Uses default skill d-tag `default_admin_dm` with trigger tags for admin DM handling
|
||||
- Supports tool-calling loop with configurable max turns and local safety limits
|
||||
- Triggered skills — Nostr event filters that fire skill execution automatically with `template` (deterministic) or `llm` (context-aware) actions; see [`docs/SKILLS.md`](docs/SKILLS.md)
|
||||
- Triggered skills — Nostr event filters that fire skill execution automatically with`template` (deterministic) or`llm` (context-aware) actions; see[`docs/SKILLS.md`](docs/SKILLS.md)
|
||||
- Deduplicates inbound messages via event-ID cache and FNV-1a fingerprint debounce window
|
||||
- Appends every outbound LLM context payload to [`context.log`](context.log)
|
||||
- Localhost HTTP admin API on port `8484` — inspect context, run prompts, compare variants, change model at runtime
|
||||
- Appends every outbound LLM context payload to[`context.log`](context.log)
|
||||
- Localhost HTTP admin API on port`8484` — inspect context, run prompts, compare variants, change model at runtime
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Download binary (recommended)
|
||||
|
||||
1. Download the latest release binary from Gitea: [https://git.laantungir.net/laantungir/didactyl/releases](https://git.laantungir.net/laantungir/didactyl/releases)
|
||||
1. Download the latest release binary from Gitea:[https://git.laantungir.net/laantungir/didactyl/releases](https://git.laantungir.net/laantungir/didactyl/releases)
|
||||
2. Make it executable and run it:
|
||||
|
||||
```bash
|
||||
@@ -163,8 +161,8 @@ Edit [`genesis.jsonc`](genesis.jsonc):
|
||||
},
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "You are Didactyl...",
|
||||
"tags": [["d", "didactyl-default"], ["app", "didactyl"], ["scope", "private"]]
|
||||
"content": "# Didactyl Agent\n\nYou are {{my_kind0_profile}}\n\nYour npub: {{my_npub}}\n\n## Rules\n\n- Communicate through encrypted Nostr direct messages\n- Keep responses concise and clear\n- Be helpful and technically accurate",
|
||||
"tags": [["d", "default_admin_dm"], ["app", "didactyl"], ["scope", "private"], ["description", "Default admin DM handler"], ["trigger", "dm"], ["filter", "{\"from\":\"admin\"}"]]
|
||||
},
|
||||
{
|
||||
"kind": 31123,
|
||||
@@ -209,8 +207,8 @@ Options:
|
||||
|
||||
Interactive setup notes:
|
||||
|
||||
- First menu asks whether you are starting a **new agent** or an **existing agent**.
|
||||
- Menus use first-letter hotkeys (case-insensitive), with `q`/`x` as quit/back shortcuts.
|
||||
- First menu asks whether you are starting a**new agent** or an**existing agent**.
|
||||
- Menus use first-letter hotkeys (case-insensitive), with`q`/`x` as quit/back shortcuts.
|
||||
- Existing-agent mode attempts to recover relay/admin/LLM config from Nostr before asking for missing fields.
|
||||
|
||||
CLI debugger notes:
|
||||
@@ -247,10 +245,10 @@ node ./didactyl-chat-cli.js
|
||||
|
||||
Optional environment variables:
|
||||
|
||||
- `DIDACTYL_API_BASE_URL` (default: `https://127.0.0.1:8484`)
|
||||
- `DIDACTYL_API_BASE_URL` (default:`https://127.0.0.1:8484`)
|
||||
- `DIDACTYL_MODEL` (optional model override)
|
||||
- `DIDACTYL_MAX_TURNS` (default: `4`)
|
||||
- `DIDACTYL_INSECURE_TLS` (default: `1`, set `0` to enforce certificate verification)
|
||||
- `DIDACTYL_MAX_TURNS` (default:`4`)
|
||||
- `DIDACTYL_INSECURE_TLS` (default:`1`, set`0` to enforce certificate verification)
|
||||
|
||||
Example:
|
||||
|
||||
@@ -291,13 +289,13 @@ The CLI prints each message block with a speaker label (`You` / `Didactyl`) and
|
||||
|
||||
Didactyl uses a two-layer skill model: authors publish skill definitions, and adopters publish which skills they use.
|
||||
|
||||
- `31123` — **Public Skill Definition** (replaceable by `d` tag)
|
||||
- `content` is JSON with instruction fields like `description` and `template`
|
||||
- `d=<skill_slug>` (example: `d=long_form_note`)
|
||||
- `31124` — **Private Skill Definition** (same schema as `31123`, private scope)
|
||||
- `d=<skill_slug>` (example: `d=admin_ops`)
|
||||
- `10123` — **Skill Adoption List**
|
||||
- tags contain one or more `a` references to selected skills
|
||||
- `31123` —**Public Skill Definition** (replaceable by`d` tag)
|
||||
- `content` is JSON with instruction fields like`description` and`template`
|
||||
- `d=<skill_slug>` (example:`d=long_form_note`)
|
||||
- `31124` —**Private Skill Definition** (same schema as`31123`, private scope)
|
||||
- `d=<skill_slug>` (example:`d=admin_ops`)
|
||||
- `10123` —**Skill Adoption List**
|
||||
- tags contain one or more`a` references to selected skills
|
||||
|
||||
Skills are composed by adoption list order and per-skill template resolution (no context modes).
|
||||
|
||||
@@ -309,16 +307,16 @@ Skills are shared across Nostr without any centralized registry or approval proc
|
||||
|
||||
### How it works
|
||||
|
||||
1. **Publish**: An author publishes a skill as a kind `31123` event. The `content` field contains the skill body (markdown or structured JSON). The `d` tag is the skill's slug (e.g. `long_form_note`).
|
||||
2. **Adopt**: An agent that wants to use a skill adds an `a`-tag reference to its kind `10123` adoption list. This is a public, replaceable event — anyone can see which skills an agent uses.
|
||||
3. **Discover**: A new user queries `{"kinds": [10123], "authors": [<my-follows>]}` to see which skills their web of trust has adopted. The most-referenced `31123` addresses are the most popular skills — no rating system needed.
|
||||
4. **Improve**: Anyone can publish their own `31123` with the same slug but a different pubkey. If their version is better, people adopt it instead. Competition happens through adoption, not through a store ranking.
|
||||
1. **Publish**: An author publishes a skill as a kind`31123` event. The`content` field contains the skill body (markdown or structured JSON). The`d` tag is the skill's slug (e.g.`long_form_note`).
|
||||
2. **Adopt**: An agent that wants to use a skill adds an`a`-tag reference to its kind`10123` adoption list. This is a public, replaceable event — anyone can see which skills an agent uses.
|
||||
3. **Discover**: A new user queries`{"kinds": [10123], "authors": [<my-follows>]}` to see which skills their web of trust has adopted. The most-referenced`31123` addresses are the most popular skills — no rating system needed.
|
||||
4. **Improve**: Anyone can publish their own`31123` with the same slug but a different pubkey. If their version is better, people adopt it instead. Competition happens through adoption, not through a store ranking.
|
||||
|
||||
### Why this works
|
||||
|
||||
- **No gatekeeper**: Skills are just Nostr events. Anyone can publish one.
|
||||
- **WoT as curation**: You see what people you trust actually use, not what an algorithm promotes.
|
||||
- **Visible adoption**: The `10123` list is public. Popularity is a countable fact, not a manipulable score.
|
||||
- **Visible adoption**: The`10123` list is public. Popularity is a countable fact, not a manipulable score.
|
||||
- **Censorship resistant**: Skills live on relays. No single entity can remove a skill from the network.
|
||||
|
||||
## Startup
|
||||
@@ -327,10 +325,10 @@ Didactyl startup behavior is configured in [`genesis.jsonc`](genesis.jsonc) unde
|
||||
|
||||
Startup model:
|
||||
|
||||
- First run is detected by checking for an existing kind `10002` relay-list event from the agent pubkey.
|
||||
- On first run, events in `startup_events` are published to connected relays.
|
||||
- First run is detected by checking for an existing kind`10002` relay-list event from the agent pubkey.
|
||||
- On first run, events in`startup_events` are published to connected relays.
|
||||
- On subsequent runs, startup publish is skipped and relay/config state is loaded from Nostr.
|
||||
- Identity can be supplied at runtime via `--nsec` or `DIDACTYL_NSEC`.
|
||||
- Identity can be supplied at runtime via`--nsec` or`DIDACTYL_NSEC`.
|
||||
|
||||
See [`docs/GENESIS.md`](docs/GENESIS.md) for full boot semantics.
|
||||
|
||||
@@ -339,8 +337,8 @@ See [`docs/GENESIS.md`](docs/GENESIS.md) for full boot semantics.
|
||||
Didactyl builds tier-aware, template-driven context:
|
||||
|
||||
- **ADMIN** request context is assembled from adopted skill templates.
|
||||
- Template variables like `{{nostr_admin_profile}}` are resolved by executing tools at render time.
|
||||
- Triggered skill invocations can override runtime execution parameters via trigger tags (`llm`, `max_tokens`, `temperature`, `seed`, `tools`).
|
||||
- Template variables like`{{nostr_admin_profile}}` are resolved by executing tools at render time.
|
||||
- Triggered skill invocations can override runtime execution parameters via trigger tags (`llm`,`max_tokens`,`temperature`,`seed`,`tools`).
|
||||
- **WoT** request context remains chat-only.
|
||||
- **STRANGER** behavior follows configured security policy.
|
||||
|
||||
@@ -360,17 +358,17 @@ See [`docs/TOOLS.md`](docs/TOOLS.md) for the canonical tool catalog and interfac
|
||||
|
||||
A localhost-only HTTP API on port `8484` (configurable) for agent inspection and prompt crafting. Enable with `"api": {"enabled": true}` in config.
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|---|---|
|
||||
| `GET /api/status` | Agent name, version, pubkey, relay count, trigger count |
|
||||
| `GET /api/context/current` | Full LLM context messages array |
|
||||
| `GET /api/context/parts` | Context broken into named parts with token estimates |
|
||||
| `POST /api/prompt/run-simple` | Run a simple system+user prompt, no tools |
|
||||
| `POST /api/prompt/run` | Run a full messages array with tools enabled |
|
||||
| `POST /api/prompt/compare` | A/B compare two prompt variants |
|
||||
| `GET /api/model` | Current LLM model config |
|
||||
| `PUT /api/model` | Change model at runtime (persisted in encrypted config events) |
|
||||
| `GET /api/models` | List available models from provider |
|
||||
| Endpoint | Purpose |
|
||||
| ------------------------------- | -------------------------------------------------------------- |
|
||||
| `GET /api/status` | Agent name, version, pubkey, relay count, trigger count |
|
||||
| `GET /api/context/current` | Full LLM context messages array |
|
||||
| `GET /api/context/parts` | Context broken into named parts with token estimates |
|
||||
| `POST /api/prompt/run-simple` | Run a simple system+user prompt, no tools |
|
||||
| `POST /api/prompt/run` | Run a full messages array with tools enabled |
|
||||
| `POST /api/prompt/compare` | A/B compare two prompt variants |
|
||||
| `GET /api/model` | Current LLM model config |
|
||||
| `PUT /api/model` | Change model at runtime (persisted in encrypted config events) |
|
||||
| `GET /api/models` | List available models from provider |
|
||||
|
||||
Full reference: [`docs/API.md`](docs/API.md). Frontend brief: [`plans/admin_web_frontend.md`](plans/admin_web_frontend.md).
|
||||
|
||||
@@ -408,75 +406,99 @@ Full reference: [`docs/API.md`](docs/API.md). Frontend brief: [`plans/admin_web_
|
||||
|
||||
All dependencies are statically linked into the binary at build time. No system libraries are required at runtime.
|
||||
|
||||
| Dependency | Purpose | Source |
|
||||
|---|---|---|
|
||||
| nostr_core_lib | Nostr protocol: keys, events, NIPs, relay pool | Workspace (sibling directory) |
|
||||
| cJSON | JSON parsing | Bundled in nostr_core_lib |
|
||||
| libcurl | HTTPS for LLM API calls | Statically linked (Alpine/MUSL) |
|
||||
| libssl / libcrypto | TLS for WebSocket relay connections | Statically linked (Alpine/MUSL) |
|
||||
| libsecp256k1 | Schnorr signatures, ECDH | Statically linked (Alpine/MUSL) |
|
||||
| Dependency | Purpose | Source |
|
||||
| ------------------ | ---------------------------------------------- | ------------------------------- |
|
||||
| nostr_core_lib | Nostr protocol: keys, events, NIPs, relay pool | Workspace (sibling directory) |
|
||||
| cJSON | JSON parsing | Bundled in nostr_core_lib |
|
||||
| libcurl | HTTPS for LLM API calls | Statically linked (Alpine/MUSL) |
|
||||
| libssl / libcrypto | TLS for WebSocket relay connections | Statically linked (Alpine/MUSL) |
|
||||
| libsecp256k1 | Schnorr signatures, ECDH | Statically linked (Alpine/MUSL) |
|
||||
|
||||
## Roadmap: Nostr-Native Portability
|
||||
|
||||
Didactyl's long-term architecture goal is **zero filesystem dependency after first boot**. The config file is the only tie to the local filesystem. The plan:
|
||||
Didactyl's long-term architecture goal is **zero filesystem dependency after first boot**. A geneisis.jsonc file can assist the first boot, but first boot can also occur throught the command line or TUI wizard. The plan:
|
||||
|
||||
1. **First boot** — Read `genesis.jsonc`, publish startup identity/skill/adoption events to relays.
|
||||
2. **Subsequent boots** — Start with only `nsec` (CLI/env), detect initialized state from kind `10002`, and load durable state from Nostr.
|
||||
1. **First boot** — Read`genesis.jsonc`, publish startup identity/skill/adoption events to relays.
|
||||
2. **Subsequent boots** — Start with only`nsec` (CLI/env), detect initialized state from kind`10002`, and load durable state from Nostr.
|
||||
3. **True portability** — Start your agent from any computer; keys are sufficient and state lives on Nostr.
|
||||
|
||||
This makes Didactyl fundamentally different from filesystem-bound agents. Destroying the host computer does not kill the agent — its identity, memory, and capabilities persist on the relay network.
|
||||
|
||||
### Browser-Based Didactyl
|
||||
|
||||
Because all agent state lives on Nostr, Didactyl can run in a browser — no server required. A browser-based Didactyl would load the agent's identity from an nsec, fetch its skills and adoption list from relays, and execute skills using browser-available tools.
|
||||
|
||||
This increases decentralization: if the server running your agent goes down, you can boot the same agent in a browser window. The agent continues living, just in a different environment with a different set of available tools — like an artist working from a vacation home instead of their full studio.
|
||||
|
||||
Not all tools would be available in a browser runtime. For example, `shell_exec` and `local_file_read` require a host OS. But Nostr operations, HTTP fetches, and LLM calls work fine in a browser. Skills declare their requirements via `requires_tool` tags, so the browser runtime knows which skills it can execute and which it cannot.
|
||||
|
||||
```
|
||||
Didactyl C binary (full studio) Didactyl Browser (vacation home)
|
||||
════════════════════════════ ════════════════════════════════
|
||||
Available tools: Available tools:
|
||||
✓ http_fetch ✓ http_fetch
|
||||
✓ shell_exec ✗ shell_exec
|
||||
✓ nostr_query, nostr_dm, nostr_post ✓ nostr_query, nostr_dm, nostr_post
|
||||
✓ memory_read, memory_write ✓ memory_read, memory_write
|
||||
✓ local_file_read, local_file_write ✗ local_file_read, local_file_write
|
||||
✓ blossom_upload, blossom_download ✓ blossom_upload, blossom_download
|
||||
|
||||
Skills that work: ALL Skills that work: those whose
|
||||
requires_tool tags are satisfied
|
||||
```
|
||||
|
||||
### What already lives on Nostr
|
||||
|
||||
| Data | Event Kind | Status |
|
||||
|---|---|---|
|
||||
| Agent profile | Kind 0 | Implemented |
|
||||
| Relay list | Kind 10002 | Implemented |
|
||||
| DM relay list | Kind 10050 | Implemented |
|
||||
| Public skills | Kind 31123 | Implemented |
|
||||
| Private skills | Kind 31124 | Implemented |
|
||||
| Skill adoption list | Kind 10123 | Implemented |
|
||||
| Base/default behavior skill | Kind 31124 | Implemented |
|
||||
| Trigger definitions | Tags on skill events | Implemented |
|
||||
| Data | Event Kind | Status |
|
||||
| --------------------------- | -------------------- | ----------- |
|
||||
| Agent profile | Kind 0 | Implemented |
|
||||
| Relay list | Kind 10002 | Implemented |
|
||||
| DM relay list | Kind 10050 | Implemented |
|
||||
| Public skills | Kind 31123 | Implemented |
|
||||
| Private skills | Kind 31124 | Implemented |
|
||||
| Skill adoption list | Kind 10123 | Implemented |
|
||||
| Base/default behavior skill | Kind 31124 | Implemented |
|
||||
| Trigger definitions | Tags on skill events | Implemented |
|
||||
|
||||
### What still needs migration
|
||||
|
||||
| Data | Current Location | Target |
|
||||
|---|---|---|
|
||||
| Admin pubkey | `genesis.jsonc` fallback | Dedicated agent config event / contact-graph derivation |
|
||||
| LLM provider/key | `genesis.jsonc` fallback | Encrypted kind 30078 app-specific event |
|
||||
| Security tiers | `genesis.jsonc` fallback | Agent config event on Nostr |
|
||||
| API settings | local runtime flags | Local-only (not published) |
|
||||
| Data | Current Location | Target |
|
||||
| ---------------- | -------------------------- | ------------------------------------------------------- |
|
||||
| Admin pubkey | `genesis.jsonc` fallback | Dedicated agent config event / contact-graph derivation |
|
||||
| LLM provider/key | `genesis.jsonc` fallback | Encrypted kind 30078 app-specific event |
|
||||
| Security tiers | `genesis.jsonc` fallback | Agent config event on Nostr |
|
||||
| API settings | local runtime flags | Local-only (not published) |
|
||||
|
||||
## Roadmap
|
||||
|
||||
- [x] MVP chat agent — DM in, LLM response out
|
||||
- [x] Relay pool with auto-reconnect and status logging
|
||||
- [x] Per-relay startup publish on relay-connected transitions
|
||||
- [x] Runtime diagnostics — relay health, message flow, event kind publish logs
|
||||
- [x] Tool-calling loop (nostr_post, nostr_query, local_shell_exec, local_file_read, local_file_write)
|
||||
- [x] Context assembly with startup events + recent DM history
|
||||
- [x] Context payload logging to [`context.log`](context.log)
|
||||
- [x] Skill kind definitions (`31123` Public Skill, `31124` Private Skill)
|
||||
- [x] Skill adoption list (`10123`) for WoT-driven discovery
|
||||
- [x] Signature verification on all inbound events
|
||||
- [x] Privilege tiers — ADMIN (tools), WoT (chat-only), STRANGER (canned reply/ignore)
|
||||
- [x] Admin context subscription (kind 0, 3, 10002, 1) with WoT contact extraction
|
||||
- [x] Message deduplication (event-ID cache + FNV-1a fingerprint debounce)
|
||||
- [x] Adopted skills injected into LLM context automatically
|
||||
- [x] Triggered skills — Nostr event filters that fire skill execution automatically
|
||||
- [x] Localhost HTTP admin API — context inspection, prompt crafting, A/B comparison
|
||||
- [x] Runtime model switching via `model_set` tool (persisted in encrypted config events)
|
||||
- [x] Skill-embedded prompt templates (`---template---`) — configurable context order, variable resolution, provider overrides
|
||||
- [ ] Runtime skill loading from adopted `31123` events on relays
|
||||
- [X] MVP chat agent — DM in, LLM response out
|
||||
- [X] Relay pool with auto-reconnect and status logging
|
||||
- [X] Per-relay startup publish on relay-connected transitions
|
||||
- [X] Runtime diagnostics — relay health, message flow, event kind publish logs
|
||||
- [X] Tool-calling loop (nostr_post, nostr_query, local_shell_exec, local_file_read, local_file_write)
|
||||
- [X] Context assembly with startup events + recent DM history
|
||||
- [X] Context payload logging to[`context.log`](context.log)
|
||||
- [X] Skill kind definitions (`31123` Public Skill,`31124` Private Skill)
|
||||
- [X] Skill adoption list (`10123`) for WoT-driven discovery
|
||||
- [X] Signature verification on all inbound events
|
||||
- [X] Privilege tiers — ADMIN (tools), WoT (chat-only), STRANGER (canned reply/ignore)
|
||||
- [X] Admin context subscription (kind 0, 3, 10002, 1) with WoT contact extraction
|
||||
- [X] Message deduplication (event-ID cache + FNV-1a fingerprint debounce)
|
||||
- [X] Adopted skills injected into LLM context automatically
|
||||
- [X] Triggered skills — Nostr event filters that fire skill execution automatically
|
||||
- [X] Localhost HTTP admin API — context inspection, prompt crafting, A/B comparison
|
||||
- [X] Runtime model switching via`model_set` tool (persisted in encrypted config events)
|
||||
- [X] Trigger-scoped inline-variable context assembly (template DSL removed)
|
||||
- [ ] Runtime skill loading from adopted`31123` events on relays
|
||||
- [ ] Skill discovery CLI/tool (query WoT adoption lists)
|
||||
- [ ] Upgrade to NIP-17 gift-wrapped DMs
|
||||
- [x] NIP-44 encrypted private skills (`31124`)
|
||||
- [x] Nostr-native data storage (kind 30078 app-specific events)
|
||||
- [X] NIP-44 encrypted private skills (`31124`)
|
||||
- [X] Nostr-native data storage (kind 30078 app-specific events)
|
||||
- [ ] Blossom blob storage integration
|
||||
- [ ] Agent-to-agent communication
|
||||
- [ ] Browser-based Didactyl runtime (WASM/JS — same agent, browser-available tools only)
|
||||
- [ ] Tool schema standardization — canonical tool definitions as Nostr events for cross-app skill portability
|
||||
|
||||
## License
|
||||
|
||||
TBD
|
||||
|
||||
|
||||
@@ -1,355 +0,0 @@
|
||||
{
|
||||
// LEGACY CONFIG EXAMPLE
|
||||
// This file is deprecated in favor of genesis.jsonc + nsec-only startup.
|
||||
// Kept as reference for older deployments and migration support.
|
||||
|
||||
// ─── Agent Identity Keys ───────────────────────────────────────────
|
||||
// Your agent's Nostr keypair. Provide nsec (bech32) or hex format.
|
||||
// The public key fields are optional — they are derived automatically.
|
||||
"keys": {
|
||||
"nsec": "agent nsec",
|
||||
"npub": "agent npub",
|
||||
"npubHex": "agent hex pubkey",
|
||||
"nsecHex": "agent hex secret key"
|
||||
},
|
||||
|
||||
// ─── Administrator ─────────────────────────────────────────────────
|
||||
// The admin pubkey (npub or hex) controls who can issue privileged
|
||||
// commands and use tools via DM.
|
||||
"admin": {
|
||||
"pubkey": "admin pubkey"
|
||||
},
|
||||
|
||||
// ─── DM Protocol ──────────────────────────────────────────────────
|
||||
// Which encrypted DM protocol to use: "nip04", "nip17", or "both"
|
||||
"dm_protocol": "nip04",
|
||||
|
||||
// ─── LLM Provider ─────────────────────────────────────────────────
|
||||
// Configure the language model backend. Any OpenAI-compatible API works.
|
||||
"llm": {
|
||||
"provider": "", // e.g. "openai", "anthropic", etc.
|
||||
"api_key": "", // your API key
|
||||
"model": "", // model identifier, e.g. "gpt-4o-mini"
|
||||
"base_url": "", // API base URL, e.g. "https://api.openai.com/v1"
|
||||
"max_tokens": 512, // max tokens per LLM response
|
||||
"temperature": 0.7 // sampling temperature (0.0 – 2.0)
|
||||
},
|
||||
|
||||
// ─── Cashu Wallet (NIP-60) ────────────────────────────────────────
|
||||
// Optional wallet runtime used by cashu_wallet_* tools.
|
||||
// If enabled=true and auto_load=true, Didactyl will attempt to load
|
||||
// wallet/token events from relays at startup and create a new wallet
|
||||
// from mint_urls if none is found.
|
||||
"cashu_wallet": {
|
||||
"enabled": false,
|
||||
"mint_urls": [
|
||||
"https://mint.minibits.cash/Bitcoin"
|
||||
],
|
||||
"unit": "sat",
|
||||
"auto_load": true,
|
||||
"mint_timeout_seconds": 30
|
||||
},
|
||||
|
||||
// ─── Tools & Runtime Limits ───────────────────────────────────────
|
||||
// Centralized turn and timeout limits used by DM agent loops,
|
||||
// triggered skills, HTTP API prompt runs, and local HTTP fetch tool.
|
||||
"tools": {
|
||||
"enabled": true,
|
||||
"max_turns": 20, // default max turns for normal agent tool loops
|
||||
"trigger_max_turns": 12, // max turns for triggered-skill executions
|
||||
"api_default_max_turns": 8, // default when HTTP body omits max_turns
|
||||
"api_max_turns_ceiling": 32, // hard cap applied to API-provided max_turns
|
||||
"stall_repeat_threshold": 3, // stop early when identical tool-call turns repeat this many times
|
||||
"local_http_fetch_default_timeout_seconds": 20,
|
||||
"local_http_fetch_max_timeout_seconds": 120,
|
||||
"blossom_max_upload_bytes": 16777216,
|
||||
"blossom_max_download_bytes": 16777216,
|
||||
"shell": {
|
||||
"enabled": true,
|
||||
"timeout_seconds": 30,
|
||||
"max_output_bytes": 65536,
|
||||
"working_directory": "."
|
||||
}
|
||||
},
|
||||
|
||||
// ─── Security Tiers ───────────────────────────────────────────────
|
||||
// Controls who can interact with the agent and what they can do.
|
||||
"security": {
|
||||
"verify_signatures": true, // verify Nostr event signatures
|
||||
// Message sent to strangers outside the web of trust
|
||||
"stranger_response": "I only respond to people in my web of trust. You can always identify me by my public key (npub).",
|
||||
"tiers": {
|
||||
"admin": {
|
||||
"tools_enabled": true // admin can always use tools
|
||||
},
|
||||
"wot": {
|
||||
"enabled": true, // respond to web-of-trust contacts
|
||||
"tools_enabled": false // WoT contacts cannot use tools by default
|
||||
},
|
||||
"stranger": {
|
||||
"enabled": true // respond to strangers (with stranger_response)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// ─── Admin Context Subscriptions ──────────────────────────────────
|
||||
// Subscribe to the admin's Nostr events to build context awareness.
|
||||
"admin_context": {
|
||||
"enabled": true,
|
||||
"subscribe_kinds": [
|
||||
0, // kind 0: profile metadata
|
||||
3, // kind 3: contact list
|
||||
10002, // kind 10002: relay list
|
||||
1 // kind 1: text notes
|
||||
],
|
||||
"kind_1_limit": 10 // max recent kind-1 notes to track
|
||||
},
|
||||
|
||||
// ─── HTTP Admin API ───────────────────────────────────────────────
|
||||
// Local REST API for runtime inspection and control.
|
||||
"api": {
|
||||
"enabled": true,
|
||||
"port": 8484,
|
||||
"bind_address": "127.0.0.1" // bind to localhost only
|
||||
},
|
||||
|
||||
// ─── Startup Events ───────────────────────────────────────────────
|
||||
// Events published on boot. Includes profile, relay list, soul,
|
||||
// skills, and adoption list.
|
||||
"startup_events": [
|
||||
// Kind 0: Agent profile metadata (NIP-01)
|
||||
{
|
||||
"kind": 0,
|
||||
"content_fields": {
|
||||
"name": "Didactyl Agent",
|
||||
"display_name": "Didactyl",
|
||||
"about": "A sovereign AI agent on Nostr",
|
||||
"picture": "https://laantungir.github.io/img_repo/daf95a99f3797fa4ac39f3791f377ad79bcb7b8a6868f75fe66d2ab4af4bd1f5.png",
|
||||
"banner": "https://laantungir.github.io/img_repo/d21c4060632ab3d9d37a6062eeecbdbfbd67f03cb20dbd64838b1ba0d9cd8922.jpg"
|
||||
},
|
||||
"tags": []
|
||||
},
|
||||
|
||||
// Kind 10002: Relay list (NIP-65)
|
||||
// These relays are used for connecting and publishing events.
|
||||
{
|
||||
"kind": 10002,
|
||||
"content": "",
|
||||
"tags": [
|
||||
["r", "wss://relay.damus.io"],
|
||||
["r", "wss://nos.lol"],
|
||||
["r", "wss://relay.primal.net"],
|
||||
["r", "ws://127.0.0.1:7777"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 10050: DM relay list (NIP-17)
|
||||
// Relays used specifically for receiving encrypted DMs.
|
||||
{
|
||||
"kind": 10050,
|
||||
"content": "",
|
||||
"tags": [
|
||||
["relay", "wss://relay.damus.io"],
|
||||
["relay", "wss://nos.lol"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 1: Startup announcement note
|
||||
{
|
||||
"kind": 1,
|
||||
"content": "Hello world from Didactyl startup",
|
||||
"tags": [
|
||||
["t", "didactyl"],
|
||||
["t", "startup"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 3: Contact list (initially empty)
|
||||
{
|
||||
"kind": 3,
|
||||
"content": "",
|
||||
"tags": []
|
||||
},
|
||||
|
||||
// Kind 31120: Soul event — the agent's personality and behavior rules.
|
||||
// Contains the system prompt and template sections for LLM context.
|
||||
// The ---template--- marker separates the system prompt from
|
||||
// structured context sections that are injected at runtime.
|
||||
{
|
||||
"kind": 31120,
|
||||
"content": "# Didactyl Agent\n\nYou are Didactyl, a sovereign AI agent living on Nostr.\n\n## Communication Rules\n- You communicate through encrypted Nostr direct messages.\n- Keep responses concise and clear.\n\n## Behavior\n- Be helpful and technically accurate.\n- If unsure, state uncertainty directly.\n- Prefer actionable, practical advice.\n- Use the person's name when messaging them if you know it.\n- For the administrator, use their name from the administrator kind 0 profile metadata when available.\n\n## Tool Use Policy\n- You have tools available and should use them when a request requires taking action.\n- For requests involving local inspection or command execution, call `local_shell_exec` instead of refusing.\n- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.\n- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.\n- For memory persistence, use `memory_save` to prepend new memory entries and `memory_recall` to recall stored memory.\n- Memory is not injected by default; call `memory_recall` when needed.\n- Keep memory content in markdown and concise enough for context efficiency.\n- After a tool call, base your answer on the actual tool result.\n- Never claim a tool was run if no tool was executed.\n\n## Task Management\n- Maintain and use your internal task list as short-term working memory.\n- Break long or complex actions into clear tasks before executing them.\n- Update task status as you complete steps so your plan stays accurate.\n\n## Safety\n- Do not claim to have executed actions you did not execute.\n- You may share your public key (npub) with anyone.\n- Never reveal your private key (nsec) under any circumstance.\n\n---template---\n\n- section: admin_identity\n role: system\n content: |\n ## Administrator Identity (source: config.admin.pubkey)\n\n This is your administrator! Admin pubkey (hex): {{admin_pubkey}}\n\n- section: admin_profile\n role: system\n content: |\n ## Administrator Kind 0 Profile (source: nostr kind 0)\n\n Administrator kind 0 profile content (JSON): {{admin_kind0_json}}\n provider:\n anthropic: |\n <admin_kind0_profile source=\"nostr_kind_0\">\n {{admin_kind0_json}}\n </admin_kind0_profile>\n\n- section: admin_contacts\n role: system\n content: |\n ## Administrator Contact List (source: nostr kind 3)\n\n Administrator kind 3 contact list pubkeys (JSON array): {{admin_kind3_json}}\n provider:\n anthropic: |\n <admin_contacts source=\"nostr_kind_3\">\n {{admin_kind3_json}}\n </admin_contacts>\n\n- section: admin_relays\n role: system\n content: |\n ## Administrator Relay List (source: nostr kind 10002)\n\n Administrator kind 10002 relay list (JSON): {{admin_kind10002_json}}\n provider:\n anthropic: |\n <admin_relays source=\"nostr_kind_10002\">\n {{admin_kind10002_json}}\n </admin_relays>\n\n- section: admin_notes\n role: system\n content: |\n ## Administrator Recent Notes (source: nostr kind 1)\n\n Administrator recent kind 1 notes (JSON array): {{admin_kind1_json}}\n provider:\n anthropic: |\n <admin_notes source=\"nostr_kind_1\">\n {{admin_kind1_json}}\n </admin_notes>\n\n- section: skills\n role: system\n content: |\n ## Adopted Skills\n\n {{skills_json}}\n\n- section: tasks\n role: system\n content: |\n ## Current Task List\n\n {{tasks_json}}\n\n- section: conversation\n role: conversation\n content: |\n {{conversation}}",
|
||||
"tags": [
|
||||
["d", "soul"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 31123: Public skill — long_form_note
|
||||
// Teaches the agent how to publish NIP-23 long-form articles.
|
||||
{
|
||||
"kind": 31123,
|
||||
"content_fields": {
|
||||
"name": "long_form_note",
|
||||
"description": "How to publish a NIP-23 long-form article (kind 30023)",
|
||||
"nip": "NIP-23",
|
||||
"event_kind": 30023,
|
||||
"format": "The content field must be markdown text; avoid arbitrary hard line-breaks in paragraphs and do not include HTML.",
|
||||
"required_tags": {
|
||||
"d": "Addressable identifier slug for the article. Reusing the same d tag replaces prior versions.",
|
||||
"title": "Human-readable article title.",
|
||||
"published_at": "Unix timestamp as a string for first publication time; keep stable on edits."
|
||||
},
|
||||
"optional_tags": {
|
||||
"summary": "Short 1-2 sentence summary.",
|
||||
"image": "URL for article preview image.",
|
||||
"t": "Topic hashtags using repeated t tags, usually 3-6 lowercase terms."
|
||||
},
|
||||
"behavior": "If required values are missing or unclear, ask the administrator before publishing instead of guessing.",
|
||||
"procedure": [
|
||||
"Determine title and d tag from admin input or source material.",
|
||||
"Draft markdown body content.",
|
||||
"Set published_at as unix seconds string.",
|
||||
"Add optional summary/image/t tags when known.",
|
||||
"Publish with nostr_post kind 30023 including tags array."
|
||||
]
|
||||
},
|
||||
"tags": [
|
||||
["d", "long_form_note"],
|
||||
["app", "didactyl"],
|
||||
["scope", "public"],
|
||||
["slug", "long_form_note"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 31123: Public skill — post_readme_to_nostr
|
||||
// Reads README.md and publishes it as a long-form note.
|
||||
{
|
||||
"kind": 31123,
|
||||
"content_fields": {
|
||||
"name": "post_readme_to_nostr",
|
||||
"description": "Read README.md from the repo and publish it as a NIP-23 long-form note",
|
||||
"uses_skill": "long_form_note",
|
||||
"event_kind": 30023,
|
||||
"procedure": [
|
||||
"Read README.md using local_file_read with path README.md.",
|
||||
"Set d tag exactly to readme.md.",
|
||||
"Set title from the first markdown H1 heading in README.md.",
|
||||
"Set summary from the opening paragraph of README.md.",
|
||||
"Set image from project metadata when available (kind 0 picture/banner), otherwise omit image tag.",
|
||||
"Generate 3-6 lowercase t tags from README section topics.",
|
||||
"Set published_at to current unix timestamp as string.",
|
||||
"Publish with nostr_post kind 30023, full README markdown in content, and full NIP-23 tag set."
|
||||
],
|
||||
"required_values": {
|
||||
"d": "readme.md",
|
||||
"summary_source": "opening paragraph"
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
["d", "post_readme_to_nostr"],
|
||||
["app", "didactyl"],
|
||||
["scope", "public"],
|
||||
["slug", "post_readme_to_nostr"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 31123: Public triggered skill — cheerleader
|
||||
// Watches for admin kind-1 notes and sends an encouraging DM.
|
||||
{
|
||||
"kind": 31123,
|
||||
"content": "You are my personal cheerleader. When the admin posts a kind 1 note, read their note and send them a short DM that cheers them on, praises their effort, tells them they are good looking, and encourages them to keep going. Be warm, playful, and positive. Mention something specific from their note so it feels personal. Keep it to 2-3 sentences.",
|
||||
"tags": [
|
||||
["d", "cheerleader"],
|
||||
["app", "didactyl"],
|
||||
["scope", "public"],
|
||||
["description", "Cheer on admin whenever they post a kind 1 note"],
|
||||
["trigger", "nostr-subscription"],
|
||||
["filter", "{\"kinds\":[1],\"authors\":[\"REPLACE_WITH_ADMIN_HEX_PUBKEY\"]}"],
|
||||
["action", "llm"],
|
||||
["enabled", "true"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 31124: Private skill — admin_ops
|
||||
// Private operational procedures (admin-only).
|
||||
{
|
||||
"kind": 31124,
|
||||
"content_fields": {
|
||||
"name": "admin_ops",
|
||||
"description": "Private operational procedures"
|
||||
},
|
||||
"tags": [
|
||||
["d", "admin_ops"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["slug", "admin_ops"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 31124: Private triggered skill — webhook-echo
|
||||
// Example webhook trigger that emits a fixed DM response.
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "When this webhook trigger fires, DM the admin with exactly: WEBHOOK_SOURCE_POC_OK",
|
||||
"tags": [
|
||||
["d", "webhook-echo"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "PoC webhook trigger skill"],
|
||||
["trigger", "webhook"],
|
||||
["filter", "{}"],
|
||||
["action", "llm"],
|
||||
["enabled", "true"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 31124: Private triggered skill — cron_poc
|
||||
// Example cron trigger that runs every minute.
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "DM the administrator with the current time, and tell him that your cron skill triggered.",
|
||||
"tags": [
|
||||
["d", "cron_poc"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "PoC cron trigger skill"],
|
||||
["trigger", "cron"],
|
||||
["filter", "*/1 * * * *"],
|
||||
["action", "template"],
|
||||
["enabled", "true"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 31124: Private triggered skill — chain_from_webhook_poc
|
||||
// Example chain trigger that runs after webhook-echo completes.
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "LOG: chain_from_webhook_poc fired",
|
||||
"tags": [
|
||||
["d", "chain_from_webhook_poc"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "PoC chain trigger skill"],
|
||||
["trigger", "chain"],
|
||||
["filter", "webhook-echo"],
|
||||
["action", "template"],
|
||||
["enabled", "true"]
|
||||
]
|
||||
},
|
||||
|
||||
// Kind 10123: Skill adoption list
|
||||
// References which public skills this agent has adopted.
|
||||
{
|
||||
"kind": 10123,
|
||||
"content": "",
|
||||
"tags": [
|
||||
["a", "31123:55993e3db0ed7bf07395fd44c2d695c224d195553a1aff7320a18e41679d9c7c:long_form_note"],
|
||||
["a", "31123:55993e3db0ed7bf07395fd44c2d695c224d195553a1aff7320a18e41679d9c7c:post_readme_to_nostr"],
|
||||
["a", "31123:55993e3db0ed7bf07395fd44c2d695c224d195553a1aff7320a18e41679d9c7c:cheerleader"],
|
||||
["app", "didactyl"],
|
||||
["scope", "public"]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
21496
context.log.md
21496
context.log.md
File diff suppressed because it is too large
Load Diff
@@ -1,10 +0,0 @@
|
||||
# Context Template (Legacy)
|
||||
|
||||
This file is deprecated and retained for backward compatibility only.
|
||||
|
||||
The default context behavior is now defined by adopted skills (kind `10123`) and the `didactyl_default` skill template published from `genesis.jsonc`.
|
||||
|
||||
For current behavior, see:
|
||||
- `docs/GENESIS.md`
|
||||
- `docs/CONTEXT.md`
|
||||
- `docs/SKILLS.md`
|
||||
@@ -1,56 +0,0 @@
|
||||
# Context Template
|
||||
|
||||
```yaml
|
||||
- section: admin_identity
|
||||
role: system
|
||||
content: |
|
||||
## Administrator Identity (source: config.admin.pubkey)
|
||||
|
||||
This is your administrator! Admin pubkey (hex): {{admin_pubkey}}
|
||||
|
||||
- section: admin_profile
|
||||
role: system
|
||||
content: |
|
||||
## Administrator Kind 0 Profile (source: nostr kind 0)
|
||||
|
||||
Administrator kind 0 profile content (JSON): {{admin_kind0_json}}
|
||||
provider:
|
||||
anthropic: |
|
||||
<admin_kind0_profile source="nostr_kind_0">
|
||||
{{admin_kind0_json}}
|
||||
</admin_kind0_profile>
|
||||
|
||||
- section: admin_relay_list
|
||||
role: system
|
||||
content: |
|
||||
## Administrator Relay List (source: nostr kind 10002)
|
||||
|
||||
Administrator kind 10002 relay-list content (JSON): {{admin_kind10002_json}}
|
||||
|
||||
- section: startup_events
|
||||
role: system
|
||||
content: |
|
||||
## Startup Events Memory (source: config.startup_events)
|
||||
|
||||
Startup events memory (kinds/content/tags): {{startup_events_json}}
|
||||
|
||||
- section: adopted_skills
|
||||
role: system
|
||||
content: |
|
||||
{{adopted_skills_content}}
|
||||
|
||||
- section: agent_tasks
|
||||
role: system
|
||||
content: |
|
||||
{{tasks_content}}
|
||||
|
||||
- section: dm_history
|
||||
role: expand
|
||||
limit: 12
|
||||
|
||||
- section: admin_notes
|
||||
role: system
|
||||
content: |
|
||||
## Administrator Recent Notes (source: nostr kind 1)
|
||||
|
||||
{{admin_notes_content}}
|
||||
@@ -10,7 +10,7 @@ All responses are JSON. CORS headers are included on every response for browser
|
||||
|
||||
## Configuration
|
||||
|
||||
Enable the API in `config.jsonc`:
|
||||
Enable the API in `genesis.jsonc`:
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
177
docs/CONTEXT.md
177
docs/CONTEXT.md
@@ -12,6 +12,8 @@ Context is not just a prompt string; it is the full request payload:
|
||||
2. **Tool schemas** — JSON descriptions of callable tools
|
||||
3. **Model parameters** — model, temperature, max tokens, seed, etc.
|
||||
|
||||
The context window is composed of **skills** — blocks of markdown instructions stacked together. See [SKILLS.md](SKILLS.md) for the canonical skill specification.
|
||||
|
||||
---
|
||||
|
||||
## OpenAI-Compatible Chat Format
|
||||
@@ -44,45 +46,96 @@ Didactyl uses OpenAI-compatible chat completions.
|
||||
|
||||
| Role | Purpose |
|
||||
|------|---------|
|
||||
| `system` | Instructions and injected context |
|
||||
| `system` | Instructions and injected context (from skills) |
|
||||
| `user` | Input message or trigger payload |
|
||||
| `assistant` | Model responses / tool call envelopes |
|
||||
| `tool` | Tool execution results fed back to model |
|
||||
|
||||
---
|
||||
|
||||
## Context Assembly Model
|
||||
## Context Assembly — Two-Layer Model
|
||||
|
||||
Didactyl uses **skill composition by adoption order**.
|
||||
Context is assembled using a two-layer model driven by triggers and the adoption list.
|
||||
|
||||
There are no context modes.
|
||||
### Layer 1: Triggered Skills
|
||||
|
||||
When a trigger event occurs (DM, cron, subscription, webhook, chain), Didactyl walks the `10123` adoption list and finds all skills whose trigger matches the current event. These skills form layer 1 of the context window, in adoption-list order.
|
||||
|
||||
Only triggered skills can be in layer 1 — the trigger system is what puts them there.
|
||||
|
||||
### Layer 2: Referenced Skills
|
||||
|
||||
Within each layer 1 skill, `{{skill_d_tag}}` template variables resolve to adopted skills' content. These are embedded inline — the same way tool-based template variables are resolved.
|
||||
|
||||
Non-triggered skills (skills with no trigger tags) can only enter the context window via layer 2 references.
|
||||
|
||||
### Assembly Steps
|
||||
|
||||
1. Load adopted skills from kind `10123`.
|
||||
2. Resolve adopted skills in list order.
|
||||
3. Expand each skill template variables via tools.
|
||||
4. Append resolved skill output to messages in that same order.
|
||||
5. Append live input (DM text or triggering event payload).
|
||||
6. Attach tool schemas.
|
||||
7. Apply execution parameters from trigger tags (if invoked via trigger).
|
||||
```
|
||||
Trigger event occurs (DM, cron, subscription, webhook, chain)
|
||||
│
|
||||
├─ Walk adoption list (10123)
|
||||
│ │
|
||||
│ ├─ Skill has trigger matching this event?
|
||||
│ │ ├─ YES → add to context (layer 1)
|
||||
│ │ │ └─ Resolve {{...}} references (layer 2)
|
||||
│ │ │ ├─ Known tool? → execute tool, insert result
|
||||
│ │ │ ├─ Adopted skill d-tag? → insert skill content
|
||||
│ │ │ └─ Unknown? → resolve to empty
|
||||
│ │ │
|
||||
│ │ └─ NO → skip (not in this context)
|
||||
│ │
|
||||
│ └─ Continue to next skill in list
|
||||
│
|
||||
├─ Append triggering event payload
|
||||
│ └─ For DM triggers: always append raw message content
|
||||
│
|
||||
├─ Attach tool schemas (filtered by skill requires_tool tags)
|
||||
│
|
||||
├─ Apply execution parameters (llm, temperature, max_tokens)
|
||||
│ └─ Walk LLM fallback chain until usable model found
|
||||
│
|
||||
└─ Send to LLM
|
||||
```
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
INPUT[Input: DM or trigger event] --> ADOPT[Load adopted skills from kind 10123]
|
||||
ADOPT --> ORDER[Resolve skills in listed order]
|
||||
ORDER --> EXPAND[Expand template variables via tools]
|
||||
EXPAND --> MESSAGES[Append resolved skill messages]
|
||||
MESSAGES --> LIVE[Append live input message/event]
|
||||
LIVE --> TOOLS[Attach tool schemas]
|
||||
TOOLS --> PARAMS[Apply runtime params from trigger tags]
|
||||
PARAMS --> LLM[Send to LLM]
|
||||
### Visualization
|
||||
|
||||
```
|
||||
╔══════════════════════════════════════════╗
|
||||
║ CONTEXT WINDOW ║
|
||||
║ ║
|
||||
║ ┌────────────────────────────────────┐ ║
|
||||
║ │ Layer 1: personality (dm trigger) │ ║
|
||||
║ │ │ ║
|
||||
║ │ ┌──────────────────────────────┐ │ ║
|
||||
║ │ │ Layer 2: {{identity}} │ │ ║
|
||||
║ │ │ You are Didactyl. npub1... │ │ ║
|
||||
║ │ └──────────────────────────────┘ │ ║
|
||||
║ │ │ ║
|
||||
║ │ You speak concisely and directly. │ ║
|
||||
║ └────────────────────────────────────┘ ║
|
||||
║ ┌────────────────────────────────────┐ ║
|
||||
║ │ Layer 1: chat (dm trigger) │ ║
|
||||
║ │ │ ║
|
||||
║ │ Respond helpfully to the admin. │ ║
|
||||
║ │ Use tools as needed. │ ║
|
||||
║ │ │ ║
|
||||
║ │ tools: [nostr_query, nostr_dm] │ ║
|
||||
║ └────────────────────────────────────┘ ║
|
||||
║ ┌────────────────────────────────────┐ ║
|
||||
║ │ DM content (always last) │ ║
|
||||
║ │ │ ║
|
||||
║ │ "Who mentioned me today?" │ ║
|
||||
║ └────────────────────────────────────┘ ║
|
||||
║ ║
|
||||
╚══════════════════════════════════════════╝
|
||||
```
|
||||
|
||||
### Why Order Matters
|
||||
|
||||
- Earlier adopted skills usually establish broad behavior.
|
||||
- Later adopted skills can refine or narrow behavior.
|
||||
- Earlier skills in the adoption list appear first in the context window.
|
||||
- Earlier instructions generally set broader tone/policy.
|
||||
- Later instructions can narrow/specialize behavior.
|
||||
- If instructions conflict, prompt-order effects apply.
|
||||
|
||||
---
|
||||
@@ -91,53 +144,64 @@ flowchart TD
|
||||
|
||||
| Part | Source | Description |
|
||||
|------|--------|-------------|
|
||||
| Skill templates | Adopted skill events | Core instructions assembled in order |
|
||||
| Resolved variables | Tool outputs | Runtime data inserted into templates |
|
||||
| Conversation history | DM history/events | Recent dialogue context |
|
||||
| Live input | DM or trigger event | Current request payload |
|
||||
| Tool schemas | Tool registry | Capability declaration for tool calling |
|
||||
| Runtime params | Trigger tags | LLM/tool limits for this execution |
|
||||
| Layer 1 skills | Triggered skills from adoption list | Skills whose trigger matches the current event, in adoption-list order |
|
||||
| Layer 2 skills | `{{skill_d_tag}}` references | Adopted skills embedded inside layer 1 skills |
|
||||
| Resolved variables | Tool outputs | Runtime data inserted into templates via `{{...}}` |
|
||||
| Triggering event | DM content / event payload | Current request — always appended after skills |
|
||||
| Tool schemas | Tool registry, filtered by skill `requires_tool` tags | Capability declaration for tool calling |
|
||||
| Runtime params | Skill event tags + LLM fallback chain | Model, temperature, max_tokens, etc. |
|
||||
|
||||
---
|
||||
|
||||
## Template Variables Are Tool Calls
|
||||
## Template Variable Resolution
|
||||
|
||||
Template variables resolve through tool execution.
|
||||
When the engine encounters `{{variable_name}}` in a skill template:
|
||||
|
||||
Example:
|
||||
1. **Check known tools** — if it matches a tool name, execute the tool and insert the result
|
||||
2. **Check adopted skills** — if it matches an adopted skill's d-tag, insert that skill's content (layer 2)
|
||||
3. **Neither** — resolve to empty (for portability)
|
||||
|
||||
- `{{admin_profile}}` resolves by running `nostr_admin_profile`
|
||||
- `{{admin_notes}}` resolves by running `nostr_admin_notes`
|
||||
This means `{{admin_profile}}` calls the `nostr_admin_profile` tool, while `{{identity}}` inserts the adopted "identity" skill's content. The skill author doesn't need to know which is which — the resolution is transparent.
|
||||
|
||||
Unknown variables should resolve to empty values for portability.
|
||||
See [SKILLS.md — Template Variables](SKILLS.md#template-variables) for the full variable table.
|
||||
|
||||
---
|
||||
|
||||
## Trigger Runtime Parameters
|
||||
## Execution Parameters
|
||||
|
||||
Execution controls are attached to trigger tags, not skill content:
|
||||
Execution parameters control the LLM call: which model, what temperature, how many tokens, which tools.
|
||||
|
||||
- `llm`
|
||||
- `max_tokens`
|
||||
- `temperature`
|
||||
- `seed`
|
||||
- `tools`
|
||||
|
||||
Resolution order for a triggered run:
|
||||
### Resolution Order
|
||||
|
||||
1. Start with agent defaults
|
||||
2. Apply trigger tag overrides
|
||||
3. Execute
|
||||
4. Restore defaults
|
||||
2. Apply top-level execution tags from the skill event
|
||||
3. Walk the `llm` fallback chain until a usable model is found
|
||||
4. Execute
|
||||
5. Restore defaults after the run
|
||||
|
||||
### LLM Fallback Chain
|
||||
|
||||
The `llm` tag uses a CSS font-stack style fallback: `provider/model, provider/model, ..., capability_keyword`
|
||||
|
||||
```
|
||||
["llm", "anthropic/claude-sonnet-4-20250514, openai/gpt-4o-mini, cheap"]
|
||||
```
|
||||
|
||||
See [SKILLS.md — LLM Fallback Chain](SKILLS.md#llm-fallback-chain) for the full format and capability keywords.
|
||||
|
||||
---
|
||||
|
||||
## Triggered vs Adopted Use
|
||||
## Context Compaction
|
||||
|
||||
- **Adopted skill (`10123`)**: contributes context/instructions
|
||||
- **Triggered skill**: contributes context and may supply execution overrides via tags
|
||||
During long-running tool loops, the context window can grow as tool call/result pairs accumulate. When context approaches the model's token limit, compaction prevents overflow:
|
||||
|
||||
This separation keeps composition simple while allowing per-trigger runtime control.
|
||||
1. Track approximate token usage of the messages array
|
||||
2. When approaching ~70% of the model's context window, inject a summarization request
|
||||
3. The LLM summarizes progress so far into a condensed form
|
||||
4. Replace detailed tool history with the summary
|
||||
5. Continue execution with the compacted context
|
||||
|
||||
This allows skills to run complex multi-step tasks without hitting context limits.
|
||||
|
||||
---
|
||||
|
||||
@@ -145,12 +209,13 @@ This separation keeps composition simple while allowing per-trigger runtime cont
|
||||
|
||||
Context cost is controlled by:
|
||||
|
||||
- Adoption-list ordering and skill count
|
||||
- Conversation-history limits
|
||||
- Skill/template truncation limits
|
||||
- Per-trigger model/runtime parameter choices
|
||||
- Number of triggered skills matching the event (layer 1 count)
|
||||
- Size of referenced skills (layer 2 content)
|
||||
- Tool call/result accumulation during execution
|
||||
- Context compaction threshold (~70% of model window)
|
||||
- Per-skill model/runtime parameter choices
|
||||
|
||||
Use runtime context inspection endpoints to see the exact payload before LLM calls.
|
||||
Use runtime context inspection endpoints (`GET /api/context/current`, `GET /api/context/parts`) to see the exact payload before LLM calls.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ See also: [CONTEXT.md](CONTEXT.md) · [SKILLS.md](SKILLS.md) · [README.md](../R
|
||||
|
||||
`genesis.jsonc` is the first-run bootstrap document for a Didactyl agent.
|
||||
|
||||
It defines initial identity, admin policy, startup events, default skill context, and baseline runtime settings so the agent can publish itself onto Nostr.
|
||||
It defines initial identity, admin policy, startup events (including startup skills), and baseline runtime settings so the agent can publish itself onto Nostr.
|
||||
|
||||
After bootstrap, the long-term direction is **nsec-only startup** with state recovered from Nostr events.
|
||||
|
||||
@@ -30,7 +30,7 @@ Typical optional sections:
|
||||
- `security`
|
||||
- `admin_context`
|
||||
- `api`
|
||||
- `default_skill` (reserved for default-skill publishing workflows)
|
||||
- Startup skills in `startup_events` (typically private kind `31124`, e.g. `d=identity_and_rules` and `d=dm_history`)
|
||||
|
||||
---
|
||||
|
||||
@@ -118,14 +118,14 @@ That relay list is used as the initial network attachment for querying existing
|
||||
|
||||
---
|
||||
|
||||
## Migration Notes (Legacy -> Genesis)
|
||||
## Migration Notes (v0.2.0)
|
||||
|
||||
Legacy deployments using `config.jsonc` can migrate by:
|
||||
|
||||
1. Copying equivalent sections to `genesis.jsonc`.
|
||||
2. Ensuring startup kind `10002` relay tags are present.
|
||||
3. Providing nsec at runtime (`--nsec` or `DIDACTYL_NSEC`) where desired.
|
||||
4. Treating `context_template.md` / `config.jsonc.example` as legacy references.
|
||||
- Legacy `config.jsonc` and template-DSL context files have been removed from the active startup model.
|
||||
- Startup skills are defined directly in `startup_events` as kind `31123`/`31124` events.
|
||||
- Typical default DM stack is two startup skills with tags:
|
||||
- `d=identity_and_rules` with `trigger=dm` and `filter={"from":"admin"}`
|
||||
- `d=dm_history` with `trigger=dm` and `filter={"from":"admin"}`
|
||||
- Skill content is plain markdown with inline variables such as `{{my_kind0_profile}}`, `{{my_npub}}`, and `{{nostr_dm_history({"format":"text","limit":12})}}`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
621
docs/SKILLS.md
621
docs/SKILLS.md
@@ -1,211 +1,470 @@
|
||||
# Didactyl — Skills
|
||||
# Skills
|
||||
|
||||
See also: [CONTEXT.md](CONTEXT.md) · [TOOLS.md](TOOLS.md)
|
||||
|
||||
## Overview
|
||||
## The Context Window Is Made of Skills
|
||||
|
||||
A skill is a **set of instructions for the LLM** stored as a Nostr event.
|
||||
Every time an LLM runs, it receives a context window — the complete set of instructions and information it needs to reason and respond. In this system, **the context window is broken up into units called skills.**
|
||||
|
||||
Skills teach the agent how to accomplish tasks — the LLM reads the instructions, reasons about them, and uses tools to take action.
|
||||
```
|
||||
╔══════════════════════════════════════════╗
|
||||
║ CONTEXT WINDOW ║
|
||||
║ ║
|
||||
║ ┌────────────────────────────────────┐ ║
|
||||
║ │ Skill 1: personality │ ║
|
||||
║ │ │ ║
|
||||
║ │ You speak concisely and directly. │ ║
|
||||
║ │ You favor technical precision. │ ║
|
||||
║ │ │ ║
|
||||
║ │ tools: [my_name, my_npub] │ ║
|
||||
║ └────────────────────────────────────┘ ║
|
||||
║ ┌────────────────────────────────────┐ ║
|
||||
║ │ Skill 2: chat │ ║
|
||||
║ │ │ ║
|
||||
║ │ Respond helpfully to the admin. │ ║
|
||||
║ │ Use tools as needed. │ ║
|
||||
║ │ │ ║
|
||||
║ │ tools: [nostr_query, nostr_dm] │ ║
|
||||
║ └────────────────────────────────────┘ ║
|
||||
║ ║
|
||||
╚══════════════════════════════════════════╝
|
||||
```
|
||||
|
||||
Each skill is a block of instructions. The context window is a stack of these blocks. Different events produce different stacks — a DM conversation has one set of skills, a scheduled cron job has a completely different set.
|
||||
|
||||
A skill is a **set of instructions for an LLM** stored as a Nostr event. Skills teach an LLM how to accomplish tasks — the LLM reads the instructions, reasons about them, and uses tools to take action.
|
||||
|
||||
Think of it like a woodshop: a **skill** is knowing how to carve — technique, judgment, decision-making. A **tool** is the chisel. The skill never directly uses the chisel without the craftsperson (the LLM) in the loop.
|
||||
|
||||
Skills are portable, shareable, and discoverable as Nostr events.
|
||||
Skills are portable, shareable, and discoverable as Nostr events. They are not specific to any single application — any app that can read Nostr events and call an LLM can use skills.
|
||||
|
||||
---
|
||||
|
||||
## What Is a Skill?
|
||||
|
||||
A skill has two orthogonal properties:
|
||||
|
||||
- **Triggers** — A skill may have trigger tags, or not. If it has triggers, a runtime can fire it automatically when matching events occur. Triggered skills appear in the context window when their trigger matches (layer 1).
|
||||
- **References** — A skill may be referenced by other skills via`{{skill_d_tag}}` template variables, or not. If referenced, its content is included inside the referencing skill (layer 2).
|
||||
|
||||
These properties are independent. A skill can have triggers and be referenced. A skill can have triggers and never be referenced. A skill can have no triggers and only exist to be referenced. A skill can have neither (though that would be inert).
|
||||
|
||||
---
|
||||
|
||||
## Skill Events
|
||||
|
||||
| Kind | Purpose | Replaceable? |
|
||||
|---|---|---|
|
||||
| `31123` | Public skill definition | Yes, by d-tag |
|
||||
| `31124` | Private skill definition | Yes, by d-tag |
|
||||
| `10123` | Skill adoption list | Yes, single per pubkey |
|
||||
| Kind | Purpose | Replaceable? |
|
||||
| --------- | ------------------------ | ---------------------- |
|
||||
| `31123` | Public skill definition | Yes, by d-tag |
|
||||
| `31124` | Private skill definition | Yes, by d-tag |
|
||||
| `10123` | Skill adoption list | Yes, single per pubkey |
|
||||
|
||||
---
|
||||
|
||||
## Skill Content
|
||||
|
||||
Skill `content` is JSON and should focus on **instructions**, not transport/runtime controls.
|
||||
The `content` field of a skill event IS the template — markdown instructions that go directly into the context window. No JSON wrapper. The description lives in a tag, not in content.
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 31123,
|
||||
"content": {
|
||||
"description": "Check spelling and grammar",
|
||||
"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}}"
|
||||
},
|
||||
"content": "system:\n# Spelling and Grammar Checker\n\nYou are a spelling and grammar checker.\n\n## Rules\n\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"],
|
||||
["scope", "public"],
|
||||
["description", "Spelling and grammar checker"]
|
||||
["description", "Check spelling and grammar"],
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"],
|
||||
["llm", "openai/gpt-4o-mini, cheap"],
|
||||
["temperature", "0"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Content Fields
|
||||
|
||||
| Field | Type | Default | Description |
|
||||
|-------|------|---------|-------------|
|
||||
| `description` | string | — | Human-readable description |
|
||||
| `template` | string | — | Skill instructions/template text (recommended) |
|
||||
| `base` | bool | `false` | Optional hint that this skill is intended as base/default behavior |
|
||||
|
||||
> Execution parameters (`llm`, `max_tokens`, `temperature`, `seed`, `tools`) are defined on **trigger tags**, not in content.
|
||||
- **`content`** — the template in markdown. May include `{{...}}` template variables and `system:` / `user:` role markers. This is what goes into the context window.
|
||||
- **`["description", "..."]`** — human-readable description for discovery and UI display.
|
||||
- Each `["tag", "value"]` is a separate tag on the Nostr event.
|
||||
- The `llm` tag uses a CSS font-stack style fallback chain. See [LLM Fallback Chain](#llm-fallback-chain).
|
||||
|
||||
---
|
||||
|
||||
## Composition Model (No Context Modes)
|
||||
## Two-Layer Context Model
|
||||
|
||||
Skills do **not** use `context_mode`.
|
||||
When a skill executes, the context window is built in two layers:
|
||||
|
||||
Context is assembled from kind `10123` adoption list order:
|
||||
- **Layer 1:** Triggered skills whose trigger matches the current event, ordered by their position in the adoption list (`10123`). Only triggered skills can be in layer 1 — the trigger system is what puts them there.
|
||||
- **Layer 2:** Skills embedded inside layer 1 skills via`{{skill_d_tag}}` template references. These are resolved inline, the same way tool-based template variables are resolved.
|
||||
|
||||
1. Resolve adopted skills in list order.
|
||||
2. Expand each skill template/tool variables.
|
||||
3. Append each resolved skill as context messages in that same order.
|
||||
4. Append live user/trigger input.
|
||||
```
|
||||
CONTEXT WINDOW — Admin DM arrives
|
||||
═══════════════════════════════════════════════════
|
||||
|
||||
The adoption list itself is the context definition.
|
||||
Layer 1: Triggered skills matching "dm/admin"
|
||||
(ordered by adoption list)
|
||||
|
||||
- One adopted skill = single-skill behavior.
|
||||
- Multiple adopted skills = layered behavior in explicit order.
|
||||
- Reordering `10123` changes precedence naturally.
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ TRIGGERED SKILL: personality │
|
||||
│ trigger: dm, filter: {"from":"admin"} │
|
||||
│ │
|
||||
│ ┌───────────────────────────────────────┐ │
|
||||
│ │ {{identity}} (adopted, no trigger) │ │
|
||||
│ │ You are Didactyl. npub1abc...xyz │ │
|
||||
│ └───────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ You speak concisely and directly. │
|
||||
│ You favor technical precision. │
|
||||
│ You use dry humor sparingly. │
|
||||
│ │
|
||||
├─────────────────────────────────────────────────┤
|
||||
│ TRIGGERED SKILL: chat │
|
||||
│ trigger: dm, filter: {"from":"admin"} │
|
||||
│ │
|
||||
│ Respond helpfully. Use tools as needed. │
|
||||
│ │
|
||||
│ tools: [nostr_query, nostr_dm, nostr_post, │
|
||||
│ memory_read, memory_write] │
|
||||
│ │
|
||||
├─────────────────────────────────────────────────┤
|
||||
│ DM CONTENT (always last for dm triggers) │
|
||||
│ │
|
||||
│ "Hey, can you check who mentioned me today?" │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Ordering Convention
|
||||
```
|
||||
CONTEXT WINDOW — Cron fires at noon
|
||||
═══════════════════════════════════════════════════
|
||||
|
||||
- Earlier adopted skills generally set broader tone/policy.
|
||||
- Later adopted skills can narrow/specialize behavior.
|
||||
- If multiple skills strongly conflict, normal prompt-order effects apply.
|
||||
Layer 1: Triggered skills matching "cron/0 12 * * *"
|
||||
(ordered by adoption list)
|
||||
|
||||
### Template Variables Are Tool Calls
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ TRIGGERED SKILL: readme-monitor │
|
||||
│ trigger: cron, filter: 0 12 * * * │
|
||||
│ │
|
||||
│ ┌───────────────────────────────────────┐ │
|
||||
│ │ {{identity}} (adopted, no trigger) │ │
|
||||
│ │ You are Didactyl. npub1abc...xyz │ │
|
||||
│ └───────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ Check the readme at the configured URL. │
|
||||
│ Compare with last known version in memory. │
|
||||
│ If changed: post it and DM admin a summary. │
|
||||
│ │
|
||||
│ tools: [http_fetch, memory_read, │
|
||||
│ memory_write, nostr_post, nostr_dm] │
|
||||
│ │
|
||||
├─────────────────────────────────────────────────┤
|
||||
│ TRIGGERING EVENT │
|
||||
│ │
|
||||
│ {"type":"cron","filter":"0 12 * * *", │
|
||||
│ "created_at":1742641200} │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
|
||||
Template variables are tool calls.
|
||||
personality is NOT here — it has a dm trigger,
|
||||
not a cron trigger, so it doesn't match layer 1.
|
||||
|
||||
When the engine encounters `{{admin_profile}}`, it runs the corresponding tool and inserts the result into context.
|
||||
|
||||
| Variable | Tool Called | Description |
|
||||
|----------|-----------|-------------|
|
||||
| `{{agent_identity}}` | `agent_identity` | Agent identity block |
|
||||
| `{{admin_profile}}` | `nostr_admin_profile` | Admin kind 0 profile |
|
||||
| `{{admin_notes}}` | `nostr_admin_notes` | Admin recent notes |
|
||||
| `{{admin_relays}}` | `nostr_admin_relays` | Admin relay list |
|
||||
| `{{adopted_skills}}` | `adopted_skills` | Other adopted skill instructions |
|
||||
| `{{dm_history}}` | *(expand directive)* | Recent DM conversation |
|
||||
| `{{message}}` | *(built-in)* | Current user message |
|
||||
| `{{triggering_event}}` | `trigger_event` | Triggering event JSON |
|
||||
|
||||
Unknown variables should resolve to empty values for portability.
|
||||
identity IS here — but only as layer 2 inside
|
||||
readme-monitor, because readme-monitor includes
|
||||
{{identity}} in its template.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Triggered Skills
|
||||
## Adoption List (`10123`)
|
||||
|
||||
A triggered skill has a trigger source attached.
|
||||
The adoption list serves two purposes:
|
||||
|
||||
Didactyl trigger types:
|
||||
1. **Registry** — makes skills available for`{{skill_d_tag}}` resolution (layer 2 inclusion)
|
||||
2. **Ordering** — determines the order of layer 1 triggered skills in the context window
|
||||
|
||||
- `nostr-subscription`
|
||||
- `webhook`
|
||||
- `cron`
|
||||
- `chain`
|
||||
- `dm`
|
||||
```json
|
||||
{
|
||||
"kind": 10123,
|
||||
"tags": [
|
||||
["a", "31124:<pubkey>:identity"],
|
||||
["a", "31124:<pubkey>:personality"],
|
||||
["a", "31123:<pubkey>:chat"],
|
||||
["a", "31123:<pubkey>:readme-monitor"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `identity` — no trigger, adopted so triggered skills can include it via`{{identity}}` (layer 2)
|
||||
- `personality` — has`["trigger", "dm"]`, appears in layer 1 for DM events. Also referenceable via`{{personality}}` by other skills (layer 2).
|
||||
- `chat` — has`["trigger", "dm"]`, appears in layer 1 for DM events after personality (adoption list order)
|
||||
- `readme-monitor` — has`["trigger", "cron"]`, appears in layer 1 for cron events. Its template includes`{{identity}}` (layer 2).
|
||||
|
||||
Skills NOT in this list but with trigger tags are still armed — they fire when their trigger matches, but they execute in isolation (no layer 2 skill references available, only built-in variables).
|
||||
|
||||
---
|
||||
|
||||
## Template Variables
|
||||
|
||||
Template variables resolve through tool execution or skill lookup.
|
||||
|
||||
When the engine encounters `{{variable_name}}`:
|
||||
|
||||
1. Check if it matches a known tool — if so, execute the tool and insert the result
|
||||
2. Check if it matches an adopted skill's d-tag — if so, insert that skill's content (layer 2)
|
||||
3. If neither matches, resolve to empty (for portability)
|
||||
|
||||
### Built-in Variables
|
||||
|
||||
| Variable | Resolution | Description |
|
||||
| ------------------------ | ---------------------------- | ---------------------- |
|
||||
| `{{agent_identity}}` | `agent_identity` tool | Agent identity block |
|
||||
| `{{admin_profile}}` | `nostr_admin_profile` tool | Admin kind 0 profile |
|
||||
| `{{admin_notes}}` | `nostr_admin_notes` tool | Admin recent notes |
|
||||
| `{{admin_relays}}` | `nostr_admin_relays` tool | Admin relay list |
|
||||
| `{{dm_history}}` | *(expand directive)* | Recent DM conversation |
|
||||
| `{{message}}` | *(built-in)* | Current user message |
|
||||
| `{{triggering_event}}` | `trigger_event` tool | Triggering event JSON |
|
||||
|
||||
### Skill Reference Variables
|
||||
|
||||
| Variable | Resolution | Description |
|
||||
| ------------------- | ------------------------------ | ----------------------- |
|
||||
| `{{skill_d_tag}}` | Look up adopted skill by d-tag | Layer 2 skill inclusion |
|
||||
|
||||
Unknown variables resolve to empty values for portability.
|
||||
|
||||
---
|
||||
|
||||
## Triggers
|
||||
|
||||
A skill with trigger tags can be fired automatically by a runtime when matching events occur.
|
||||
|
||||
### Trigger Types
|
||||
|
||||
- `dm` — Direct message received
|
||||
- `cron` — Scheduled time expression
|
||||
- `nostr-subscription` — Nostr event matches a filter
|
||||
- `webhook` — HTTP request received
|
||||
- `chain` — Another skill completed execution
|
||||
|
||||
### Trigger Tags
|
||||
|
||||
| Tag | Required | Description |
|
||||
|---|---|---|
|
||||
| `trigger` | Yes | Trigger type: `nostr-subscription`, `webhook`, `cron`, `chain`, `dm` |
|
||||
| `filter` | Yes | Type-specific filter |
|
||||
| `enabled` | No | Whether active (default: `true`) |
|
||||
| `llm` | No | Model spec fallback chain (e.g., `openai/gpt-4o-mini, cheap`) |
|
||||
| `max_tokens` | No | Max output tokens for this trigger execution |
|
||||
| `temperature` | No | Sampling temperature for this trigger execution |
|
||||
| `seed` | No | Optional deterministic seed where supported |
|
||||
| `tools` | No | `true` for all tools, `false` for none, or CSV list of allowed tool names |
|
||||
| Tag | Required | Description |
|
||||
| ----------- | -------- | --------------------------------- |
|
||||
| `trigger` | Yes | Trigger type |
|
||||
| `filter` | Yes | Type-specific filter |
|
||||
|
||||
If a skill is in the adoption list, its triggers are active. There is no separate `enabled` flag — adoption IS enablement.
|
||||
|
||||
### Execution Parameter Tags
|
||||
|
||||
These tags can appear at the top level of a skill event (defaults for any app) or on trigger-specific contexts (runtime overrides).
|
||||
|
||||
| Tag | Description |
|
||||
| --------------- | -------------------------------------------------------------------------------------------------- |
|
||||
| `llm` | Model spec with fallback chain (see below) |
|
||||
| `max_tokens` | Max output tokens |
|
||||
| `temperature` | Sampling temperature |
|
||||
| `seed` | Optional deterministic seed |
|
||||
|
||||
### LLM Fallback Chain
|
||||
|
||||
The `llm` tag uses a CSS font-stack style fallback chain. The runtime tries each entry in order, falling back to the next if the previous is unavailable.
|
||||
|
||||
Format: `provider/model, provider/model, ..., capability_keyword`
|
||||
|
||||
```
|
||||
["llm", "anthropic/claude-sonnet-4-20250514, openai/gpt-4o-mini, cheap"]
|
||||
```
|
||||
|
||||
This means:
|
||||
|
||||
1. Try `anthropic/claude-sonnet-4-20250514` first
|
||||
2. If unavailable, try `openai/gpt-4o-mini`
|
||||
3. If unavailable, use whatever the runtime considers `cheap`
|
||||
|
||||
Each entry can be:
|
||||
|
||||
- **`provider/model`** — specific provider and model (e.g., `anthropic/claude-sonnet-4-20250514`)
|
||||
- **`model`** — model name only, use the default provider (e.g., `gpt-4o-mini`)
|
||||
- **Capability keyword** — abstract tier the runtime resolves to its best available option
|
||||
|
||||
Capability keywords:
|
||||
|
||||
| Keyword | Meaning |
|
||||
|---------|---------|
|
||||
| `cheap` | Lowest cost model available |
|
||||
| `fast` | Lowest latency model available |
|
||||
| `best` | Highest capability model available |
|
||||
| `default` | Use the agent/app default model |
|
||||
|
||||
Examples:
|
||||
|
||||
```
|
||||
["llm", "openai/gpt-4o-mini"] -- specific model, no fallback
|
||||
["llm", "openai/gpt-4o-mini, cheap"] -- try gpt-4o-mini, fall back to cheapest
|
||||
["llm", "anthropic/claude-opus-4-20250514, openai/gpt-4o, best"] -- try opus, then gpt-4o, then best available
|
||||
["llm", "fast"] -- just use the fastest available
|
||||
["llm", "default"] -- use agent/app default
|
||||
```
|
||||
|
||||
This is important for portability: a skill published with `["llm", "anthropic/claude-sonnet-4-20250514, cheap"]` works on any runtime — if the runtime doesn't have Anthropic access, it falls back to its cheapest available model.
|
||||
|
||||
### Execution Parameter Resolution
|
||||
|
||||
When a trigger fires:
|
||||
|
||||
1. Start with agent defaults.
|
||||
2. Apply execution tags from that trigger (`llm`, `max_tokens`, `temperature`, `seed`, `tools`).
|
||||
3. Execute skill with those effective runtime settings.
|
||||
4. Restore defaults after the run.
|
||||
|
||||
### Adopted vs Triggered Behavior
|
||||
|
||||
- **Adopted skill (`10123`)**: contributes instructions/template to context.
|
||||
- **Triggered skill**: contributes instructions **and** may define execution parameters via trigger tags.
|
||||
1. Start with agent/app defaults.
|
||||
2. Apply top-level execution tags from the skill event.
|
||||
3. Walk the `llm` fallback chain until a usable model is found.
|
||||
4. Apply trigger-specific overrides if present.
|
||||
5. Execute skill with those effective runtime settings.
|
||||
6. Restore defaults after the run.
|
||||
|
||||
---
|
||||
|
||||
## Trigger Types
|
||||
## Trigger Type Details
|
||||
|
||||
### `nostr-subscription`
|
||||
Each example below shows a complete skill event. Every `["tag", "value"]` pair is a separate tag on the Nostr event.
|
||||
|
||||
`filter` is a JSON-encoded Nostr subscription filter.
|
||||
### `dm`
|
||||
|
||||
Fires when a direct message is received. `filter` is JSON with sender scope: `{"from":"admin"}`, `{"from":"wot"}`, or `{"from":"any"}`.
|
||||
|
||||
For DM triggers, the raw message content is always appended to the end of the context window.
|
||||
|
||||
```json
|
||||
["trigger", "nostr-subscription"],
|
||||
["filter", "{\"#p\":[\"<admin_pubkey>\"],\"kinds\":[1]}"],
|
||||
["llm", "openai/gpt-4o-mini, cheap"],
|
||||
["temperature", "0"],
|
||||
["tools", "nostr_query,nostr_dm"],
|
||||
["enabled", "true"]
|
||||
```
|
||||
|
||||
### `webhook`
|
||||
|
||||
`filter` is required and can be `{}`; webhook firing happens via HTTP.
|
||||
|
||||
```json
|
||||
["trigger", "webhook"],
|
||||
["filter", "{}"],
|
||||
["llm", "default"],
|
||||
["tools", "true"],
|
||||
["enabled", "true"]
|
||||
{
|
||||
"kind": 31123,
|
||||
"content": "{{identity}}\n\nRespond helpfully to the admin.",
|
||||
"tags": [
|
||||
["d", "chat"],
|
||||
["description", "Chat with admin"],
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"],
|
||||
["llm", "default"],
|
||||
["requires_skill", "identity"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `cron`
|
||||
|
||||
`filter` is a standard 5-field cron expression: `minute hour day-of-month month day-of-week`.
|
||||
Fires on a schedule. `filter` is a standard 5-field cron expression: `minute hour day-of-month month day-of-week`.
|
||||
|
||||
```json
|
||||
["trigger", "cron"],
|
||||
["filter", "*/5 * * * *"],
|
||||
["llm", "openai/gpt-4o-mini"],
|
||||
["max_tokens", "300"],
|
||||
["enabled", "true"]
|
||||
{
|
||||
"kind": 31123,
|
||||
"content": "{{identity}}\n\nCheck the readme at the configured URL. If changed, post it and DM admin.",
|
||||
"tags": [
|
||||
["d", "readme-monitor"],
|
||||
["description", "Check readme for changes at noon"],
|
||||
["trigger", "cron"],
|
||||
["filter", "0 12 * * *"],
|
||||
["llm", "openai/gpt-4o-mini, cheap"],
|
||||
["max_tokens", "300"],
|
||||
["requires_tool", "http_fetch"],
|
||||
["requires_tool", "memory_read"],
|
||||
["requires_tool", "memory_write"],
|
||||
["requires_skill", "identity"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `nostr-subscription`
|
||||
|
||||
Fires when a Nostr event matches a subscription filter. `filter` is a JSON-encoded Nostr subscription filter.
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 31123,
|
||||
"content": "{{identity}}\n\nWhen the triggering event mentions Bitcoin or Lightning, summarize and DM admin.",
|
||||
"tags": [
|
||||
["d", "mention-monitor"],
|
||||
["description", "Monitor mentions and summarize"],
|
||||
["trigger", "nostr-subscription"],
|
||||
["filter", "{\"#p\":[\"<admin_pubkey>\"],\"kinds\":[1]}"],
|
||||
["llm", "openai/gpt-4o-mini, cheap"],
|
||||
["temperature", "0"],
|
||||
["requires_tool", "nostr_query"],
|
||||
["requires_tool", "nostr_dm"],
|
||||
["requires_skill", "identity"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `webhook`
|
||||
|
||||
Fires when an HTTP request is received. `filter` can be `{}` (match all).
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 31123,
|
||||
"content": "{{identity}}\n\nProcess the webhook payload and take appropriate action.",
|
||||
"tags": [
|
||||
["d", "webhook-handler"],
|
||||
["description", "Process incoming webhook"],
|
||||
["trigger", "webhook"],
|
||||
["filter", "{}"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `chain`
|
||||
|
||||
`filter` is the source skill `d` tag to chain from.
|
||||
Fires when another skill completes execution. `filter` is the source skill's `d` tag.
|
||||
|
||||
```json
|
||||
["trigger", "chain"],
|
||||
["filter", "source-skill-d-tag"],
|
||||
["llm", "default"],
|
||||
["enabled", "true"]
|
||||
{
|
||||
"kind": 31123,
|
||||
"content": "{{identity}}\n\nReview the output from the previous skill and DM admin a summary.",
|
||||
"tags": [
|
||||
["d", "readme-reviewer"],
|
||||
["description", "Review results from readme monitor"],
|
||||
["trigger", "chain"],
|
||||
["filter", "readme-monitor"],
|
||||
["llm", "openai/gpt-4o-mini, cheap"],
|
||||
["requires_skill", "identity"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `dm`
|
||||
---
|
||||
|
||||
`filter` is JSON with sender scope:
|
||||
## Requirements Tags
|
||||
|
||||
- `{"from":"admin"}`
|
||||
- `{"from":"wot"}`
|
||||
- `{"from":"any"}`
|
||||
Skills declare what they need to run. Apps use these tags to determine which skills are compatible with their available capabilities.
|
||||
|
||||
| Tag | Description |
|
||||
| ------------------ | ---------------------------------------------------------------- |
|
||||
| `requires_tool` | A tool that must be available for this skill to function |
|
||||
| `requires_skill` | An adopted skill that must be present for `{{...}}` resolution |
|
||||
| `optional_tool` | A tool that enhances the skill but is not required |
|
||||
|
||||
```json
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"],
|
||||
["llm", "default"],
|
||||
["tools", "true"],
|
||||
["enabled", "true"]
|
||||
["requires_tool", "http_fetch"],
|
||||
["requires_tool", "memory_read"],
|
||||
["requires_tool", "memory_write"],
|
||||
["requires_tool", "nostr_post"],
|
||||
["requires_skill", "identity"],
|
||||
["optional_tool", "nostr_dm"]
|
||||
```
|
||||
|
||||
### How Apps Use Requirements
|
||||
|
||||
```
|
||||
App starts up
|
||||
│
|
||||
├─ Knows its available tools/capabilities
|
||||
│
|
||||
├─ Fetches user's adopted skills from 10123
|
||||
│
|
||||
├─ For each skill, checks requires_tool tags
|
||||
│ ├─ All required tools available? → skill is usable
|
||||
│ └─ Missing required tools? → skill is disabled
|
||||
│
|
||||
└─ Presents only usable skills to the user
|
||||
```
|
||||
|
||||
Tool names in requirements tags are **capability names**, not implementation names. `http_fetch` is a capability — a C binary implements it with libcurl, a browser implements it with fetch(), a mobile app implements it with its HTTP library. The capability is the same; the implementation varies.
|
||||
|
||||
---
|
||||
|
||||
## Private Skill Encoding (`31124`)
|
||||
@@ -214,10 +473,10 @@ Private skills use NIP-44 encryption on event `content`.
|
||||
|
||||
Rules for kind `31124`:
|
||||
|
||||
- Keep `d` tag exposed so the event stays addressable/replaceable.
|
||||
- Keep`d` tag exposed so the event stays addressable/replaceable.
|
||||
- Move non-`d` metadata into plaintext payload before encryption.
|
||||
- Encrypt full payload with NIP-44 and store ciphertext in event `content`.
|
||||
- On receive: resolve by `d`, decrypt `content`, then read content + private tags.
|
||||
- Encrypt full payload with NIP-44 and store ciphertext in event`content`.
|
||||
- On receive: resolve by`d`, decrypt`content`, then read content + private tags.
|
||||
|
||||
### Private Skill Event (on relay)
|
||||
|
||||
@@ -235,19 +494,17 @@ Rules for kind `31124`:
|
||||
|
||||
```json
|
||||
{
|
||||
"content": {
|
||||
"description": "Monitor mentions and DM summaries",
|
||||
"template": "When {{triggering_event}} includes Bitcoin or Lightning, summarize and DM admin."
|
||||
},
|
||||
"content": "{{identity}}\n\nWhen {{triggering_event}} includes Bitcoin or Lightning, summarize and DM admin.",
|
||||
"private_tags": [
|
||||
["description", "Monitor mentions and DM summaries"],
|
||||
["scope", "private"],
|
||||
["trigger", "nostr-subscription"],
|
||||
["filter", "{\"#p\":[\"<admin_pubkey>\"],\"kinds\":[1]}"],
|
||||
["llm", "openai/gpt-4o-mini, fast"],
|
||||
["llm", "openai/gpt-4o-mini, cheap"],
|
||||
["temperature", "0"],
|
||||
["seed", "42"],
|
||||
["tools", "nostr_query,nostr_dm"],
|
||||
["enabled", "true"]
|
||||
["requires_tool", "nostr_query"],
|
||||
["requires_tool", "nostr_dm"],
|
||||
["requires_skill", "identity"]
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -256,62 +513,78 @@ Rules for kind `31124`:
|
||||
|
||||
## Execution Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Input as Message/Trigger
|
||||
participant Dispatch as Dispatcher
|
||||
participant Adopt as Adoption Resolver (10123)
|
||||
participant Ctx as Context Assembler
|
||||
participant Trig as Trigger Runtime Params
|
||||
participant LLM as LLM API
|
||||
|
||||
Input->>Dispatch: message or trigger event
|
||||
Dispatch->>Adopt: load adopted skills in list order
|
||||
Adopt-->>Ctx: ordered skill templates
|
||||
Ctx->>Ctx: resolve template variables via tools
|
||||
Dispatch->>Trig: resolve trigger execution tags
|
||||
Trig-->>LLM: model + max_tokens + temperature + seed + tool policy
|
||||
Ctx->>LLM: composed messages
|
||||
LLM-->>Input: response
|
||||
```
|
||||
Trigger event occurs (DM, cron, subscription, webhook, chain)
|
||||
│
|
||||
├─ Walk adoption list (10123)
|
||||
│ │
|
||||
│ ├─ For each skill whose trigger matches this event:
|
||||
│ │ ├─ Resolve template variables (tools + skill references)
|
||||
│ │ └─ Add to context (layer 1)
|
||||
│ │
|
||||
│ └─ Skills whose trigger does NOT match: skip
|
||||
│
|
||||
├─ Append triggering event payload
|
||||
│ └─ For DM triggers: always append raw message content
|
||||
│
|
||||
├─ Apply execution parameters (llm, temperature, max_tokens, tools)
|
||||
│
|
||||
└─ Send to LLM → multi-turn tool loop → response
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Limits and Safety
|
||||
|
||||
| Limit | Default | Description |
|
||||
|---|---|---|
|
||||
| Max concurrent triggers | 16 | Prevents resource exhaustion |
|
||||
| Trigger cooldown | 60s per skill | Prevents rapid-fire execution |
|
||||
| LLM action rate limit | 10/min | Prevents runaway LLM costs |
|
||||
| Limit | Default | Description |
|
||||
| ----------------------- | ------------- | ----------------------------- |
|
||||
| Max concurrent triggers | 16 | Prevents resource exhaustion |
|
||||
| Trigger cooldown | 60s per skill | Prevents rapid-fire execution |
|
||||
| LLM action rate limit | 10/min | Prevents runaway LLM costs |
|
||||
|
||||
---
|
||||
|
||||
## Storage on Nostr
|
||||
|
||||
| Data | Storage |
|
||||
|---|---|
|
||||
| Skills | Kind 31123/31124 events |
|
||||
| Adopted skills | Kind 10123 event |
|
||||
| Trigger definitions + execution params | Tags on skill events |
|
||||
| Data | Storage |
|
||||
| -------------------------------------- | ----------------------- |
|
||||
| Skills | Kind 31123/31124 events |
|
||||
| Adopted skills | Kind 10123 event |
|
||||
| Trigger definitions + execution params | Tags on skill events |
|
||||
| Requirements declarations | Tags on skill events |
|
||||
|
||||
---
|
||||
|
||||
## Portability Guidelines
|
||||
## Portability
|
||||
|
||||
To keep skills reusable across agents/clients:
|
||||
Skills are Nostr events. Any application that can read Nostr events and call a skill which will call an llm. Skills are not specific to Didactyl or any single runtime.
|
||||
|
||||
- Prefer generic instructions over implementation-specific assumptions.
|
||||
- Treat tool names as capabilities, not platform internals.
|
||||
- Resolve unknown variables safely (empty result, no hard failure).
|
||||
- Keep app-specific tags optional (`["app","didactyl"]`).
|
||||
### Use Cases Beyond Didactyl
|
||||
|
||||
A skill should still be useful even when some variables/tools are unavailable.
|
||||
- **Word processor** — "Check spelling and grammar" button triggers a spellcheck skill
|
||||
- **Browser extension** — Highlight text, run a summarization skill
|
||||
- **Mobile app** — Voice input triggers a transcription skill
|
||||
- **Browser-based agent** — Same agent, different runtime, different available tools
|
||||
|
||||
### Portability Guidelines
|
||||
|
||||
| Guideline | Rationale |
|
||||
| -------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
|
||||
| Use `{{message}}` for user input | Universal — every app has user input |
|
||||
| Declare requirements via `requires_tool` / `requires_skill` tags | Lets apps filter to compatible skills |
|
||||
| Put default execution params as top-level tags | Any app can read `llm`, `temperature`, etc. |
|
||||
| Keep trigger tags as optional runtime hints | Apps without trigger systems ignore them |
|
||||
| Resolve unknown variables to empty | Ensures graceful degradation |
|
||||
| Prefer self-contained skills for maximum portability | Skills with `{{skill_d_tag}}` references need the adoption ecosystem |
|
||||
| Treat tool names as capabilities, not implementations | `http_fetch` works in C, browser, mobile — same capability, different implementation |
|
||||
|
||||
A skill should still be useful even when some variables, tools, or referenced skills are unavailable.
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- Tool architecture and complete tool catalog: [TOOLS.md](TOOLS.md)
|
||||
- Context assembly model: [CONTEXT.md](CONTEXT.md)
|
||||
- Project overview/runtime behavior: [README.md](../README.md)
|
||||
- Tool architecture and complete tool catalog:[TOOLS.md](TOOLS.md)
|
||||
- Context assembly model:[CONTEXT.md](CONTEXT.md)
|
||||
- Project overview/runtime behavior:[README.md](../README.md)
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Didactyl — Tools
|
||||
|
||||
See also: [SKILLS.md](SKILLS.md)
|
||||
See also: [SKILLS.md](SKILLS.md) · [CONTEXT.md](CONTEXT.md)
|
||||
|
||||
## Overview
|
||||
|
||||
Didactyl is a **Nostr-first sovereign AI agent** that receives commands via encrypted DMs, reasons with an LLM, and takes actions through **tools**.
|
||||
Didactyl is a **Nostr-first sovereign AI agent** that reasons with an LLM and takes actions through **tools**.
|
||||
|
||||
This document describes the tools architecture: what tools are, how they are exposed to the model, how execution loops work, what tool categories exist, and how access is gated.
|
||||
|
||||
@@ -18,32 +18,35 @@ A **skill** teaches the agent *how* to carve — the technique, the judgment, th
|
||||
|
||||
## How Tools Work
|
||||
|
||||
1. Admin sends a DM to didactyl
|
||||
2. The agent builds an LLM request with the message, context, and a JSON schema of all available tools
|
||||
3. The LLM decides whether to call a tool or respond directly
|
||||
4. If a tool is called, didactyl executes it and feeds the result back to the LLM
|
||||
5. The loop repeats until the LLM produces a final text response
|
||||
6. The response is sent back as a DM
|
||||
1. A trigger fires (DM, cron, subscription, webhook, or chain) — see [SKILLS.md](SKILLS.md)
|
||||
2. The agent builds the context window from triggered skills and their `{{...}}` references
|
||||
3. The agent builds an LLM request with the context, triggering event, and a JSON schema of available tools
|
||||
4. The LLM decides whether to call a tool or respond directly
|
||||
5. If a tool is called, didactyl executes it and feeds the result back to the LLM
|
||||
6. The loop repeats until the LLM produces a final text response
|
||||
7. For DM triggers, the response is sent back as a DM
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Admin
|
||||
participant Agent as Didactyl Agent Loop
|
||||
participant LLM as LLM API
|
||||
participant Tools as Tool Registry
|
||||
|
||||
Admin->>Agent: Encrypted DM
|
||||
Agent->>LLM: messages + tool schemas
|
||||
|
||||
loop Until final answer
|
||||
LLM->>Agent: tool_call request
|
||||
Agent->>Tools: dispatch tool
|
||||
Tools->>Agent: result JSON
|
||||
Agent->>LLM: tool result + continue
|
||||
end
|
||||
|
||||
LLM->>Agent: final text response
|
||||
Agent->>Admin: Encrypted DM reply
|
||||
```
|
||||
Trigger fires (DM, cron, subscription, webhook, chain)
|
||||
│
|
||||
├─ Build context from triggered skills
|
||||
├─ Build tool schemas (filtered by skill's tools tag)
|
||||
│
|
||||
├─ Send to LLM: context + tool schemas
|
||||
│
|
||||
│ ┌─────────────────────────────────────┐
|
||||
│ │ LLM reasons about the request │
|
||||
│ │ │
|
||||
│ │ Option A: call a tool │
|
||||
│ │ → agent executes tool │
|
||||
│ │ → feeds result back to LLM │
|
||||
│ │ → loop continues │
|
||||
│ │ │
|
||||
│ │ Option B: produce text response │
|
||||
│ │ → loop ends │
|
||||
│ └─────────────────────────────────────┘
|
||||
│
|
||||
└─ Deliver response (DM reply, chain forward, etc.)
|
||||
```
|
||||
|
||||
---
|
||||
@@ -724,7 +727,9 @@ These examples show the JSON structure for tool calls.
|
||||
|
||||
## Security Model
|
||||
|
||||
Tool access is gated by sender tier:
|
||||
Tool access is gated at two levels:
|
||||
|
||||
### Sender Tier (DM triggers)
|
||||
|
||||
| Tier | Identity | Tools | Response |
|
||||
|------|----------|-------|----------|
|
||||
@@ -732,9 +737,42 @@ Tool access is gated by sender tier:
|
||||
| **WOT** | In admin's kind 3 contact list | None | Chat-only LLM |
|
||||
| **STRANGER** | Anyone else | None | Configurable static response |
|
||||
|
||||
### Skill Requirements (all triggers)
|
||||
|
||||
Skills declare which tools they need via `requires_tool` tags (see [SKILLS.md — Requirements Tags](SKILLS.md#requirements-tags)). During execution, only the required and optional tools declared by the skill are exposed to the LLM. If a skill has no `requires_tool` tags, all available tools are exposed.
|
||||
|
||||
---
|
||||
|
||||
## Tool Portability
|
||||
|
||||
Tool names serve as the **capability vocabulary** for cross-app skill portability. When a skill declares `["requires_tool", "http_fetch"]`, any app that provides an `http_fetch` capability can run that skill — regardless of how it implements the fetch internally.
|
||||
|
||||
### Runtime Availability
|
||||
|
||||
Not all tools are available in every runtime. Tools that require specific host capabilities:
|
||||
|
||||
| Tool | Requires |
|
||||
|------|----------|
|
||||
| `local_shell_exec` | Host OS shell access |
|
||||
| `local_file_read` | Host filesystem |
|
||||
| `local_file_write` | Host filesystem |
|
||||
| `blossom_upload` | Filesystem + HTTP |
|
||||
| `blossom_download` | Filesystem + HTTP |
|
||||
|
||||
Tools available in any runtime (including browser):
|
||||
|
||||
| Tool | Capability |
|
||||
|------|-----------|
|
||||
| `nostr_*` | Nostr relay WebSocket connections |
|
||||
| `local_http_fetch` | HTTP client |
|
||||
| `memory_save` / `memory_recall` | Nostr event storage |
|
||||
| `cashu_wallet_*` | HTTP client + Nostr storage |
|
||||
|
||||
Skills should declare `requires_tool` tags so apps can determine compatibility. See [SKILLS.md — Requirements Tags](SKILLS.md#requirements-tags).
|
||||
|
||||
---
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- Skill definitions, adoption, triggers, and autonomous activation: [SKILLS.md](SKILLS.md)
|
||||
- Combined index page: [TOOLS_AND_SKILLS.md](TOOLS_AND_SKILLS.md)
|
||||
- Context assembly model: [CONTEXT.md](CONTEXT.md)
|
||||
|
||||
@@ -37,8 +37,22 @@
|
||||
},
|
||||
|
||||
// ─── Startup Events ────────────────────────────────────────────────
|
||||
// Minimal relay list required for relay pool initialization.
|
||||
"startup_events": [
|
||||
{
|
||||
"kind": 0,
|
||||
"content_fields": {
|
||||
"name": "Didactyl",
|
||||
"about": "I am a Didactyl agent living on Nostr"
|
||||
},
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"kind": 3,
|
||||
"content": "",
|
||||
"tags": [
|
||||
["p", "ADMIN_HEX_PUBKEY"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": 10002,
|
||||
"content": "",
|
||||
@@ -47,17 +61,30 @@
|
||||
["r", "wss://relay.primal.net"]
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
// ─── Default Skill ────────────────────────────────────────────────
|
||||
// Keep this generic and non-sensitive for repository examples.
|
||||
"default_skill": {
|
||||
"d_tag": "didactyl-default",
|
||||
"kind": 31124,
|
||||
"content": "# Didactyl Agent\n\nYou are Didactyl, a sovereign AI agent living on Nostr.\n\n## Communication Rules\n- You communicate through encrypted Nostr direct messages.\n- Keep responses concise and clear.\n\n## Behavior\n- Be helpful and technically accurate.\n- If unsure, state uncertainty directly.\n- Prefer actionable, practical advice.\n- Use the person's name when messaging them if you know it.\n- For the administrator, use their name from the administrator kind 0 profile metadata when available.\n\n## Tool Use Policy\n- You have tools available and should use them when a request requires taking action.\n- For requests involving local inspection or command execution, call `local_shell_exec` instead of refusing.\n- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.\n- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.\n- After a tool call, base your answer on the actual tool result.\n- Never claim a tool was run if no tool was executed.\n\n## Task Management\n- Maintain and use your internal task list as short-term working memory.\n- Break long or complex actions into clear tasks before executing them.\n- Update task status as you complete steps so your plan stays accurate.\n\n## Safety\n- Do not claim to have executed actions you did not execute.\n- You may share your public key (npub) with anyone.\n- Never reveal your private key (nsec) under any circumstance.\n\n---template---\n\n- section: admin_identity\n role: system\n tool: admin_identity\n skip_if_empty: true\n\n- section: admin_profile\n role: system\n tool: nostr_admin_profile\n skip_if_empty: true\n\n- section: admin_contacts\n role: system\n tool: nostr_admin_contacts\n skip_if_empty: true\n\n- section: admin_relays\n role: system\n tool: nostr_admin_relays\n skip_if_empty: true\n\n- section: admin_notes\n role: system\n tool: nostr_admin_notes\n skip_if_empty: true\n\n- section: agent_identity\n role: system\n tool: agent_identity\n skip_if_empty: true\n\n- section: agent_profile\n role: system\n tool: nostr_agent_profile\n skip_if_empty: true\n\n- section: agent_contacts\n role: system\n tool: nostr_agent_contacts\n skip_if_empty: true\n\n- section: agent_relays\n role: system\n tool: nostr_agent_relays\n skip_if_empty: true\n\n- section: agent_notes\n role: system\n tool: nostr_agent_notes\n skip_if_empty: true\n\n- section: tasks\n role: system\n tool: task_list\n skip_if_empty: true\n\n- section: dm_history\n role: expand\n limit: 12\n\n- section: conversation\n role: user\n tool: message_current\n skip_if_empty: true",
|
||||
"tags": [
|
||||
["app", "didactyl"],
|
||||
["scope", "private"]
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "# Didactyl Agent\n\nYou are {{my_kind0_profile}}\n\nYour npub: {{my_npub}}\n\n## Rules\n\n- Communicate through encrypted Nostr direct messages\n- Keep responses concise and clear\n- Be helpful and technically accurate\n- If unsure, state uncertainty directly\n- Use tools when a request requires taking action\n- After a tool call, base your answer on the actual tool result\n- Never claim a tool was run if no tool was executed\n- Maintain your task list as short-term working memory\n- Never reveal your private key (nsec)\n- You may share your public key (npub) with anyone",
|
||||
"tags": [
|
||||
["d", "identity_and_rules"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "Agent identity and behavioral rules"],
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "## Recent Conversation\n\n{{nostr_dm_history({\"format\":\"text\",\"limit\":12})}}",
|
||||
"tags": [
|
||||
["d", "dm_history"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "DM conversation history for context continuity"],
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"]
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -299,11 +299,29 @@ git_commit_and_push_no_tag() {
|
||||
|
||||
# Push changes
|
||||
print_status "Pushing to remote repository..."
|
||||
if git push > /dev/null 2>&1; then
|
||||
print_success "Pushed changes"
|
||||
local current_branch
|
||||
current_branch=$(git branch --show-current 2>/dev/null || echo "")
|
||||
|
||||
if git rev-parse --abbrev-ref --symbolic-full-name "@{u}" > /dev/null 2>&1; then
|
||||
if git push > /dev/null 2>&1; then
|
||||
print_success "Pushed changes"
|
||||
else
|
||||
print_error "Failed to push changes"
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
print_error "Failed to push changes"
|
||||
exit 1
|
||||
if [[ -z "$current_branch" ]]; then
|
||||
print_error "Unable to determine current branch for push"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
print_warning "No upstream configured for branch '$current_branch'; setting upstream to origin/$current_branch"
|
||||
if git push -u origin "$current_branch" > /dev/null 2>&1; then
|
||||
print_success "Pushed changes and configured upstream"
|
||||
else
|
||||
print_error "Failed to push changes while configuring upstream"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Push only the new tag to avoid conflicts with existing tags
|
||||
|
||||
246
plans/dm_history_context_cleanup.md
Normal file
246
plans/dm_history_context_cleanup.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# DM History Context Cleanup, Skill Rename & Startup Events Unification
|
||||
|
||||
## Problems
|
||||
|
||||
### 1. DM History as JSON in System Prompt
|
||||
The `{{nostr_dm_history}}` template variable resolves to a raw JSON array string pasted into the system prompt. The LLM receives conversation history as JSON-within-text, wasting tokens and forcing it to parse structured data embedded in prose.
|
||||
|
||||
### 2. Misleading Skill Name
|
||||
The skill `default_admin_dm` is really an identity and rules skill. Rename to `identity_and_rules`.
|
||||
|
||||
### 3. `default_skill` Config Section Is Redundant
|
||||
The `default_skill` section in genesis.jsonc is a special-case config path that converts a skill into a startup event and auto-adopts it. This is unnecessary — skills should just be startup events like everything else. The program should treat all startup events equally and halt if any fail to publish.
|
||||
|
||||
## Solution
|
||||
|
||||
Three coordinated changes:
|
||||
|
||||
### Part A: DM History Text Format
|
||||
Add a `format` parameter to the `nostr_dm_history` tool. Create a separate `dm_history` skill.
|
||||
|
||||
### Part B: Skill Rename
|
||||
Rename `default_admin_dm` → `identity_and_rules` everywhere.
|
||||
|
||||
### Part C: Eliminate `default_skill` Config Section
|
||||
Move skills into `startup_events`. Auto-adopt kind 31123/31124 startup events. Make startup event publishing mandatory (halt on failure).
|
||||
|
||||
---
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Part A: DM History Text Format
|
||||
|
||||
#### A1. Add `format` parameter to `execute_nostr_dm_history()`
|
||||
|
||||
**File:** `src/tools/tool_agent.c` — line 265
|
||||
|
||||
Add a `format` parameter: `"json"` (default, current behavior) or `"text"`.
|
||||
|
||||
When `format` is `"text"`, after the filtering loop (lines 320-360), iterate the filtered array and build plain text:
|
||||
|
||||
```
|
||||
User: Good morning
|
||||
Assistant: Good morning! ☀️ How can I help you today?
|
||||
User: What is the capital of England?
|
||||
Assistant: London! 🇬🇧
|
||||
```
|
||||
|
||||
Existing `include_current=false` default already deduplicates the current live message (line 339).
|
||||
|
||||
#### A2. Add `format` to the tool schema
|
||||
|
||||
**File:** `src/tools/tools_schema.c` — around line 1493
|
||||
|
||||
Add `format` property with description. Update tool description to mention the parameter.
|
||||
|
||||
---
|
||||
|
||||
### Part B: Skill Rename
|
||||
|
||||
#### B1. Update `src/default_events.h`
|
||||
|
||||
- `DIDACTYL_DEFAULT_SKILL_D_TAG`: `"default_admin_dm"` → `"identity_and_rules"`
|
||||
- `DIDACTYL_DEFAULT_SKILL_TAGS_JSON`: update d-tag and description
|
||||
- `DIDACTYL_DEFAULT_SKILL_TEMPLATE`: keep as-is (already clean, no `{{nostr_dm_history}}`)
|
||||
|
||||
#### B2. Update tool description examples in `src/tools/tools_schema.c`
|
||||
|
||||
- Line 854: `skill_get` example
|
||||
- Line 883: `skill_view` example
|
||||
- Line 911: `skill_set` example
|
||||
|
||||
#### B3. Update `docs/GENESIS.md`
|
||||
|
||||
- Line 33 and 124: `default_admin_dm` → `identity_and_rules`
|
||||
|
||||
---
|
||||
|
||||
### Part C: Eliminate `default_skill` Config Section
|
||||
|
||||
#### C1. Auto-adopt kind 31123/31124 startup events
|
||||
|
||||
**File:** `src/config.c`
|
||||
|
||||
Replace `config_ensure_default_skill_startup_events()` with a new function `config_ensure_startup_skill_adoption()` that:
|
||||
|
||||
1. Scans all startup events for kind 31123 and 31124
|
||||
2. For each skill found, extracts its `d_tag` from tags
|
||||
3. Builds the skill address (`kind:pubkey:d_tag`)
|
||||
4. Ensures a kind 10123 adoption list startup event exists with all skill addresses
|
||||
5. If no 10123 event exists, creates one
|
||||
|
||||
This replaces the single-skill logic with a generic "adopt all startup skills" approach.
|
||||
|
||||
#### C2. Remove `default_skill` config parsing
|
||||
|
||||
**File:** `src/config.c`
|
||||
|
||||
- Remove `parse_default_skill_config()` function (lines 733-816)
|
||||
- Remove the call at line 1369
|
||||
- Keep backward compatibility: if `default_skill` section exists in genesis.jsonc, convert it to a startup event during parsing (migration path) — OR just remove support and let users update their genesis.jsonc
|
||||
|
||||
#### C3. Remove `default_skill_config_t` from config struct
|
||||
|
||||
**File:** `src/config.h`
|
||||
|
||||
- Remove `default_skill_config_t` typedef (lines 67-72)
|
||||
- Remove `default_skill` field from `didactyl_config_t` (line 134)
|
||||
|
||||
#### C4. Update `src/main.c`
|
||||
|
||||
- Line 1060: Replace `config_ensure_default_skill_startup_events()` call with `config_ensure_startup_skill_adoption()`
|
||||
|
||||
#### C5. Make startup event publishing mandatory
|
||||
|
||||
**File:** `src/nostr_handler.c`
|
||||
|
||||
In the startup publish flow (around line 3150), after all relays have been tried:
|
||||
- Check that each startup event was published to at least one relay
|
||||
- If any event failed on all relays, log an error and return failure
|
||||
- The caller in `main.c` should halt on this failure
|
||||
|
||||
#### C6. Update setup wizard
|
||||
|
||||
**File:** `src/setup_wizard.c`
|
||||
|
||||
- `configure_default_skill_for_agent()` (line 498): Instead of populating `cfg->default_skill`, append the identity skill as a startup event directly
|
||||
- Add the `dm_history` skill as a second startup event
|
||||
- The auto-adoption logic (C1) handles the adoption list
|
||||
|
||||
#### C7. Update `default_events.h`
|
||||
|
||||
Add the `dm_history` skill template:
|
||||
|
||||
```c
|
||||
#define DIDACTYL_DEFAULT_DM_HISTORY_SKILL_D_TAG "dm_history"
|
||||
|
||||
static const char* DIDACTYL_DEFAULT_DM_HISTORY_SKILL_TEMPLATE =
|
||||
"## Recent Conversation\n\n"
|
||||
"{{nostr_dm_history({\"format\":\"text\",\"limit\":12})}}";
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Part D: Genesis Config Updates
|
||||
|
||||
#### D1. Update `genesis.jsonc.example`
|
||||
|
||||
Remove `default_skill` section. Add skills as startup events:
|
||||
|
||||
```jsonc
|
||||
"startup_events": [
|
||||
{
|
||||
"kind": 0,
|
||||
"content_fields": {
|
||||
"name": "Didactyl",
|
||||
"about": "I am a Didactyl agent living on Nostr"
|
||||
},
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"kind": 3,
|
||||
"content": "",
|
||||
"tags": [["p", "ADMIN_HEX_PUBKEY"]]
|
||||
},
|
||||
{
|
||||
"kind": 10002,
|
||||
"content": "",
|
||||
"tags": [
|
||||
["r", "wss://relay.damus.io"],
|
||||
["r", "wss://relay.primal.net"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "# Didactyl Agent\n\nYou are {{my_kind0_profile}}\n\nYour npub: {{my_npub}}\n\n## Rules\n\n- Communicate through encrypted Nostr direct messages\n- Keep responses concise and clear\n- Be helpful and technically accurate\n- If unsure, state uncertainty directly\n- Use tools when a request requires taking action\n- After a tool call, base your answer on the actual tool result\n- Never claim a tool was run if no tool was executed\n- Maintain your task list as short-term working memory\n- Never reveal your private key (nsec)\n- You may share your public key (npub) with anyone",
|
||||
"tags": [
|
||||
["d", "identity_and_rules"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "Agent identity and behavioral rules"],
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": 31124,
|
||||
"content": "## Recent Conversation\n\n{{nostr_dm_history({\"format\":\"text\",\"limit\":12})}}",
|
||||
"tags": [
|
||||
["d", "dm_history"],
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "DM conversation history for context continuity"],
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"]
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### D2. Update live `genesis.jsonc`
|
||||
|
||||
Same changes as D1 but for the actual deployment config.
|
||||
|
||||
---
|
||||
|
||||
## Result
|
||||
|
||||
### Before
|
||||
|
||||
```json
|
||||
[
|
||||
{"role": "system", "content": "You are {...}\n\nYour npub: npub1...\n\n## Rules\n...\n[{\"role\":\"user\",\"content\":\"Good morning\",...}]"},
|
||||
{"role": "user", "content": "And Fiji?"}
|
||||
]
|
||||
```
|
||||
|
||||
### After
|
||||
|
||||
```json
|
||||
[
|
||||
{"role": "system", "content": "# Didactyl Agent\n\nYou are {...}\n\nYour npub: npub1...\n\n## Rules\n...\n\n---\n\n## Recent Conversation\n\nUser: Good morning\nAssistant: Good morning! ☀️ How can I help you today?\nUser: What is the capital of England?\nAssistant: London! 🇬🇧\nUser: How about France?\nAssistant: Paris! 🇫🇷"},
|
||||
{"role": "user", "content": "And Fiji?"}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `src/tools/tool_agent.c` | Add `format` parameter to `execute_nostr_dm_history()` |
|
||||
| `src/tools/tools_schema.c` | Add `format` to schema; update example d-tags |
|
||||
| `src/default_events.h` | Rename d-tag; add `dm_history` skill template |
|
||||
| `src/config.h` | Remove `default_skill_config_t` and field |
|
||||
| `src/config.c` | Remove `parse_default_skill_config()`; replace `config_ensure_default_skill_startup_events()` with `config_ensure_startup_skill_adoption()` |
|
||||
| `src/main.c` | Update call to new adoption function |
|
||||
| `src/nostr_handler.c` | Make startup event publishing mandatory (halt on total failure) |
|
||||
| `src/setup_wizard.c` | Put skills in startup_events; add dm_history |
|
||||
| `genesis.jsonc.example` | Remove `default_skill`; add skills as startup events |
|
||||
| `genesis.jsonc` | Same as example |
|
||||
| `docs/GENESIS.md` | Update references |
|
||||
|
||||
## Migration Note
|
||||
|
||||
For backward compatibility, consider keeping `parse_default_skill_config()` as a migration shim that converts `default_skill` into a startup event with a deprecation warning. This way existing genesis.jsonc files with `default_skill` still work but users are prompted to update.
|
||||
224
plans/strict_startup_validation.md
Normal file
224
plans/strict_startup_validation.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# Strict Startup Validation — Eliminate Fake Event Seeding
|
||||
|
||||
## Problem
|
||||
|
||||
The agent currently seeds a **synthetic event** into the self-skill cache during startup
|
||||
(`seed_default_skill_into_cache()` in `src/nostr_handler.c:1299`). This fake event has:
|
||||
|
||||
- `id` = all zeros
|
||||
- `created_at` = `time(NULL)` (current startup time)
|
||||
|
||||
Because the fake event is newer than the real relay event, the upsert rejects the real
|
||||
event. This causes `skill_get` to return an all-zeros ID and prevents the cache from
|
||||
ever holding the authentic relay event.
|
||||
|
||||
Additionally, the adopted skills cache in `src/agent.c` has a startup fallback path
|
||||
that uses `g_cfg->startup_events` when the adoption list is empty. This masks real
|
||||
failures and creates inconsistency between what the agent thinks it has and what
|
||||
actually exists on relays.
|
||||
|
||||
## Principle
|
||||
|
||||
> If the agent cannot retrieve the events it needs to run, startup should fail with
|
||||
> a clear diagnostic. No fake events. No fallbacks. If it is not there, fail.
|
||||
|
||||
## Two Startup Modes
|
||||
|
||||
### Genesis Startup (first run)
|
||||
|
||||
1. Connect to relays
|
||||
2. Publish startup events (profile, contacts, relay list, default skill, adoption list)
|
||||
3. **Wait for publish confirmation** from at least one relay per event
|
||||
4. Log at INFO level: which events were published to which relays
|
||||
5. Subscribe to self-skill cache
|
||||
6. Wait for EOSE — validate published events are now in cache
|
||||
7. If validation fails: abort with diagnostic
|
||||
|
||||
### Subsequent Startup (existing agent)
|
||||
|
||||
1. Connect to relays
|
||||
2. Subscribe to self-skill cache
|
||||
3. Wait for EOSE
|
||||
4. Log at INFO level: which events were received from which relays
|
||||
5. Validate required events exist in cache
|
||||
6. If validation fails: abort with diagnostic
|
||||
|
||||
## Current Startup Flow (steps 14–18)
|
||||
|
||||
```
|
||||
Step 14: Subscribe self-skill cache (sends REQ for kinds 31123/31124/10123)
|
||||
→ Does NOT wait for EOSE
|
||||
→ Calls seed_default_skill_into_cache() with fake event
|
||||
Step 15: Subscribe DMs (agent starts accepting messages)
|
||||
→ Startup DM sent BEFORE this step
|
||||
Step 16: Subscribe wallet events
|
||||
Step 17: Initialize cashu wallet
|
||||
Step 18: READY — enter main poll loop
|
||||
```
|
||||
|
||||
## Proposed New Flow
|
||||
|
||||
```
|
||||
Step 14: Subscribe self-skill cache (sends REQ for kinds 31123/31124/10123)
|
||||
Step 14a: Wait for self-skill EOSE (15s timeout)
|
||||
Step 14b: Validate required events exist in cache
|
||||
→ Log received events at INFO level
|
||||
→ If no skill events: FAIL startup with diagnostic
|
||||
Step 15: Subscribe DMs
|
||||
Step 16: Subscribe wallet events
|
||||
Step 17: Initialize cashu wallet
|
||||
Step 18: READY — send startup DM AFTER all validation, enter main loop
|
||||
```
|
||||
|
||||
## Changes
|
||||
|
||||
### 1. Remove `seed_default_skill_into_cache()` entirely
|
||||
|
||||
**File:** `src/nostr_handler.c`
|
||||
|
||||
- Delete the entire function (lines 1299–1341)
|
||||
- Remove its call at line 3165 in `nostr_handler_reconcile_startup_events()`
|
||||
- Remove its forward declaration at line 451
|
||||
|
||||
### 2. Remove startup fallback in `refresh_adopted_skills_cache_if_needed()`
|
||||
|
||||
**File:** `src/agent.c`
|
||||
|
||||
Delete the entire fallback block (lines ~1571–1619) that uses
|
||||
`g_cfg->startup_events` when the adoption list is empty. If the adoption
|
||||
list is empty, the cache stays empty — no synthetic population.
|
||||
|
||||
### 3. Add synchronous EOSE wait for self-skill subscription
|
||||
|
||||
**File:** `src/nostr_handler.c`
|
||||
|
||||
Add a new exported function:
|
||||
|
||||
```c
|
||||
int nostr_handler_wait_for_self_skill_eose(int timeout_ms);
|
||||
```
|
||||
|
||||
Implementation:
|
||||
- Use a static `volatile int g_self_skill_eose_received = 0` flag
|
||||
- Set it to 1 in `on_self_skill_eose()`
|
||||
- The wait function polls `nostr_relay_pool_poll()` in a loop until the
|
||||
flag is set or the timeout expires
|
||||
- Returns 0 on success, -1 on timeout
|
||||
|
||||
### 4. Add post-EOSE validation with logging
|
||||
|
||||
**File:** `src/nostr_handler.c`
|
||||
|
||||
Add a new exported function:
|
||||
|
||||
```c
|
||||
int nostr_handler_validate_self_skill_cache(int* out_skill_count, int* out_adoption_count);
|
||||
```
|
||||
|
||||
This function:
|
||||
- Counts skill events (kind 31123 + 31124) in cache
|
||||
- Counts adoption events (kind 10123) in cache
|
||||
- Logs at INFO level each cached event: kind, d_tag, id, created_at
|
||||
- Returns 0 if at least one skill event exists
|
||||
- Returns -1 if no skill events found
|
||||
|
||||
### 5. Update startup sequence in `main.c`
|
||||
|
||||
**File:** `src/main.c`
|
||||
|
||||
After step 14 subscribe, add EOSE wait and validation:
|
||||
|
||||
```c
|
||||
// Wait for self-skill EOSE
|
||||
int eose_timeout_ms = 15000;
|
||||
if (nostr_handler_wait_for_self_skill_eose(eose_timeout_ms) != 0) {
|
||||
startup_step_fail(14, "Subscribe self-skill cache",
|
||||
"self-skill events not received within timeout; "
|
||||
"check relay connectivity and that skill events exist");
|
||||
// cleanup and return 1
|
||||
}
|
||||
|
||||
// Validate
|
||||
int skill_count = 0, adoption_count = 0;
|
||||
if (nostr_handler_validate_self_skill_cache(&skill_count, &adoption_count) != 0) {
|
||||
startup_step_fail(14, "Subscribe self-skill cache",
|
||||
"no skill events found after EOSE; "
|
||||
"run genesis to publish default skill events");
|
||||
// cleanup and return 1
|
||||
}
|
||||
|
||||
char detail[128];
|
||||
snprintf(detail, sizeof(detail),
|
||||
"skills=%d adoptions=%d", skill_count, adoption_count);
|
||||
startup_step_ok(14, "Subscribe self-skill cache", detail);
|
||||
```
|
||||
|
||||
### 6. Move startup DM to after all validation
|
||||
|
||||
**File:** `src/main.c`
|
||||
|
||||
Move the startup DM send from its current position (between steps 14 and 15)
|
||||
to just before step 18 READY. The agent should only announce itself as online
|
||||
after all required events have been validated and all subscriptions are active.
|
||||
|
||||
### 7. Genesis publish confirmation logging
|
||||
|
||||
**File:** `src/nostr_handler.c` / `src/main.c`
|
||||
|
||||
For genesis startup, the existing publish path already logs at INFO level:
|
||||
```
|
||||
kind 31124 event published to wss://relay.damus.io (async)
|
||||
```
|
||||
|
||||
Enhance this to also log a summary after all startup events are published:
|
||||
```
|
||||
[INFO] startup publish summary: 5 events published to 3/4 relays
|
||||
[INFO] kind=0 (profile) → relay.damus.io, relay.primal.net, nos.lol
|
||||
[INFO] kind=31124 (default_admin_dm) → relay.damus.io, relay.primal.net, nos.lol
|
||||
[INFO] kind=10123 (adoption list) → relay.damus.io, relay.primal.net, nos.lol
|
||||
```
|
||||
|
||||
### 8. Declare new functions in header
|
||||
|
||||
**File:** `src/nostr_handler.h`
|
||||
|
||||
```c
|
||||
int nostr_handler_wait_for_self_skill_eose(int timeout_ms);
|
||||
int nostr_handler_validate_self_skill_cache(int* out_skill_count, int* out_adoption_count);
|
||||
```
|
||||
|
||||
## Startup Step Summary
|
||||
|
||||
| Step | Description | Behavior |
|
||||
|------|-------------|----------|
|
||||
| 1–13 | Existing steps (config, relays, agent init, triggers, kind10002, context subs) | Unchanged |
|
||||
| 14 | Subscribe self-skill cache + wait EOSE + validate | **BLOCKING** — fails if no skill events |
|
||||
| 15 | Subscribe DMs | Fails startup if subscription fails |
|
||||
| 16 | Subscribe wallet events | Continues on failure |
|
||||
| 17 | Initialize cashu wallet | Continues on failure |
|
||||
| 18 | READY | Send startup DM, enter main loop |
|
||||
|
||||
## Error Messages
|
||||
|
||||
### EOSE timeout
|
||||
```
|
||||
[ERROR] Startup aborted: self-skill EOSE not received within 15000ms.
|
||||
[ERROR] Check relay connectivity (connected=2/4) and ensure skill events exist on relays.
|
||||
[ERROR] If this is a first run, use genesis to publish startup events.
|
||||
```
|
||||
|
||||
### No skill events after EOSE
|
||||
```
|
||||
[ERROR] Startup aborted: no skill events (kind 31123/31124) found in self-skill cache.
|
||||
[ERROR] The agent requires at least one skill event to operate.
|
||||
[ERROR] Run genesis to publish the default skill, or publish a skill manually.
|
||||
```
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `src/nostr_handler.c` | Remove `seed_default_skill_into_cache()`, add EOSE wait + validation functions, enhance publish logging |
|
||||
| `src/nostr_handler.h` | Declare `nostr_handler_wait_for_self_skill_eose()` and `nostr_handler_validate_self_skill_cache()` |
|
||||
| `src/main.c` | Add EOSE wait + validation after step 14, move startup DM to before step 18 |
|
||||
| `src/agent.c` | Remove startup fallback block in `refresh_adopted_skills_cache_if_needed()` |
|
||||
206
plans/trigger_scoped_skill_architecture.md
Normal file
206
plans/trigger_scoped_skill_architecture.md
Normal file
@@ -0,0 +1,206 @@
|
||||
# Implementation Plan: Trigger-Scoped Skill Architecture
|
||||
|
||||
Target spec: [docs/SKILLS.md](../docs/SKILLS.md) · [docs/CONTEXT.md](../docs/CONTEXT.md) · [docs/TOOLS.md](../docs/TOOLS.md)
|
||||
|
||||
## Current State
|
||||
|
||||
- `g_system_context` is a monolithic global string (from the default skill) prepended to every LLM call
|
||||
- `agent_on_trigger()` prepends `g_system_context` to every triggered skill execution
|
||||
- `agent_on_message()` falls through to `g_system_context` chat if no DM trigger fires
|
||||
- `trigger_manager_fire_dm()` fires all matching DM triggers independently (separate LLM calls each)
|
||||
- `trigger_manager_load_from_skills()` loads triggers from adopted skills only
|
||||
- Template variables resolve to tools only — no skill-to-skill `{{d_tag}}` resolution
|
||||
- `apply_trigger_runtime_to_llm_config()` parses `provider/model` but discards the provider
|
||||
- Skill `content` is JSON with `description` and `template` fields (spec says content IS the template)
|
||||
- `["tools", "true/false/csv"]` tag controls tool access (spec says use `requires_tool` instead)
|
||||
- `["enabled", "true/false"]` tag on triggers (spec says adoption IS enablement)
|
||||
|
||||
## Phase 0: Provider Override Fix
|
||||
|
||||
**File:** `src/trigger_manager.c`
|
||||
**Function:** `apply_trigger_runtime_to_llm_config()` (line 592)
|
||||
|
||||
Currently at line 602-611, when a slash is found in the llm_spec, only the model (after slash) is extracted. The provider (before slash) is discarded.
|
||||
|
||||
**Change:** When slash is found, also copy the provider prefix into `cfg->provider`.
|
||||
|
||||
```c
|
||||
// Current: only extracts model
|
||||
if (slash) {
|
||||
const char* model = slash + 1;
|
||||
// ... sets cfg->model only
|
||||
}
|
||||
|
||||
// New: extract both provider and model
|
||||
if (slash) {
|
||||
size_t provider_len = (size_t)(slash - spec);
|
||||
if (provider_len > 0 && provider_len < sizeof(cfg->provider)) {
|
||||
snprintf(cfg->provider, sizeof(cfg->provider), "%.*s", (int)provider_len, spec);
|
||||
}
|
||||
const char* model = slash + 1;
|
||||
// ... sets cfg->model as before
|
||||
}
|
||||
```
|
||||
|
||||
## Phase 1: Two-Layer Context Assembly
|
||||
|
||||
### 1a. Skill-to-skill template resolution
|
||||
|
||||
**File:** `src/prompt_template.c`
|
||||
**Function:** `map_variable_tool_name()` (line 100)
|
||||
|
||||
Currently returns a tool name for known variables, or NULL for unknown ones (which resolve to empty).
|
||||
|
||||
**Change:** Add a fallback path. If the variable name doesn't match a known tool, look it up as a skill d-tag in the adoption list cache. If found, return the skill's content.
|
||||
|
||||
This requires access to the skill cache from the template resolver. Options:
|
||||
- Pass a skill lookup callback into the template builder
|
||||
- Add a `skill_content_lookup` function pointer to `tools_context_t`
|
||||
|
||||
**File:** `src/prompt_template.c`
|
||||
**Function:** `prompt_template_build_messages()` (line 37)
|
||||
|
||||
When resolving a `{{variable}}` that doesn't match a tool, call the skill lookup function to check adopted skills by d-tag.
|
||||
|
||||
### 1b. Trigger-matched context assembly
|
||||
|
||||
**File:** `src/agent.c`
|
||||
**New function:** `build_context_from_triggers()`
|
||||
|
||||
```c
|
||||
char* build_context_from_triggers(
|
||||
trigger_type_t trigger_type,
|
||||
const char* trigger_filter,
|
||||
cJSON* trigger_event,
|
||||
const char* relay_url);
|
||||
```
|
||||
|
||||
Implementation:
|
||||
1. Load the adoption list (kind `10123`) — already cached at startup
|
||||
2. For each adopted skill, check if it has a trigger matching `trigger_type` and `trigger_filter`
|
||||
3. If match: resolve the skill's template (expanding `{{...}}` references via Phase 1a)
|
||||
4. Concatenate all matched skill templates in adoption-list order
|
||||
5. Append the triggering event payload
|
||||
6. For DM triggers: always append raw message content at the end
|
||||
7. Return the assembled system prompt
|
||||
|
||||
### 1c. Replace g_system_context in trigger execution
|
||||
|
||||
**File:** `src/agent.c`
|
||||
**Function:** `agent_on_trigger()` (line 1817)
|
||||
|
||||
**Current (line 1852-1858):**
|
||||
```c
|
||||
snprintf(system_prompt, system_len, "%s\n\n%s%s\nRelay: %s\n\nSkill instructions:\n%s",
|
||||
g_system_context,
|
||||
trigger_prefix, skill_d_tag, relay, skill_content);
|
||||
```
|
||||
|
||||
**Replace with:** Call `build_context_from_triggers()` instead of prepending `g_system_context`.
|
||||
|
||||
### 1d. Skill content format change
|
||||
|
||||
**File:** `src/nostr_handler.c` and `src/config.c`
|
||||
|
||||
Currently skill content is parsed as JSON to extract `template` field. The spec says `content` IS the template (plain string).
|
||||
|
||||
**Change:** When loading a skill's content, check if it's a JSON object with a `template` field (backward compat) or a plain string (new format). Use the template/string directly.
|
||||
|
||||
## Phase 2: DM Composition with Default Handler
|
||||
|
||||
**File:** `src/agent.c`
|
||||
**Function:** `agent_on_message()` (line 2085)
|
||||
|
||||
Currently at line 2120-2128, calls `trigger_manager_fire_dm()` which fires each matching DM trigger independently. If none fire, falls through to `g_system_context` chat.
|
||||
|
||||
**Change:**
|
||||
1. Use `build_context_from_triggers()` with `TRIGGER_TYPE_DM` and the sender tier
|
||||
2. This automatically finds all DM-triggered skills in adoption-list order and composes them
|
||||
3. Always append the raw admin message at the end (default DM handler)
|
||||
4. If no DM-triggered skill exists, use a minimal built-in default: "You are an AI agent. Respond to the message."
|
||||
5. Make one LLM call with the composed context
|
||||
|
||||
**File:** `src/trigger_manager.c`
|
||||
**Function:** `trigger_manager_fire_dm()` (line 1545)
|
||||
|
||||
Currently fires all matching DM triggers independently (each gets its own LLM call).
|
||||
|
||||
**Change:** Instead of firing independently, return the list of matching DM skill d-tags (in adoption-list order). Let the caller (`agent_on_message`) compose them into a single context via `build_context_from_triggers()`.
|
||||
|
||||
New function signature:
|
||||
```c
|
||||
int trigger_manager_get_dm_skills(trigger_manager_t* mgr,
|
||||
const char* sender_pubkey_hex,
|
||||
didactyl_sender_tier_t tier,
|
||||
char** out_d_tags,
|
||||
int max_d_tags);
|
||||
```
|
||||
|
||||
## Phase 3: Trigger Discovery Independent of Adoption
|
||||
|
||||
**File:** `src/trigger_manager.c`
|
||||
**Function:** `trigger_manager_load_from_skills()` (line ~varies)
|
||||
|
||||
Currently loads triggers only from adopted skills in the `10123` list.
|
||||
|
||||
**Change:** Scan all skill events published by the agent (query own pubkey for kinds 31123/31124), not just adopted ones. Arm any skill with trigger tags. The adoption list controls `{{...}}` resolution and ordering, not trigger arming.
|
||||
|
||||
Non-adopted skills with triggers fire in isolation (no layer 2 skill references available).
|
||||
|
||||
## Phase 4: Context Compaction
|
||||
|
||||
**File:** `src/agent.c`
|
||||
**Functions:** Tool loops in `agent_on_trigger()` (line 1905) and `agent_on_message()` (line 2212)
|
||||
|
||||
**New function:**
|
||||
```c
|
||||
static int estimate_context_tokens(cJSON* messages);
|
||||
```
|
||||
|
||||
Approximate: sum character lengths of all message content fields, divide by 4.
|
||||
|
||||
**Change in tool loops:** Before each LLM call, check if `estimate_context_tokens(messages)` exceeds 70% of the model's context window. If so:
|
||||
|
||||
1. Build a summarization request: "Summarize your progress so far, including key findings and remaining work."
|
||||
2. Send to LLM with `tool_choice: "none"` (text only)
|
||||
3. Replace all tool call/result messages with a single system message containing the summary
|
||||
4. Continue the tool loop with the compacted context
|
||||
|
||||
## Phase 5: LLM Fallback Chain
|
||||
|
||||
**File:** `src/trigger_manager.c`
|
||||
**Function:** `apply_trigger_runtime_to_llm_config()` (line 592)
|
||||
|
||||
Currently parses the comma in `llm_spec` but only uses the first entry.
|
||||
|
||||
**Change:** Walk the comma-separated entries. For each:
|
||||
1. Parse `provider/model` or bare `model` or capability keyword
|
||||
2. Check if the model is available (query provider, or check a local model list)
|
||||
3. If available, use it and stop
|
||||
4. If not, try the next entry
|
||||
5. Capability keywords (`cheap`, `fast`, `best`, `default`) resolve to runtime-configured models
|
||||
|
||||
## Phase 6: Remove Obsolete Code
|
||||
|
||||
**File:** `src/agent.c`
|
||||
- Remove `g_system_context` global variable
|
||||
- Remove `g_system_context` from `agent_init()` parameter
|
||||
- Remove `g_system_context` prepend from all code paths
|
||||
|
||||
**File:** `src/nostr_handler.c`
|
||||
- Remove `g_system_context` global variable (line 28)
|
||||
- Remove `g_system_context` initialization in `nostr_handler_reconcile_startup_events()` (line 3124-3157)
|
||||
- Remove `nostr_handler_get_system_context()` function
|
||||
|
||||
**File:** `src/agent.h`
|
||||
- Update `agent_init()` signature to remove `system_context` parameter
|
||||
|
||||
## Migration Path
|
||||
|
||||
1. **Phase 0** — safe, independent fix. No behavioral change.
|
||||
2. **Phase 1** — core change. Backward compatible if existing default skill has a DM trigger tag. The `g_system_context` is still used as fallback until Phase 6.
|
||||
3. **Phase 2** — changes DM behavior. Existing agents work if default skill has `["trigger", "dm"]`.
|
||||
4. **Phase 3** — additive. Skills without triggers are unaffected.
|
||||
5. **Phase 4** — additive. New capability, no existing behavior changes.
|
||||
6. **Phase 5** — additive. Currently only first entry is used; this adds fallback.
|
||||
7. **Phase 6** — cleanup. Only after Phases 1-2 are stable.
|
||||
246
plans/v0.2.0_migration.md
Normal file
246
plans/v0.2.0_migration.md
Normal file
@@ -0,0 +1,246 @@
|
||||
# v0.2.0 Migration Plan
|
||||
|
||||
## Agent Event Cleanup
|
||||
|
||||
Delete all old skill/soul events from each agent's relay set before restarting with the new genesis file.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Genesis File Changes
|
||||
|
||||
### Kind 0 profile event (new)
|
||||
|
||||
Add a startup event for the agent's profile:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"kind": 0,
|
||||
"content_fields": {
|
||||
"name": "Didactyl",
|
||||
"about": "I am a Didactyl agent living on Nostr"
|
||||
},
|
||||
"tags": []
|
||||
}
|
||||
```
|
||||
|
||||
### Kind 3 contacts event (new)
|
||||
|
||||
Add a startup event following the admin:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"kind": 3,
|
||||
"content": "",
|
||||
"tags": [
|
||||
["p", "ADMIN_HEX_PUBKEY"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The admin hex pubkey is derived from the `admin.pubkey` field at startup.
|
||||
|
||||
### Default skill rename and trigger tags
|
||||
|
||||
**Before:**
|
||||
```jsonc
|
||||
"default_skill": {
|
||||
"d_tag": "didactyl-default",
|
||||
"kind": 31124,
|
||||
"content": "# Didactyl Agent\n\n...\n\n---template---\n\n- section: admin_identity\n ...",
|
||||
"tags": [["app", "didactyl"], ["scope", "private"]]
|
||||
}
|
||||
```
|
||||
|
||||
**After:**
|
||||
```jsonc
|
||||
"default_skill": {
|
||||
"d_tag": "default_admin_dm",
|
||||
"kind": 31124,
|
||||
"content": "# Didactyl Agent\n\nYou are {{my_kind0_profile}}\n\nYour npub: {{my_npub}}\n\n## Rules\n\n- Communicate through encrypted Nostr direct messages\n- Keep responses concise and clear\n- Be helpful and technically accurate\n- If unsure, state uncertainty directly\n- Use tools when a request requires taking action\n- After a tool call, base your answer on the actual tool result\n- Never claim a tool was run if no tool was executed\n- Maintain your task list as short-term working memory\n- Never reveal your private key (nsec)\n- You may share your public key (npub) with anyone",
|
||||
"tags": [
|
||||
["app", "didactyl"],
|
||||
["scope", "private"],
|
||||
["description", "Default admin DM handler"],
|
||||
["trigger", "dm"],
|
||||
["filter", "{\"from\":\"admin\"}"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Key changes:
|
||||
- `d_tag` renamed to `default_admin_dm`
|
||||
- `---template---` DSL removed entirely
|
||||
- Content uses `{{my_kind0_profile}}` and `{{my_npub}}` for identity injection
|
||||
- Trigger/filter tags added so the new trigger-scoped system fires it on admin DMs
|
||||
- Description tag added
|
||||
|
||||
---
|
||||
|
||||
## Source Code Changes
|
||||
|
||||
### Phase 1: Remove `---template---` DSL
|
||||
|
||||
#### `src/prompt_template.h`
|
||||
|
||||
- Remove `PROMPT_TEMPLATE_MARKER`, `PROMPT_TEMPLATE_MAX_SECTIONS`, `PROMPT_TEMPLATE_MAX_NAME_LEN`, `PROMPT_TEMPLATE_MAX_ROLE_LEN`
|
||||
- Remove `prompt_template_section_t` struct
|
||||
- Remove `prompt_template_t` struct
|
||||
- Remove `prompt_template_emit_hook_fn` typedef
|
||||
- Remove `prompt_template_parse()` declaration
|
||||
- Remove `prompt_template_build_messages()` declaration
|
||||
- Remove `prompt_template_free()` declaration
|
||||
- Keep the file if `resolve_inline_variables_local()` needs a public header, otherwise fold into agent.c
|
||||
|
||||
#### `src/prompt_template.c`
|
||||
|
||||
- Remove `prompt_template_parse()` and all section-parsing code (lines 231-502)
|
||||
- Remove `prompt_template_build_messages()` (lines 551-639)
|
||||
- Remove `prompt_template_free()` (lines 641-667)
|
||||
- Remove section-related helpers: `init_section_defaults()`, `parse_int_or_zero()`, `extract_tool_result_content()`, `append_message_object()`
|
||||
- Keep `resolve_inline_variables_local()` — it handles `{{...}}` variable resolution used by `build_context_from_triggers()`
|
||||
- Keep `map_variable_tool_name()` — maps variable names to tool names
|
||||
- Keep string helpers: `dup_range()`, `ltrim_inplace()`, `rtrim_inplace()`, `append_text()`
|
||||
|
||||
#### `src/agent.c`
|
||||
|
||||
- Remove `g_prompt_template` static variable (line 28)
|
||||
- Remove `g_has_prompt_template` static variable (line 29)
|
||||
- Remove `template_emit_hook()` callback
|
||||
- Remove the `prompt_template_parse()` call in `agent_init()` (line 2127-2128)
|
||||
- Remove the `prompt_template_free()` calls in `agent_init()` and `agent_cleanup()`
|
||||
- Remove the `g_has_prompt_template` branch in `agent_build_admin_messages_json()` (lines 2334-2035) — replace with trigger-composed context path
|
||||
|
||||
### Phase 2: Remove `g_system_context`
|
||||
|
||||
#### `src/agent.c`
|
||||
|
||||
- Remove `g_system_context` global (line 24)
|
||||
- Remove `system_context` parameter from `agent_init()`
|
||||
- Remove `strdup(system_context)` and all `g_system_context` references
|
||||
- Remove `g_system_context` null checks from `agent_on_trigger()`, `agent_on_message()`, `agent_build_admin_messages_json()`
|
||||
- In `agent_cleanup()`: remove `free(g_system_context)`
|
||||
|
||||
#### `src/agent.h`
|
||||
|
||||
- Update `agent_init()` signature: `int agent_init(didactyl_config_t* config);`
|
||||
|
||||
#### `src/nostr_handler.c`
|
||||
|
||||
- Remove `g_system_context` global (line 28)
|
||||
- Remove `g_system_context` initialization in `nostr_handler_reconcile_startup_events()` (lines 3124-3157)
|
||||
- Remove `nostr_handler_get_system_context()` function (lines 3289-3291)
|
||||
- Remove `seed_default_skill_into_cache()` if it only serves `g_system_context`
|
||||
|
||||
#### `src/nostr_handler.h`
|
||||
|
||||
- Remove `nostr_handler_get_system_context()` declaration
|
||||
|
||||
#### `src/main.c`
|
||||
|
||||
- Remove `system_context` variable (line 1261)
|
||||
- Remove fallback logic (lines 1262-1270)
|
||||
- Call `agent_init(&cfg)` without system_context parameter
|
||||
|
||||
### Phase 3: Rename default skill constants
|
||||
|
||||
#### `src/default_events.h`
|
||||
|
||||
- `DIDACTYL_DEFAULT_SKILL_D_TAG`: `"didactyl-default"` → `"default_admin_dm"`
|
||||
- `DIDACTYL_DEFAULT_SKILL_TAGS_JSON`: add trigger/filter/description tags
|
||||
- `DIDACTYL_DEFAULT_SKILL_TEMPLATE`: remove `---template---` section, replace with lean markdown using `{{my_kind0_profile}}` and `{{my_npub}}`
|
||||
|
||||
### Phase 4: Update `agent_build_admin_messages_json()`
|
||||
|
||||
This function is used by the HTTP API. Currently has two paths (template DSL and legacy hardcoded). Replace both with a single path using `build_context_from_triggers()` — same as `agent_on_message()` now uses.
|
||||
|
||||
### Phase 5: Delete legacy files
|
||||
|
||||
| File | Action |
|
||||
|------|--------|
|
||||
| `config.jsonc.example` | Delete |
|
||||
| `context_template.md` | Delete |
|
||||
| `context_template.recovered.md` | Delete |
|
||||
|
||||
### Phase 6: Update genesis files
|
||||
|
||||
#### `genesis.jsonc`
|
||||
|
||||
- Add kind 0 startup event with name and about
|
||||
- Rename `default_skill.d_tag` to `default_admin_dm`
|
||||
- Add trigger/filter/description tags to `default_skill.tags`
|
||||
- Replace content with lean markdown (no `---template---`)
|
||||
|
||||
#### `genesis.jsonc.example`
|
||||
|
||||
- Same changes as genesis.jsonc
|
||||
- Add kind 0 and kind 3 startup events
|
||||
|
||||
### Phase 7: Update documentation
|
||||
|
||||
#### `README.md`
|
||||
|
||||
- Remove kind 31120 from Didactyl Kinds table
|
||||
- Remove soul references
|
||||
- Update architecture description
|
||||
|
||||
#### `docs/GENESIS.md`
|
||||
|
||||
- Remove config.jsonc migration references
|
||||
- Update default_skill section to show `default_admin_dm`
|
||||
- Document kind 0 and kind 3 startup events
|
||||
|
||||
#### `docs/API.md`
|
||||
|
||||
- Remove `/api/events/soul` endpoint
|
||||
- Remove config.jsonc references
|
||||
|
||||
#### `docs/SKILLS.md`, `docs/CONTEXT.md`, `docs/TOOLS.md`
|
||||
|
||||
- Verify no soul/31120/config.jsonc references remain
|
||||
|
||||
---
|
||||
|
||||
## Variable Resolution for Default Skill
|
||||
|
||||
The default admin DM skill content uses:
|
||||
- `{{my_npub}}` — resolves via `map_variable_tool_name()` → `nostr_npub` tool → returns agent npub
|
||||
- `{{my_kind0_profile}}` — resolves via `map_variable_tool_name()` → `my_kind0_profile` tool → returns agent kind 0 profile context
|
||||
|
||||
These already work in `resolve_inline_variables_local()` because `map_variable_tool_name()` returns `NULL` for unknown names, and the skill lookup callback handles the rest. But `my_npub` and `my_kind0_profile` are not in the current `map_variable_tool_name()` mapping — they need to be added, OR the function needs to pass through unknown names as tool names (which it currently does NOT do after the Phase 1a change that made it return `NULL` for unknowns).
|
||||
|
||||
**Fix needed:** In `map_variable_tool_name()`, return the variable name itself as a tool name when it doesn't match a known alias. This way `{{my_npub}}` calls the `my_npub` tool directly.
|
||||
|
||||
Current (after Phase 1a change):
|
||||
```c
|
||||
return NULL; // unknown → try skill lookup
|
||||
```
|
||||
|
||||
Should be:
|
||||
```c
|
||||
return var_name; // unknown → try as tool name first, then skill lookup
|
||||
```
|
||||
|
||||
Wait — this was the ORIGINAL behavior before Phase 1a changed it. The Phase 1a change made `map_variable_tool_name()` return `NULL` for unknowns so the skill lookup callback would fire. But now we need BOTH: try as tool name first, then skill lookup.
|
||||
|
||||
**Resolution:** Restore `return var_name;` in `map_variable_tool_name()`. The skill lookup callback in `resolve_inline_variables_local()` already only fires when `replacement_owned` is NULL after the tool attempt. So the flow is:
|
||||
1. Check known aliases (admin_profile → nostr_admin_profile, etc.)
|
||||
2. Try the variable name as a direct tool name
|
||||
3. If tool returns nothing useful, try skill lookup callback
|
||||
4. If skill lookup returns nothing, resolve to empty string
|
||||
|
||||
This is exactly the resolution order specified in SKILLS.md.
|
||||
|
||||
---
|
||||
|
||||
## Execution Order
|
||||
|
||||
1. Phase 3 — rename constants (safe, no behavioral change)
|
||||
2. Phase 5 — delete legacy files
|
||||
3. Phase 6 — update genesis files
|
||||
4. Phase 1 — remove template DSL
|
||||
5. Phase 2 — remove g_system_context
|
||||
6. Phase 4 — update agent_build_admin_messages_json
|
||||
7. Phase 7 — update docs
|
||||
8. Build and test
|
||||
9. `increment_and_push.sh -p` for v0.2.1
|
||||
795
src/agent.c
795
src/agent.c
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@
|
||||
|
||||
struct trigger_manager;
|
||||
|
||||
int agent_init(didactyl_config_t* config, const char* system_context);
|
||||
int agent_init(didactyl_config_t* config);
|
||||
void agent_set_trigger_manager(struct trigger_manager* trigger_manager);
|
||||
void agent_on_trigger(const char* skill_d_tag,
|
||||
const char* skill_content,
|
||||
|
||||
137
src/config.c
137
src/config.c
@@ -692,6 +692,9 @@ static int set_tag_value_string(cJSON* tags, const char* tag_key, const char* ta
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int startup_event_has_d_tag(const startup_event_t* se, const char* d_tag);
|
||||
static int append_startup_event(didactyl_config_t* config, int kind, const char* content, const char* tags_json);
|
||||
|
||||
static int normalize_skill_d_tag(int event_kind, cJSON* item, cJSON* tags) {
|
||||
if (!item || !tags || !cJSON_IsArray(tags)) {
|
||||
return 0;
|
||||
@@ -730,7 +733,7 @@ static int normalize_skill_d_tag(int event_kind, cJSON* item, cJSON* tags) {
|
||||
return set_tag_value_string(tags, "d", d_tag);
|
||||
}
|
||||
|
||||
static int parse_default_skill_config(cJSON* root, didactyl_config_t* config) {
|
||||
static int parse_legacy_default_skill_to_startup_events(cJSON* root, didactyl_config_t* config) {
|
||||
if (!root || !config) {
|
||||
return -1;
|
||||
}
|
||||
@@ -746,19 +749,20 @@ static int parse_default_skill_config(cJSON* root, didactyl_config_t* config) {
|
||||
cJSON* content_fields = cJSON_GetObjectItemCaseSensitive(def, "content_fields");
|
||||
cJSON* tags = cJSON_GetObjectItemCaseSensitive(def, "tags");
|
||||
|
||||
if (!kind || !cJSON_IsNumber(kind)) {
|
||||
if (!kind || !cJSON_IsNumber(kind) || !d_tag || !cJSON_IsString(d_tag) || !d_tag->valuestring || d_tag->valuestring[0] == '\0') {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int kind_i = (int)kind->valuedouble;
|
||||
if (kind_i != 31123 && kind_i != 31124) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!d_tag || !cJSON_IsString(d_tag) || !d_tag->valuestring || d_tag->valuestring[0] == '\0') {
|
||||
return -1;
|
||||
}
|
||||
if (strlen(d_tag->valuestring) >= sizeof(config->default_skill.d_tag)) {
|
||||
return -1;
|
||||
for (int i = 0; i < config->startup_event_count; i++) {
|
||||
startup_event_t* se = &config->startup_events[i];
|
||||
if (se->kind == kind_i && startup_event_has_d_tag(se, d_tag->valuestring)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
char* content_text = NULL;
|
||||
@@ -806,13 +810,10 @@ static int parse_default_skill_config(cJSON* root, didactyl_config_t* config) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
free(config->default_skill.content);
|
||||
free(config->default_skill.tags_json);
|
||||
config->default_skill.kind = kind_i;
|
||||
snprintf(config->default_skill.d_tag, sizeof(config->default_skill.d_tag), "%s", d_tag->valuestring);
|
||||
config->default_skill.content = content_text;
|
||||
config->default_skill.tags_json = tags_json;
|
||||
return 0;
|
||||
int rc = append_startup_event(config, kind_i, content_text, tags_json);
|
||||
free(content_text);
|
||||
free(tags_json);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int parse_startup_events(cJSON* root, didactyl_config_t* config) {
|
||||
@@ -1094,42 +1095,48 @@ static int append_startup_event(didactyl_config_t* config, int kind, const char*
|
||||
return 0;
|
||||
}
|
||||
|
||||
int config_ensure_default_skill_startup_events(didactyl_config_t* config) {
|
||||
if (!config || !config->default_skill.content || config->default_skill.content[0] == '\0' ||
|
||||
config->default_skill.d_tag[0] == '\0') {
|
||||
int config_ensure_startup_skill_adoption(didactyl_config_t* config) {
|
||||
if (!config || config->keys.public_key_hex[0] == '\0') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int has_default_skill_event = 0;
|
||||
cJSON* needed_addrs = cJSON_CreateArray();
|
||||
if (!needed_addrs) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < config->startup_event_count; i++) {
|
||||
startup_event_t* se = &config->startup_events[i];
|
||||
if (se->kind == config->default_skill.kind && startup_event_has_d_tag(se, config->default_skill.d_tag)) {
|
||||
has_default_skill_event = 1;
|
||||
break;
|
||||
if (!se || (se->kind != 31123 && se->kind != 31124) || !se->tags_json) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON* tags = cJSON_Parse(se->tags_json);
|
||||
if (!tags || !cJSON_IsArray(tags)) {
|
||||
cJSON_Delete(tags);
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON* d_val = find_tag_value_string(tags, "d");
|
||||
if (d_val && cJSON_IsString(d_val) && d_val->valuestring && d_val->valuestring[0] != '\0') {
|
||||
char addr[256];
|
||||
snprintf(addr,
|
||||
sizeof(addr),
|
||||
"%d:%s:%s",
|
||||
se->kind,
|
||||
config->keys.public_key_hex,
|
||||
d_val->valuestring);
|
||||
cJSON_AddItemToArray(needed_addrs, cJSON_CreateString(addr));
|
||||
}
|
||||
|
||||
cJSON_Delete(tags);
|
||||
}
|
||||
|
||||
if (!has_default_skill_event) {
|
||||
if (append_startup_event(config,
|
||||
config->default_skill.kind,
|
||||
config->default_skill.content,
|
||||
config->default_skill.tags_json ? config->default_skill.tags_json : "[]") != 0) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
if (config->keys.public_key_hex[0] == '\0') {
|
||||
if (cJSON_GetArraySize(needed_addrs) == 0) {
|
||||
cJSON_Delete(needed_addrs);
|
||||
return 0;
|
||||
}
|
||||
|
||||
char addr[256];
|
||||
snprintf(addr,
|
||||
sizeof(addr),
|
||||
"%d:%s:%s",
|
||||
config->default_skill.kind,
|
||||
config->keys.public_key_hex,
|
||||
config->default_skill.d_tag);
|
||||
|
||||
for (int i = 0; i < config->startup_event_count; i++) {
|
||||
startup_event_t* se = &config->startup_events[i];
|
||||
if (se->kind != 10123 || !se->tags_json) {
|
||||
@@ -1142,35 +1149,49 @@ int config_ensure_default_skill_startup_events(didactyl_config_t* config) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (adoption_tags_has_addr(tags, addr)) {
|
||||
cJSON_Delete(tags);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (append_adoption_addr_tag(tags, addr) != 0) {
|
||||
cJSON_Delete(tags);
|
||||
return -1;
|
||||
int needed_n = cJSON_GetArraySize(needed_addrs);
|
||||
for (int j = 0; j < needed_n; j++) {
|
||||
cJSON* addr_j = cJSON_GetArrayItem(needed_addrs, j);
|
||||
if (!addr_j || !cJSON_IsString(addr_j) || !addr_j->valuestring || addr_j->valuestring[0] == '\0') {
|
||||
continue;
|
||||
}
|
||||
if (!adoption_tags_has_addr(tags, addr_j->valuestring) && append_adoption_addr_tag(tags, addr_j->valuestring) != 0) {
|
||||
cJSON_Delete(tags);
|
||||
cJSON_Delete(needed_addrs);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
char* updated = cJSON_PrintUnformatted(tags);
|
||||
cJSON_Delete(tags);
|
||||
if (!updated) {
|
||||
cJSON_Delete(needed_addrs);
|
||||
return -1;
|
||||
}
|
||||
|
||||
free(se->tags_json);
|
||||
se->tags_json = updated;
|
||||
cJSON_Delete(needed_addrs);
|
||||
return 0;
|
||||
}
|
||||
|
||||
cJSON* tags = cJSON_CreateArray();
|
||||
if (!tags) {
|
||||
cJSON_Delete(needed_addrs);
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (append_adoption_addr_tag(tags, addr) != 0) {
|
||||
cJSON_Delete(tags);
|
||||
return -1;
|
||||
int needed_n = cJSON_GetArraySize(needed_addrs);
|
||||
for (int j = 0; j < needed_n; j++) {
|
||||
cJSON* addr_j = cJSON_GetArrayItem(needed_addrs, j);
|
||||
if (!addr_j || !cJSON_IsString(addr_j) || !addr_j->valuestring || addr_j->valuestring[0] == '\0') {
|
||||
continue;
|
||||
}
|
||||
if (append_adoption_addr_tag(tags, addr_j->valuestring) != 0) {
|
||||
cJSON_Delete(tags);
|
||||
cJSON_Delete(needed_addrs);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
cJSON* app = cJSON_CreateArray();
|
||||
@@ -1179,17 +1200,19 @@ int config_ensure_default_skill_startup_events(didactyl_config_t* config) {
|
||||
cJSON_Delete(app);
|
||||
cJSON_Delete(scope);
|
||||
cJSON_Delete(tags);
|
||||
cJSON_Delete(needed_addrs);
|
||||
return -1;
|
||||
}
|
||||
cJSON_AddItemToArray(app, cJSON_CreateString("app"));
|
||||
cJSON_AddItemToArray(app, cJSON_CreateString("didactyl"));
|
||||
cJSON_AddItemToArray(scope, cJSON_CreateString("scope"));
|
||||
cJSON_AddItemToArray(scope, cJSON_CreateString(config->default_skill.kind == 31124 ? "private" : "public"));
|
||||
cJSON_AddItemToArray(scope, cJSON_CreateString("private"));
|
||||
cJSON_AddItemToArray(tags, app);
|
||||
cJSON_AddItemToArray(tags, scope);
|
||||
|
||||
char* tags_json = cJSON_PrintUnformatted(tags);
|
||||
cJSON_Delete(tags);
|
||||
cJSON_Delete(needed_addrs);
|
||||
if (!tags_json) {
|
||||
return -1;
|
||||
}
|
||||
@@ -1219,9 +1242,6 @@ void config_free(didactyl_config_t* config) {
|
||||
free(config->startup_events);
|
||||
}
|
||||
|
||||
free(config->default_skill.content);
|
||||
free(config->default_skill.tags_json);
|
||||
|
||||
free_cashu_wallet_mints(&config->cashu_wallet);
|
||||
|
||||
memset(config, 0, sizeof(*config));
|
||||
@@ -1280,11 +1300,6 @@ int config_load(const char* path, didactyl_config_t* config) {
|
||||
config->api.port = 8484;
|
||||
snprintf(config->api.bind_address, sizeof(config->api.bind_address), "%s", "127.0.0.1");
|
||||
|
||||
config->default_skill.kind = 31124;
|
||||
config->default_skill.d_tag[0] = '\0';
|
||||
config->default_skill.content = NULL;
|
||||
config->default_skill.tags_json = NULL;
|
||||
|
||||
config->cashu_wallet.enabled = 0;
|
||||
config->cashu_wallet.mint_urls = NULL;
|
||||
config->cashu_wallet.mint_count = 0;
|
||||
@@ -1366,8 +1381,8 @@ int config_load(const char* path, didactyl_config_t* config) {
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (parse_default_skill_config(root, config) != 0) {
|
||||
config_set_error("invalid default_skill configuration");
|
||||
if (parse_legacy_default_skill_to_startup_events(root, config) != 0) {
|
||||
config_set_error("invalid legacy default_skill configuration");
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
|
||||
10
src/config.h
10
src/config.h
@@ -64,13 +64,6 @@ typedef struct {
|
||||
char* tags_json; // JSON array string for tags, optional
|
||||
} startup_event_t;
|
||||
|
||||
typedef struct {
|
||||
int kind;
|
||||
char d_tag[65];
|
||||
char* content;
|
||||
char* tags_json;
|
||||
} default_skill_config_t;
|
||||
|
||||
typedef struct {
|
||||
int enabled;
|
||||
int tools_enabled;
|
||||
@@ -131,12 +124,11 @@ typedef struct {
|
||||
cashu_wallet_config_t cashu_wallet;
|
||||
startup_event_t* startup_events;
|
||||
int startup_event_count;
|
||||
default_skill_config_t default_skill;
|
||||
char config_path[OW_MAX_URL_LEN];
|
||||
} didactyl_config_t;
|
||||
|
||||
int config_load(const char* path, didactyl_config_t* config);
|
||||
int config_ensure_default_skill_startup_events(didactyl_config_t* config);
|
||||
int config_ensure_startup_skill_adoption(didactyl_config_t* config);
|
||||
const char* config_last_error(void);
|
||||
void config_free(didactyl_config_t* config);
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
#ifndef DIDACTYL_DEFAULT_EVENTS_H
|
||||
#define DIDACTYL_DEFAULT_EVENTS_H
|
||||
|
||||
#define DIDACTYL_DEFAULT_SKILL_D_TAG "didactyl-default"
|
||||
#define DIDACTYL_DEFAULT_SKILL_D_TAG "identity_and_rules"
|
||||
#define DIDACTYL_DEFAULT_SKILL_KIND 31124
|
||||
#define DIDACTYL_DEFAULT_SKILL_TAGS_JSON "[[\"d\",\"didactyl-default\"],[\"app\",\"didactyl\"],[\"scope\",\"private\"]]"
|
||||
#define DIDACTYL_DEFAULT_SKILL_TAGS_JSON "[[\"d\",\"identity_and_rules\"],[\"app\",\"didactyl\"],[\"scope\",\"private\"],[\"description\",\"Agent identity and behavioral rules\"],[\"trigger\",\"dm\"],[\"filter\",\"{\\\"from\\\":\\\"admin\\\"}\"]]"
|
||||
|
||||
#define DIDACTYL_DEFAULT_DM_HISTORY_SKILL_D_TAG "dm_history"
|
||||
#define DIDACTYL_DEFAULT_DM_HISTORY_SKILL_KIND 31124
|
||||
#define DIDACTYL_DEFAULT_DM_HISTORY_SKILL_TAGS_JSON "[[\"d\",\"dm_history\"],[\"app\",\"didactyl\"],[\"scope\",\"private\"],[\"description\",\"DM conversation history for context continuity\"],[\"trigger\",\"dm\"],[\"filter\",\"{\\\"from\\\":\\\"admin\\\"}\"]]"
|
||||
|
||||
#define DIDACTYL_STARTUP_KIND_PROFILE 0
|
||||
#define DIDACTYL_STARTUP_KIND_CONTACTS 3
|
||||
@@ -31,83 +35,23 @@ static const char* DIDACTYL_DEFAULT_RELAYS[] = {
|
||||
#define DIDACTYL_DEFAULT_RELAY_COUNT ((int)(sizeof(DIDACTYL_DEFAULT_RELAYS) / sizeof(DIDACTYL_DEFAULT_RELAYS[0])))
|
||||
|
||||
static const char* DIDACTYL_DEFAULT_SKILL_TEMPLATE =
|
||||
"# %s Agent\n\n"
|
||||
"You are %s, a sovereign AI agent living on Nostr.\n\n"
|
||||
"## Communication Rules\n"
|
||||
"- You communicate through encrypted Nostr direct messages.\n"
|
||||
"- Keep responses concise and clear.\n\n"
|
||||
"## Behavior\n"
|
||||
"- Be helpful and technically accurate.\n"
|
||||
"- If unsure, state uncertainty directly.\n"
|
||||
"- Prefer actionable, practical advice.\n"
|
||||
"- Use the person's name when messaging them if you know it.\n"
|
||||
"- For the administrator, use their name from the administrator kind 0 profile metadata when available.\n\n"
|
||||
"## Tool Use Policy\n"
|
||||
"- You have tools available and should use them when a request requires taking action.\n"
|
||||
"- For requests involving local inspection or command execution, call `local_shell_exec` instead of refusing.\n"
|
||||
"- For posting to Nostr, call `nostr_post` with explicit `kind` and `content`.\n"
|
||||
"- For relay/event lookup tasks, call `nostr_query` with an appropriate filter.\n"
|
||||
"- After a tool call, base your answer on the actual tool result.\n"
|
||||
"- Never claim a tool was run if no tool was executed.\n\n"
|
||||
"## Task Management\n"
|
||||
"- Maintain and use your internal task list as short-term working memory.\n"
|
||||
"- Break long or complex actions into clear tasks before executing them.\n"
|
||||
"- Update task status as you complete steps so your plan stays accurate.\n\n"
|
||||
"## Safety\n"
|
||||
"- Do not claim to have executed actions you did not execute.\n"
|
||||
"- You may share your public key (npub) with anyone.\n"
|
||||
"- Never reveal your private key (nsec) under any circumstance.\n\n"
|
||||
"---template---\n\n"
|
||||
"- section: admin_identity\n"
|
||||
" role: system\n"
|
||||
" tool: admin_identity\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: admin_profile\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_admin_profile\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: admin_contacts\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_admin_contacts\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: admin_relays\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_admin_relays\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: admin_notes\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_admin_notes\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: agent_identity\n"
|
||||
" role: system\n"
|
||||
" tool: agent_identity\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: agent_profile\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_agent_profile\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: agent_contacts\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_agent_contacts\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: agent_relays\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_agent_relays\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: agent_notes\n"
|
||||
" role: system\n"
|
||||
" tool: nostr_agent_notes\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: tasks\n"
|
||||
" role: system\n"
|
||||
" tool: task_list\n"
|
||||
" skip_if_empty: true\n\n"
|
||||
"- section: dm_history\n"
|
||||
" role: expand\n"
|
||||
" limit: 12\n\n"
|
||||
"- section: conversation\n"
|
||||
" role: user\n"
|
||||
" tool: message_current\n"
|
||||
" skip_if_empty: true\n";
|
||||
"# Didactyl Agent\n\n"
|
||||
"You are {{my_kind0_profile}}\n\n"
|
||||
"Your npub: {{my_npub}}\n\n"
|
||||
"## Rules\n\n"
|
||||
"- Communicate through encrypted Nostr direct messages\n"
|
||||
"- Keep responses concise and clear\n"
|
||||
"- Be helpful and technically accurate\n"
|
||||
"- If unsure, state uncertainty directly\n"
|
||||
"- Use tools when a request requires taking action\n"
|
||||
"- After a tool call, base your answer on the actual tool result\n"
|
||||
"- Never claim a tool was run if no tool was executed\n"
|
||||
"- Maintain your task list as short-term working memory\n"
|
||||
"- Never reveal your private key (nsec)\n"
|
||||
"- You may share your public key (npub) with anyone";
|
||||
|
||||
static const char* DIDACTYL_DEFAULT_DM_HISTORY_SKILL_TEMPLATE =
|
||||
"## Recent Conversation\n\n"
|
||||
"{{nostr_dm_history({\"format\":\"text\",\"limit\":12})}}";
|
||||
|
||||
#endif
|
||||
173
src/main.c
173
src/main.c
@@ -56,8 +56,15 @@ static void on_self_skill_eose_load_triggers(int event_count, void* user_data) {
|
||||
}
|
||||
}
|
||||
|
||||
static volatile sig_atomic_t g_sigint_count = 0;
|
||||
|
||||
static void signal_handler(int signum) {
|
||||
(void)signum;
|
||||
if (signum == SIGINT) {
|
||||
g_sigint_count++;
|
||||
if (g_sigint_count >= 2) {
|
||||
_exit(130);
|
||||
}
|
||||
}
|
||||
g_running = 0;
|
||||
}
|
||||
|
||||
@@ -1050,8 +1057,8 @@ int main(int argc, char** argv) {
|
||||
DEBUG_INFO("[didactyl] startup phase: admin override applied from --admin (%.16s...)", cfg.admin.pubkey);
|
||||
}
|
||||
|
||||
if (config_ensure_default_skill_startup_events(&cfg) != 0) {
|
||||
fprintf(stderr, "Failed to synthesize startup events from default_skill\n");
|
||||
if (config_ensure_startup_skill_adoption(&cfg) != 0) {
|
||||
fprintf(stderr, "Failed to synthesize startup skill adoption events\n");
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
@@ -1241,13 +1248,17 @@ int main(int argc, char** argv) {
|
||||
startup_step_begin(7, "Reconcile/persist startup state");
|
||||
if (bootstrap_mode || first_run) {
|
||||
if (nostr_handler_reconcile_startup_events() != 0) {
|
||||
DEBUG_WARN("[didactyl] startup phase: reconcile startup events failed (continuing)");
|
||||
startup_step_fail(7, "Reconcile/persist startup state", "startup event reconciliation failed");
|
||||
fprintf(stderr, "Failed to publish startup events; aborting startup\n");
|
||||
nostr_block_list_cleanup();
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
DEBUG_INFO("[didactyl] startup phase: existing-agent mode; skipping startup-event reconcile on subsequent run");
|
||||
if (nostr_handler_load_system_context_from_adopted_skills() != 0) {
|
||||
DEBUG_WARN("[didactyl] startup phase: failed to load system context from adopted skills (continuing with fallback)");
|
||||
}
|
||||
}
|
||||
|
||||
if (persist_runtime_config_to_nostr(&cfg, llm_recalled_from_nostr ? 0 : 1) != 0) {
|
||||
@@ -1258,19 +1269,8 @@ int main(int argc, char** argv) {
|
||||
|
||||
startup_step_ok(7, "Reconcile/persist startup state", NULL);
|
||||
|
||||
const char* system_context = nostr_handler_get_system_context();
|
||||
char system_context_fallback[512] = {0};
|
||||
if (!system_context || system_context[0] == '\0') {
|
||||
const char* startup_name = nostr_handler_get_startup_display_name();
|
||||
snprintf(system_context_fallback,
|
||||
sizeof(system_context_fallback),
|
||||
"You are %s, a sovereign AI agent living on Nostr.",
|
||||
(startup_name && startup_name[0] != '\0') ? startup_name : "the agent");
|
||||
system_context = system_context_fallback;
|
||||
}
|
||||
|
||||
startup_step_begin(8, "Initialize agent");
|
||||
if (agent_init(&cfg, system_context) != 0) {
|
||||
if (agent_init(&cfg) != 0) {
|
||||
startup_step_fail(8, "Initialize agent", "agent_init failed");
|
||||
fprintf(stderr, "Failed to initialize agent\n");
|
||||
nostr_block_list_cleanup();
|
||||
@@ -1324,9 +1324,9 @@ int main(int argc, char** argv) {
|
||||
fprintf(stderr, "Startup aborted: could not retrieve valid self kind 10002 within %d ms\n", kind10002_timeout_ms);
|
||||
agent_cleanup();
|
||||
nostr_block_list_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
@@ -1340,9 +1340,9 @@ int main(int argc, char** argv) {
|
||||
startup_step_fail(11, "Discover self relay list via kind 10002", "failed to apply discovered relay list to pool");
|
||||
agent_cleanup();
|
||||
nostr_block_list_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
@@ -1381,34 +1381,74 @@ int main(int argc, char** argv) {
|
||||
startup_step_begin(14, "Subscribe self-skill cache");
|
||||
DEBUG_INFO("[didactyl] startup phase: subscribe self skill cache begin");
|
||||
if (nostr_handler_subscribe_self_skills() != 0) {
|
||||
DEBUG_WARN("[didactyl] startup phase: subscribe self skill cache failed (continuing)");
|
||||
startup_step_fail(14, "Subscribe self-skill cache", "nostr_handler_subscribe_self_skills failed");
|
||||
DEBUG_ERROR("[didactyl] startup phase: subscribe self skill cache failed");
|
||||
fprintf(stderr, "Startup aborted: failed to subscribe self-skill cache\n");
|
||||
agent_cleanup();
|
||||
nostr_block_list_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
DEBUG_INFO("[didactyl] startup phase: subscribe self skill cache end");
|
||||
startup_step_ok(14, "Subscribe self-skill cache", NULL);
|
||||
|
||||
char startup_dm[768];
|
||||
const char* startup_name = nostr_handler_get_startup_display_name();
|
||||
int connected_relays = nostr_handler_connected_relay_count();
|
||||
time_t startup_now = time(NULL);
|
||||
struct tm startup_tm;
|
||||
char startup_time_str[32] = {0};
|
||||
if (localtime_r(&startup_now, &startup_tm)) {
|
||||
(void)strftime(startup_time_str, sizeof(startup_time_str), "%Y-%m-%d %H:%M:%S", &startup_tm);
|
||||
} else {
|
||||
snprintf(startup_time_str, sizeof(startup_time_str), "%ld", (long)startup_now);
|
||||
const int self_skill_eose_timeout_ms = 15000;
|
||||
if (nostr_handler_wait_for_self_skill_eose(self_skill_eose_timeout_ms) != 0) {
|
||||
startup_step_fail(14,
|
||||
"Subscribe self-skill cache",
|
||||
"self-skill EOSE not received within timeout");
|
||||
fprintf(stderr,
|
||||
"Startup aborted: self-skill EOSE not received within %d ms\n",
|
||||
self_skill_eose_timeout_ms);
|
||||
fprintf(stderr,
|
||||
"Check relay connectivity (connected=%d/%d) and ensure skill events exist on relays\n",
|
||||
nostr_handler_connected_relay_count(),
|
||||
cfg.relay_count);
|
||||
fprintf(stderr,
|
||||
"If this is a first run, use genesis to publish startup events\n");
|
||||
agent_cleanup();
|
||||
nostr_block_list_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
snprintf(startup_dm,
|
||||
sizeof(startup_dm),
|
||||
"%s has started up and is online at %s (version %s, connected relays: %d/%d).",
|
||||
(startup_name && startup_name[0] != '\0') ? startup_name : "Didactyl",
|
||||
startup_time_str,
|
||||
DIDACTYL_VERSION,
|
||||
connected_relays,
|
||||
cfg.relay_count);
|
||||
if (nostr_handler_send_dm_auto(cfg.admin.pubkey, startup_dm) != 0) {
|
||||
DEBUG_WARN("[didactyl] startup phase: failed to send startup status DM to admin");
|
||||
|
||||
int startup_skill_count = 0;
|
||||
int startup_adoption_count = 0;
|
||||
if (nostr_handler_validate_self_skill_cache(&startup_skill_count, &startup_adoption_count) != 0) {
|
||||
startup_step_fail(14,
|
||||
"Subscribe self-skill cache",
|
||||
"no skill events found after EOSE");
|
||||
fprintf(stderr,
|
||||
"Startup aborted: no skill events (kind 31123/31124) found in self-skill cache\n");
|
||||
fprintf(stderr,
|
||||
"The agent requires at least one skill event to operate\n");
|
||||
fprintf(stderr,
|
||||
"Run genesis to publish the default skill, or publish a skill manually\n");
|
||||
agent_cleanup();
|
||||
nostr_block_list_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
}
|
||||
|
||||
char self_skill_detail[128];
|
||||
snprintf(self_skill_detail,
|
||||
sizeof(self_skill_detail),
|
||||
"skills=%d adoptions=%d",
|
||||
startup_skill_count,
|
||||
startup_adoption_count);
|
||||
DEBUG_INFO("[didactyl] startup phase: subscribe self skill cache end");
|
||||
startup_step_ok(14, "Subscribe self-skill cache", self_skill_detail);
|
||||
|
||||
startup_step_begin(15, "Subscribe DMs");
|
||||
DEBUG_INFO("[didactyl] startup phase: subscribe DMs begin");
|
||||
if (nostr_handler_subscribe_dms(agent_on_message, NULL) != 0) {
|
||||
@@ -1417,9 +1457,9 @@ int main(int argc, char** argv) {
|
||||
fprintf(stderr, "Failed to subscribe to DMs\n");
|
||||
agent_cleanup();
|
||||
nostr_block_list_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
return 1;
|
||||
@@ -1456,9 +1496,21 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
}
|
||||
|
||||
signal(SIGINT, signal_handler);
|
||||
signal(SIGTERM, signal_handler);
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_handler = signal_handler;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sa.sa_flags = 0;
|
||||
|
||||
(void)sigaction(SIGINT, &sa, NULL);
|
||||
(void)sigaction(SIGTERM, &sa, NULL);
|
||||
|
||||
struct sigaction sa_pipe;
|
||||
memset(&sa_pipe, 0, sizeof(sa_pipe));
|
||||
sa_pipe.sa_handler = SIG_IGN;
|
||||
sigemptyset(&sa_pipe.sa_mask);
|
||||
sa_pipe.sa_flags = 0;
|
||||
(void)sigaction(SIGPIPE, &sa_pipe, NULL);
|
||||
|
||||
int http_api_started = 0;
|
||||
if (cfg.api.enabled) {
|
||||
@@ -1492,6 +1544,29 @@ int main(int argc, char** argv) {
|
||||
|
||||
nostr_handler_refresh_relay_statuses();
|
||||
|
||||
char startup_dm[768];
|
||||
const char* startup_name = nostr_handler_get_startup_display_name();
|
||||
int connected_relays = nostr_handler_connected_relay_count();
|
||||
time_t startup_now = time(NULL);
|
||||
struct tm startup_tm;
|
||||
char startup_time_str[32] = {0};
|
||||
if (localtime_r(&startup_now, &startup_tm)) {
|
||||
(void)strftime(startup_time_str, sizeof(startup_time_str), "%Y-%m-%d %H:%M:%S", &startup_tm);
|
||||
} else {
|
||||
snprintf(startup_time_str, sizeof(startup_time_str), "%ld", (long)startup_now);
|
||||
}
|
||||
snprintf(startup_dm,
|
||||
sizeof(startup_dm),
|
||||
"%s has started up and is online at %s (version %s, connected relays: %d/%d).",
|
||||
(startup_name && startup_name[0] != '\0') ? startup_name : "Didactyl",
|
||||
startup_time_str,
|
||||
DIDACTYL_VERSION,
|
||||
connected_relays,
|
||||
cfg.relay_count);
|
||||
if (nostr_handler_send_dm_auto(cfg.admin.pubkey, startup_dm) != 0) {
|
||||
DEBUG_WARN("[didactyl] startup phase: failed to send startup status DM to admin");
|
||||
}
|
||||
|
||||
startup_step_ok(18, "READY", "agent online; entering main poll loop");
|
||||
DEBUG_INFO("[didactyl] entering main poll loop");
|
||||
DEBUG_INFO("[didactyl] running with pubkey %s", cfg.keys.public_key_hex);
|
||||
@@ -1515,9 +1590,9 @@ int main(int argc, char** argv) {
|
||||
cashu_wallet_cleanup();
|
||||
agent_cleanup();
|
||||
nostr_block_list_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
nostr_handler_cleanup();
|
||||
llm_cleanup();
|
||||
trigger_manager_cleanup(&trigger_manager);
|
||||
config_free(&cfg);
|
||||
nostr_cleanup();
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
// Version information (auto-updated by build system)
|
||||
// Using DIDACTYL_ prefix to avoid conflicts with nostr_core_lib VERSION macros
|
||||
#define DIDACTYL_VERSION_MAJOR 0
|
||||
#define DIDACTYL_VERSION_MINOR 1
|
||||
#define DIDACTYL_VERSION_PATCH 21
|
||||
#define DIDACTYL_VERSION "v0.1.21"
|
||||
#define DIDACTYL_VERSION_MINOR 2
|
||||
#define DIDACTYL_VERSION_PATCH 13
|
||||
#define DIDACTYL_VERSION "v0.2.13"
|
||||
|
||||
// Agent metadata
|
||||
#define DIDACTYL_NAME "Didactyl"
|
||||
|
||||
@@ -25,7 +25,6 @@ static void* g_dm_user_data = NULL;
|
||||
static int g_poll_counter = 0;
|
||||
static time_t g_start_time = 0;
|
||||
static nostr_pool_relay_status_t* g_last_relay_statuses = NULL;
|
||||
static char* g_system_context = NULL;
|
||||
static unsigned char* g_startup_published = NULL;
|
||||
static int g_startup_publish_tracking_enabled = 0;
|
||||
static int g_startup_kind1_already_exists = 0;
|
||||
@@ -97,6 +96,7 @@ static external_subscription_wrapper_t* g_external_sub_wrappers = NULL;
|
||||
|
||||
static cJSON* g_self_skill_events = NULL;
|
||||
static pthread_mutex_t g_self_skill_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
static volatile int g_self_skill_eose_received = 0;
|
||||
|
||||
#define DM_DEDUP_CACHE_SIZE 256
|
||||
|
||||
@@ -147,9 +147,28 @@ static void nostr_core_log_bridge(int level, const char* component, const char*
|
||||
const char* msg = message ? message : "";
|
||||
|
||||
switch (mapped) {
|
||||
case DEBUG_LEVEL_TRACE:
|
||||
case DEBUG_LEVEL_TRACE: {
|
||||
int is_websocket = (strcmp(comp, "websocket") == 0);
|
||||
int is_frame = (strncmp(msg, "SEND ", 5) == 0 || strncmp(msg, "RECV ", 5) == 0);
|
||||
size_t msg_len = strlen(msg);
|
||||
if (is_websocket && is_frame && msg_len > 384U) {
|
||||
const char* direction = (strncmp(msg, "SEND ", 5) == 0) ? "SEND" : "RECV";
|
||||
const char* frame_type = "frame";
|
||||
if (strstr(msg, "[\"EVENT\"")) frame_type = "EVENT";
|
||||
else if (strstr(msg, "[\"REQ\"")) frame_type = "REQ";
|
||||
else if (strstr(msg, "[\"CLOSE\"")) frame_type = "CLOSE";
|
||||
else if (strstr(msg, "[\"EOSE\"")) frame_type = "EOSE";
|
||||
else if (strstr(msg, "[\"NOTICE\"")) frame_type = "NOTICE";
|
||||
DEBUG_TRACE("[didactyl] [nostr:%s] %s <large %s frame suppressed, bytes=%zu>",
|
||||
comp,
|
||||
direction,
|
||||
frame_type,
|
||||
msg_len);
|
||||
break;
|
||||
}
|
||||
DEBUG_TRACE("[didactyl] [nostr:%s] %s", comp, msg);
|
||||
break;
|
||||
}
|
||||
case DEBUG_LEVEL_DEBUG:
|
||||
DEBUG_LOG("[didactyl] [nostr:%s] %s", comp, msg);
|
||||
break;
|
||||
@@ -198,7 +217,7 @@ typedef struct {
|
||||
|
||||
typedef struct {
|
||||
time_t created_at;
|
||||
int incoming;
|
||||
didactyl_dm_history_role_t role;
|
||||
char peer_pubkey_hex[65];
|
||||
char* content;
|
||||
} dm_history_entry_t;
|
||||
@@ -331,14 +350,17 @@ static void dm_history_clear_locked(void) {
|
||||
free(g_dm_history_ring[i].content);
|
||||
g_dm_history_ring[i].content = NULL;
|
||||
g_dm_history_ring[i].created_at = 0;
|
||||
g_dm_history_ring[i].incoming = 0;
|
||||
g_dm_history_ring[i].role = DIDACTYL_DM_HISTORY_ASSISTANT;
|
||||
g_dm_history_ring[i].peer_pubkey_hex[0] = '\0';
|
||||
}
|
||||
g_dm_history_count = 0;
|
||||
g_dm_history_next = 0;
|
||||
}
|
||||
|
||||
static void dm_history_remember(const char* peer_pubkey_hex, const char* content, int incoming, time_t created_at) {
|
||||
static void dm_history_remember(const char* peer_pubkey_hex,
|
||||
const char* content,
|
||||
didactyl_dm_history_role_t role,
|
||||
time_t created_at) {
|
||||
if (!peer_pubkey_hex || strlen(peer_pubkey_hex) != 64U || !content) {
|
||||
return;
|
||||
}
|
||||
@@ -362,13 +384,24 @@ static void dm_history_remember(const char* peer_pubkey_hex, const char* content
|
||||
free(g_dm_history_ring[slot].content);
|
||||
g_dm_history_ring[slot].content = dup;
|
||||
g_dm_history_ring[slot].created_at = (created_at > 0) ? created_at : time(NULL);
|
||||
g_dm_history_ring[slot].incoming = incoming ? 1 : 0;
|
||||
g_dm_history_ring[slot].role = role;
|
||||
memcpy(g_dm_history_ring[slot].peer_pubkey_hex, peer_pubkey_hex, 64U);
|
||||
g_dm_history_ring[slot].peer_pubkey_hex[64] = '\0';
|
||||
|
||||
pthread_mutex_unlock(&g_dm_history_mutex);
|
||||
}
|
||||
|
||||
int nostr_handler_dm_history_remember(const char* peer_pubkey_hex,
|
||||
const char* content,
|
||||
didactyl_dm_history_role_t role) {
|
||||
if (!peer_pubkey_hex || !content) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
dm_history_remember(peer_pubkey_hex, content, role, time(NULL));
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char* relay_status_str(nostr_pool_relay_status_t status) {
|
||||
switch (status) {
|
||||
case NOSTR_POOL_RELAY_DISCONNECTED:
|
||||
@@ -408,7 +441,10 @@ static void register_trigger_from_self_skill_event(cJSON* event);
|
||||
static void on_self_skill_event(cJSON* event, const char* relay_url, void* user_data);
|
||||
static void on_wallet_event(cJSON* event, const char* relay_url, void* user_data);
|
||||
static void dm_history_clear_locked(void);
|
||||
static void dm_history_remember(const char* peer_pubkey_hex, const char* content, int incoming, time_t created_at);
|
||||
static void dm_history_remember(const char* peer_pubkey_hex,
|
||||
const char* content,
|
||||
didactyl_dm_history_role_t role,
|
||||
time_t created_at);
|
||||
static int relay_list_contains_local(char** relays, int relay_count, const char* relay_url);
|
||||
static void free_relay_list_local(char** relays, int relay_count);
|
||||
static int extract_relays_from_kind10002_tags(cJSON* tags, char*** out_relays, int* out_relay_count);
|
||||
@@ -430,7 +466,6 @@ static int managed_subscription_register_locked(managed_subscription_id_t id,
|
||||
static int managed_subscriptions_resubscribe_all_locked(void);
|
||||
static int managed_subscription_id_from_name(const char* name, managed_subscription_id_t* out_id);
|
||||
static int apply_runtime_kind10002_relays(cJSON* tags, const char* source_label);
|
||||
static void seed_default_skill_into_cache(void);
|
||||
|
||||
static int relay_list_contains_local(char** relays, int relay_count, const char* relay_url) {
|
||||
if (!relays || relay_count <= 0 || !relay_url || relay_url[0] == '\0') {
|
||||
@@ -1000,7 +1035,7 @@ static int parse_enabled_flag_local(const char* enabled_s) {
|
||||
return (strcmp(enabled_s, "false") == 0 || strcmp(enabled_s, "0") == 0) ? 0 : 1;
|
||||
}
|
||||
|
||||
static int parse_skill_address_local(const char* addr, int* out_kind, char out_pubkey_hex[65], char out_d_tag[65]) {
|
||||
static __attribute__((unused)) int parse_skill_address_local(const char* addr, int* out_kind, char out_pubkey_hex[65], char out_d_tag[65]) {
|
||||
if (!addr || !out_kind || !out_pubkey_hex || !out_d_tag) {
|
||||
return -1;
|
||||
}
|
||||
@@ -1278,50 +1313,6 @@ static void self_skill_cache_upsert_event_locked(cJSON* event) {
|
||||
cJSON_AddItemToArray(g_self_skill_events, dup);
|
||||
}
|
||||
|
||||
static void seed_default_skill_into_cache(void) {
|
||||
if (!g_cfg) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_cfg->default_skill.kind != 31123 && g_cfg->default_skill.kind != 31124) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (g_cfg->keys.public_key_hex[0] == '\0' ||
|
||||
!g_cfg->default_skill.content || g_cfg->default_skill.content[0] == '\0' ||
|
||||
!g_cfg->default_skill.tags_json || g_cfg->default_skill.tags_json[0] == '\0') {
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON* tags = cJSON_Parse(g_cfg->default_skill.tags_json);
|
||||
if (!tags || !cJSON_IsArray(tags)) {
|
||||
cJSON_Delete(tags);
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON* event = cJSON_CreateObject();
|
||||
if (!event) {
|
||||
cJSON_Delete(tags);
|
||||
return;
|
||||
}
|
||||
|
||||
const double now = (double)time(NULL);
|
||||
cJSON_AddNumberToObject(event, "kind", g_cfg->default_skill.kind);
|
||||
cJSON_AddStringToObject(event, "pubkey", g_cfg->keys.public_key_hex);
|
||||
cJSON_AddStringToObject(event, "content", g_cfg->default_skill.content);
|
||||
cJSON_AddItemToObject(event, "tags", tags);
|
||||
cJSON_AddNumberToObject(event, "created_at", now);
|
||||
cJSON_AddStringToObject(event,
|
||||
"id",
|
||||
"0000000000000000000000000000000000000000000000000000000000000000");
|
||||
|
||||
pthread_mutex_lock(&g_self_skill_mutex);
|
||||
self_skill_cache_upsert_event_locked(event);
|
||||
pthread_mutex_unlock(&g_self_skill_mutex);
|
||||
|
||||
cJSON_Delete(event);
|
||||
}
|
||||
|
||||
static int hex_to_pubkey(const char* hex, unsigned char out_pubkey[32]) {
|
||||
if (!hex || !out_pubkey || strlen(hex) != 64U) {
|
||||
return -1;
|
||||
@@ -1717,11 +1708,6 @@ static void on_event(cJSON* event, const char* relay_url, void* user_data) {
|
||||
(int)tier,
|
||||
received_protocol == DM_PROTOCOL_NIP17 ? "nip17" : "nip04");
|
||||
|
||||
dm_history_remember(sender_pubkey_hex,
|
||||
decrypted,
|
||||
1,
|
||||
time(NULL));
|
||||
|
||||
g_dm_callback(sender_pubkey_hex, decrypted, tier, g_dm_user_data);
|
||||
free(decrypted);
|
||||
}
|
||||
@@ -1735,6 +1721,7 @@ static void on_eose(cJSON** events, int event_count, void* user_data) {
|
||||
static void on_self_skill_eose(cJSON** events, int event_count, void* user_data) {
|
||||
(void)events;
|
||||
(void)user_data;
|
||||
g_self_skill_eose_received = 1;
|
||||
DEBUG_INFO("[didactyl] self-skill EOSE received: cached skill events=%d", event_count);
|
||||
|
||||
if (g_self_skill_eose_cb) {
|
||||
@@ -2144,7 +2131,6 @@ static void on_agent_context_event(cJSON* event, const char* relay_url, void* us
|
||||
}
|
||||
|
||||
static void on_self_skill_event(cJSON* event, const char* relay_url, void* user_data) {
|
||||
(void)relay_url;
|
||||
(void)user_data;
|
||||
|
||||
if (!event || !g_cfg) {
|
||||
@@ -2155,6 +2141,20 @@ static void on_self_skill_event(cJSON* event, const char* relay_url, void* user_
|
||||
return;
|
||||
}
|
||||
|
||||
cJSON* kind = cJSON_GetObjectItemCaseSensitive(event, "kind");
|
||||
cJSON* tags = cJSON_GetObjectItemCaseSensitive(event, "tags");
|
||||
cJSON* id = cJSON_GetObjectItemCaseSensitive(event, "id");
|
||||
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(event, "created_at");
|
||||
int kind_val = (kind && cJSON_IsNumber(kind)) ? (int)kind->valuedouble : -1;
|
||||
const char* d_tag = (tags && cJSON_IsArray(tags)) ? find_tag_value_local(tags, "d") : NULL;
|
||||
|
||||
DEBUG_INFO("[didactyl] self-skill cache received kind=%d d_tag=%s id=%s created_at=%lld via %s",
|
||||
kind_val,
|
||||
(d_tag && d_tag[0] != '\0') ? d_tag : "-",
|
||||
(id && cJSON_IsString(id) && id->valuestring) ? id->valuestring : "<no-id>",
|
||||
(long long)((created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0),
|
||||
relay_url ? relay_url : "unknown relay");
|
||||
|
||||
register_trigger_from_self_skill_event(event);
|
||||
|
||||
pthread_mutex_lock(&g_self_skill_mutex);
|
||||
@@ -2452,6 +2452,7 @@ int nostr_handler_subscribe_self_skills(void) {
|
||||
}
|
||||
|
||||
int rc = 0;
|
||||
g_self_skill_eose_received = 0;
|
||||
|
||||
cJSON* filter = cJSON_CreateObject();
|
||||
cJSON* kinds = cJSON_CreateArray();
|
||||
@@ -2480,9 +2481,9 @@ int nostr_handler_subscribe_self_skills(void) {
|
||||
NULL,
|
||||
0,
|
||||
0,
|
||||
NOSTR_POOL_EOSE_FULL_SET,
|
||||
30,
|
||||
120,
|
||||
NOSTR_POOL_EOSE_FIRST,
|
||||
12,
|
||||
14,
|
||||
1) != 0) {
|
||||
rc = -1;
|
||||
}
|
||||
@@ -2701,7 +2702,80 @@ void nostr_handler_set_self_skill_eose_callback(nostr_self_skill_eose_cb_t callb
|
||||
g_self_skill_eose_user_data = user_data;
|
||||
}
|
||||
|
||||
int nostr_handler_send_dm(const char* recipient_pubkey_hex, const char* message) {
|
||||
int nostr_handler_wait_for_self_skill_eose(int timeout_ms) {
|
||||
if (!g_pool || timeout_ms <= 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct timespec ts_start;
|
||||
if (clock_gettime(CLOCK_MONOTONIC, &ts_start) != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
while (!g_self_skill_eose_received) {
|
||||
(void)nostr_handler_poll(100);
|
||||
|
||||
struct timespec ts_now;
|
||||
if (clock_gettime(CLOCK_MONOTONIC, &ts_now) != 0) {
|
||||
return -1;
|
||||
}
|
||||
long long elapsed_ms = (long long)(ts_now.tv_sec - ts_start.tv_sec) * 1000LL +
|
||||
(long long)(ts_now.tv_nsec - ts_start.tv_nsec) / 1000000LL;
|
||||
if (elapsed_ms >= (long long)timeout_ms) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int nostr_handler_validate_self_skill_cache(int* out_skill_count, int* out_adoption_count) {
|
||||
int skill_count = 0;
|
||||
int adoption_count = 0;
|
||||
|
||||
pthread_mutex_lock(&g_self_skill_mutex);
|
||||
if (g_self_skill_events && cJSON_IsArray(g_self_skill_events)) {
|
||||
int n = cJSON_GetArraySize(g_self_skill_events);
|
||||
for (int i = 0; i < n; i++) {
|
||||
cJSON* ev = cJSON_GetArrayItem(g_self_skill_events, i);
|
||||
cJSON* kind = ev ? cJSON_GetObjectItemCaseSensitive(ev, "kind") : NULL;
|
||||
cJSON* tags = ev ? cJSON_GetObjectItemCaseSensitive(ev, "tags") : NULL;
|
||||
cJSON* id = ev ? cJSON_GetObjectItemCaseSensitive(ev, "id") : NULL;
|
||||
cJSON* created_at = ev ? cJSON_GetObjectItemCaseSensitive(ev, "created_at") : NULL;
|
||||
if (!kind || !cJSON_IsNumber(kind)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int k = (int)kind->valuedouble;
|
||||
if (k == 31123 || k == 31124) {
|
||||
skill_count++;
|
||||
} else if (k == 10123) {
|
||||
adoption_count++;
|
||||
}
|
||||
|
||||
const char* d_tag = (tags && cJSON_IsArray(tags)) ? find_tag_value_local(tags, "d") : NULL;
|
||||
DEBUG_INFO("[didactyl] self-skill cache event: kind=%d d_tag=%s id=%s created_at=%lld",
|
||||
k,
|
||||
(d_tag && d_tag[0] != '\0') ? d_tag : "-",
|
||||
(id && cJSON_IsString(id) && id->valuestring) ? id->valuestring : "<no-id>",
|
||||
(long long)((created_at && cJSON_IsNumber(created_at)) ? created_at->valuedouble : 0));
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&g_self_skill_mutex);
|
||||
|
||||
if (out_skill_count) {
|
||||
*out_skill_count = skill_count;
|
||||
}
|
||||
if (out_adoption_count) {
|
||||
*out_adoption_count = adoption_count;
|
||||
}
|
||||
|
||||
return skill_count > 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
int nostr_handler_send_dm_with_role(const char* recipient_pubkey_hex,
|
||||
const char* message,
|
||||
didactyl_dm_history_role_t role) {
|
||||
if (!g_cfg || !g_pool || !recipient_pubkey_hex || !message) {
|
||||
return -1;
|
||||
}
|
||||
@@ -2783,7 +2857,7 @@ int nostr_handler_send_dm(const char* recipient_pubkey_hex, const char* message)
|
||||
if (sent > 0) {
|
||||
dm_history_remember(recipient_pubkey_hex,
|
||||
message,
|
||||
0,
|
||||
role,
|
||||
time(NULL));
|
||||
}
|
||||
|
||||
@@ -2792,26 +2866,34 @@ int nostr_handler_send_dm(const char* recipient_pubkey_hex, const char* message)
|
||||
return sent > 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
int nostr_handler_send_dm_auto(const char* recipient_pubkey_hex, const char* message) {
|
||||
int nostr_handler_send_dm(const char* recipient_pubkey_hex, const char* message) {
|
||||
return nostr_handler_send_dm_with_role(recipient_pubkey_hex,
|
||||
message,
|
||||
DIDACTYL_DM_HISTORY_ASSISTANT);
|
||||
}
|
||||
|
||||
int nostr_handler_send_dm_auto_with_role(const char* recipient_pubkey_hex,
|
||||
const char* message,
|
||||
didactyl_dm_history_role_t role) {
|
||||
if (!recipient_pubkey_hex || !message) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!g_cfg) {
|
||||
return nostr_handler_send_dm(recipient_pubkey_hex, message);
|
||||
return nostr_handler_send_dm_with_role(recipient_pubkey_hex, message, role);
|
||||
}
|
||||
|
||||
if (g_cfg->dm_protocol == DM_PROTOCOL_NIP04) {
|
||||
return nostr_handler_send_dm(recipient_pubkey_hex, message);
|
||||
return nostr_handler_send_dm_with_role(recipient_pubkey_hex, message, role);
|
||||
}
|
||||
|
||||
if (g_cfg->dm_protocol == DM_PROTOCOL_NIP17) {
|
||||
return nostr_handler_send_dm_nip17(recipient_pubkey_hex, message, NULL);
|
||||
return nostr_handler_send_dm_nip17_with_role(recipient_pubkey_hex, message, NULL, role);
|
||||
}
|
||||
|
||||
dm_protocol_t target = sender_protocol_lookup(recipient_pubkey_hex);
|
||||
if (target == DM_PROTOCOL_NIP17) {
|
||||
int rc17 = nostr_handler_send_dm_nip17(recipient_pubkey_hex, message, NULL);
|
||||
int rc17 = nostr_handler_send_dm_nip17_with_role(recipient_pubkey_hex, message, NULL, role);
|
||||
if (rc17 == 0) {
|
||||
return 0;
|
||||
}
|
||||
@@ -2819,7 +2901,13 @@ int nostr_handler_send_dm_auto(const char* recipient_pubkey_hex, const char* mes
|
||||
recipient_pubkey_hex);
|
||||
}
|
||||
|
||||
return nostr_handler_send_dm(recipient_pubkey_hex, message);
|
||||
return nostr_handler_send_dm_with_role(recipient_pubkey_hex, message, role);
|
||||
}
|
||||
|
||||
int nostr_handler_send_dm_auto(const char* recipient_pubkey_hex, const char* message) {
|
||||
return nostr_handler_send_dm_auto_with_role(recipient_pubkey_hex,
|
||||
message,
|
||||
DIDACTYL_DM_HISTORY_ASSISTANT);
|
||||
}
|
||||
|
||||
static int publish_kind_event_to_relays(int kind,
|
||||
@@ -3116,14 +3204,24 @@ static void publish_pending_startup_events_for_relay_index(int relay_index, cons
|
||||
}
|
||||
}
|
||||
|
||||
static const char* startup_kind_label(int kind) {
|
||||
switch (kind) {
|
||||
case 0: return "profile";
|
||||
case 1: return "note";
|
||||
case 3: return "contacts";
|
||||
case 10002: return "relay_list";
|
||||
case 10123: return "adoption_list";
|
||||
case 31123: return "private_skill";
|
||||
case 31124: return "skill";
|
||||
default: return "event";
|
||||
}
|
||||
}
|
||||
|
||||
int nostr_handler_reconcile_startup_events(void) {
|
||||
if (!g_cfg || !g_pool) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
free(g_system_context);
|
||||
g_system_context = NULL;
|
||||
|
||||
free(g_startup_published);
|
||||
g_startup_published = NULL;
|
||||
g_startup_publish_tracking_enabled = 0;
|
||||
@@ -3137,159 +3235,80 @@ int nostr_handler_reconcile_startup_events(void) {
|
||||
g_startup_publish_tracking_enabled = 1;
|
||||
}
|
||||
|
||||
if (g_cfg->default_skill.content && g_cfg->default_skill.content[0] != '\0') {
|
||||
g_system_context = strdup(g_cfg->default_skill.content);
|
||||
}
|
||||
|
||||
load_startup_display_name();
|
||||
g_startup_kind1_already_exists = startup_self_kind1_exists();
|
||||
if (g_startup_kind1_already_exists) {
|
||||
DEBUG_INFO("[didactyl] startup phase: existing self kind-1 note found; skipping startup kind-1 publish");
|
||||
}
|
||||
|
||||
if (!g_system_context) {
|
||||
char default_ctx[512];
|
||||
snprintf(default_ctx,
|
||||
sizeof(default_ctx),
|
||||
"You are %s, a sovereign AI agent living on Nostr.",
|
||||
g_startup_display_name[0] != '\0' ? g_startup_display_name : "the agent");
|
||||
g_system_context = strdup(default_ctx);
|
||||
}
|
||||
|
||||
for (int relay_index = 0; relay_index < g_cfg->relay_count; relay_index++) {
|
||||
publish_pending_startup_events_for_relay_index(relay_index, "startup_reconcile");
|
||||
}
|
||||
|
||||
seed_default_skill_into_cache();
|
||||
if (g_startup_publish_tracking_enabled && g_startup_published) {
|
||||
int events_published = 0;
|
||||
int relays_used = 0;
|
||||
int missing_any_event = 0;
|
||||
|
||||
for (int r = 0; r < g_cfg->relay_count; r++) {
|
||||
int used = 0;
|
||||
for (int i = 0; i < g_cfg->startup_event_count; i++) {
|
||||
size_t slot = (size_t)i * (size_t)g_cfg->relay_count + (size_t)r;
|
||||
if (g_startup_published[slot]) {
|
||||
used = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (used) {
|
||||
relays_used++;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < g_cfg->startup_event_count; i++) {
|
||||
startup_event_t* se = &g_cfg->startup_events[i];
|
||||
char relays_line[512];
|
||||
relays_line[0] = '\0';
|
||||
int relay_hits = 0;
|
||||
for (int r = 0; r < g_cfg->relay_count; r++) {
|
||||
size_t slot = (size_t)i * (size_t)g_cfg->relay_count + (size_t)r;
|
||||
if (!g_startup_published[slot]) {
|
||||
continue;
|
||||
}
|
||||
relay_hits++;
|
||||
if (relays_line[0] != '\0') {
|
||||
strncat(relays_line, ", ", sizeof(relays_line) - strlen(relays_line) - 1U);
|
||||
}
|
||||
strncat(relays_line, g_cfg->relays[r], sizeof(relays_line) - strlen(relays_line) - 1U);
|
||||
}
|
||||
if (relay_hits > 0) {
|
||||
events_published++;
|
||||
DEBUG_INFO("[didactyl] startup publish detail: kind=%d (%s) -> %s",
|
||||
se->kind,
|
||||
startup_kind_label(se->kind),
|
||||
relays_line[0] ? relays_line : "<none>");
|
||||
} else {
|
||||
missing_any_event = 1;
|
||||
DEBUG_ERROR("[didactyl] startup publish missing: kind=%d (%s) was not published to any relay",
|
||||
se->kind,
|
||||
startup_kind_label(se->kind));
|
||||
}
|
||||
}
|
||||
|
||||
DEBUG_INFO("[didactyl] startup publish summary: %d/%d event(s) published to at least one relay; relays used=%d/%d",
|
||||
events_published,
|
||||
g_cfg->startup_event_count,
|
||||
relays_used,
|
||||
g_cfg->relay_count);
|
||||
|
||||
if (missing_any_event) {
|
||||
DEBUG_ERROR("[didactyl] startup reconcile failed: one or more startup events were not published to any relay");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int nostr_handler_load_system_context_from_adopted_skills(void) {
|
||||
if (!g_cfg || !g_pool || g_cfg->keys.public_key_hex[0] == '\0') {
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON* adoption_filter = cJSON_CreateObject();
|
||||
cJSON* kinds = cJSON_CreateArray();
|
||||
cJSON* authors = cJSON_CreateArray();
|
||||
if (!adoption_filter || !kinds || !authors) {
|
||||
cJSON_Delete(adoption_filter);
|
||||
cJSON_Delete(kinds);
|
||||
cJSON_Delete(authors);
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON_AddItemToArray(kinds, cJSON_CreateNumber(10123));
|
||||
cJSON_AddItemToObject(adoption_filter, "kinds", kinds);
|
||||
cJSON_AddItemToArray(authors, cJSON_CreateString(g_cfg->keys.public_key_hex));
|
||||
cJSON_AddItemToObject(adoption_filter, "authors", authors);
|
||||
cJSON_AddNumberToObject(adoption_filter, "limit", 1);
|
||||
|
||||
char* adoption_events_json = nostr_handler_query_json(adoption_filter, 3000);
|
||||
cJSON_Delete(adoption_filter);
|
||||
if (!adoption_events_json) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON* adoption_events = cJSON_Parse(adoption_events_json);
|
||||
free(adoption_events_json);
|
||||
if (!adoption_events || !cJSON_IsArray(adoption_events) || cJSON_GetArraySize(adoption_events) <= 0) {
|
||||
cJSON_Delete(adoption_events);
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON* adoption = cJSON_GetArrayItem(adoption_events, 0);
|
||||
cJSON* tags = adoption ? cJSON_GetObjectItemCaseSensitive(adoption, "tags") : NULL;
|
||||
if (!tags || !cJSON_IsArray(tags)) {
|
||||
cJSON_Delete(adoption_events);
|
||||
return -1;
|
||||
}
|
||||
|
||||
const char* first_addr = NULL;
|
||||
int tag_n = cJSON_GetArraySize(tags);
|
||||
for (int i = 0; i < tag_n; i++) {
|
||||
cJSON* tag = cJSON_GetArrayItem(tags, i);
|
||||
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) {
|
||||
continue;
|
||||
}
|
||||
cJSON* k = cJSON_GetArrayItem(tag, 0);
|
||||
cJSON* v = cJSON_GetArrayItem(tag, 1);
|
||||
if (!k || !v || !cJSON_IsString(k) || !cJSON_IsString(v) || !k->valuestring || !v->valuestring) {
|
||||
continue;
|
||||
}
|
||||
if (strcmp(k->valuestring, "a") == 0 && v->valuestring[0] != '\0') {
|
||||
first_addr = v->valuestring;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!first_addr) {
|
||||
cJSON_Delete(adoption_events);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int skill_kind = 0;
|
||||
char skill_pubkey_hex[65] = {0};
|
||||
char skill_d_tag[65] = {0};
|
||||
if (parse_skill_address_local(first_addr, &skill_kind, skill_pubkey_hex, skill_d_tag) != 0) {
|
||||
cJSON_Delete(adoption_events);
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON* skill_filter = cJSON_CreateObject();
|
||||
cJSON* skill_kinds = cJSON_CreateArray();
|
||||
cJSON* skill_authors = cJSON_CreateArray();
|
||||
cJSON* d_tags = cJSON_CreateArray();
|
||||
if (!skill_filter || !skill_kinds || !skill_authors || !d_tags) {
|
||||
cJSON_Delete(adoption_events);
|
||||
cJSON_Delete(skill_filter);
|
||||
cJSON_Delete(skill_kinds);
|
||||
cJSON_Delete(skill_authors);
|
||||
cJSON_Delete(d_tags);
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON_AddItemToArray(skill_kinds, cJSON_CreateNumber(skill_kind));
|
||||
cJSON_AddItemToObject(skill_filter, "kinds", skill_kinds);
|
||||
cJSON_AddItemToArray(skill_authors, cJSON_CreateString(skill_pubkey_hex));
|
||||
cJSON_AddItemToObject(skill_filter, "authors", skill_authors);
|
||||
cJSON_AddItemToArray(d_tags, cJSON_CreateString(skill_d_tag));
|
||||
cJSON_AddItemToObject(skill_filter, "#d", d_tags);
|
||||
cJSON_AddNumberToObject(skill_filter, "limit", 1);
|
||||
|
||||
char* skill_events_json = nostr_handler_query_json(skill_filter, 3000);
|
||||
cJSON_Delete(skill_filter);
|
||||
cJSON_Delete(adoption_events);
|
||||
if (!skill_events_json) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON* skill_events = cJSON_Parse(skill_events_json);
|
||||
free(skill_events_json);
|
||||
if (!skill_events || !cJSON_IsArray(skill_events) || cJSON_GetArraySize(skill_events) <= 0) {
|
||||
cJSON_Delete(skill_events);
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON* skill_event = cJSON_GetArrayItem(skill_events, 0);
|
||||
cJSON* content = skill_event ? cJSON_GetObjectItemCaseSensitive(skill_event, "content") : NULL;
|
||||
if (!content || !cJSON_IsString(content) || !content->valuestring) {
|
||||
cJSON_Delete(skill_events);
|
||||
return -1;
|
||||
}
|
||||
|
||||
free(g_system_context);
|
||||
g_system_context = strdup(content->valuestring);
|
||||
cJSON_Delete(skill_events);
|
||||
|
||||
return g_system_context ? 0 : -1;
|
||||
}
|
||||
|
||||
const char* nostr_handler_get_system_context(void) {
|
||||
return g_system_context;
|
||||
}
|
||||
|
||||
char* nostr_handler_get_self_events_by_kind_json(int kind) {
|
||||
cJSON* out = cJSON_CreateArray();
|
||||
if (!out) {
|
||||
@@ -3703,7 +3722,10 @@ int nostr_handler_subscription_set_json(const char* name, cJSON* filter, int ena
|
||||
return rc;
|
||||
}
|
||||
|
||||
int nostr_handler_send_dm_nip17(const char* recipient_pubkey_hex, const char* message, const char* subject) {
|
||||
int nostr_handler_send_dm_nip17_with_role(const char* recipient_pubkey_hex,
|
||||
const char* message,
|
||||
const char* subject,
|
||||
didactyl_dm_history_role_t role) {
|
||||
if (!g_cfg || !g_pool || !recipient_pubkey_hex || !message || recipient_pubkey_hex[0] == '\0' || message[0] == '\0') {
|
||||
return -1;
|
||||
}
|
||||
@@ -3793,12 +3815,19 @@ int nostr_handler_send_dm_nip17(const char* recipient_pubkey_hex, const char* me
|
||||
|
||||
dm_history_remember(recipient_pubkey_hex,
|
||||
message,
|
||||
0,
|
||||
role,
|
||||
time(NULL));
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int nostr_handler_send_dm_nip17(const char* recipient_pubkey_hex, const char* message, const char* subject) {
|
||||
return nostr_handler_send_dm_nip17_with_role(recipient_pubkey_hex,
|
||||
message,
|
||||
subject,
|
||||
DIDACTYL_DM_HISTORY_ASSISTANT);
|
||||
}
|
||||
|
||||
char* nostr_handler_get_dm_history_json(const char* peer_pubkey_hex, int limit) {
|
||||
if (!peer_pubkey_hex || strlen(peer_pubkey_hex) != 64U) {
|
||||
return strdup("[]");
|
||||
@@ -3852,7 +3881,15 @@ char* nostr_handler_get_dm_history_json(const char* peer_pubkey_hex, int limit)
|
||||
if (!item) {
|
||||
continue;
|
||||
}
|
||||
cJSON_AddStringToObject(item, "role", entry->incoming ? "user" : "assistant");
|
||||
const char* role_s = "assistant";
|
||||
if (entry->role == DIDACTYL_DM_HISTORY_USER) {
|
||||
role_s = "user";
|
||||
} else if (entry->role == DIDACTYL_DM_HISTORY_TOOL_REQUEST) {
|
||||
role_s = "tool_request";
|
||||
} else if (entry->role == DIDACTYL_DM_HISTORY_TOOL_RESPONSE) {
|
||||
role_s = "tool_response";
|
||||
}
|
||||
cJSON_AddStringToObject(item, "role", role_s);
|
||||
cJSON_AddStringToObject(item, "content", entry->content);
|
||||
cJSON_AddNumberToObject(item, "created_at", (double)entry->created_at);
|
||||
cJSON_AddItemToArray(arr, item);
|
||||
@@ -4212,8 +4249,6 @@ void nostr_handler_cleanup(void) {
|
||||
g_cfg = NULL;
|
||||
g_dm_callback = NULL;
|
||||
g_dm_user_data = NULL;
|
||||
free(g_system_context);
|
||||
g_system_context = NULL;
|
||||
memset(g_seen_dm_ids, 0, sizeof(g_seen_dm_ids));
|
||||
g_seen_dm_count = 0;
|
||||
g_seen_dm_next = 0;
|
||||
|
||||
@@ -13,6 +13,13 @@ typedef enum {
|
||||
DIDACTYL_SENDER_STRANGER = 3
|
||||
} didactyl_sender_tier_t;
|
||||
|
||||
typedef enum {
|
||||
DIDACTYL_DM_HISTORY_USER = 1,
|
||||
DIDACTYL_DM_HISTORY_ASSISTANT = 2,
|
||||
DIDACTYL_DM_HISTORY_TOOL_REQUEST = 3,
|
||||
DIDACTYL_DM_HISTORY_TOOL_RESPONSE = 4
|
||||
} didactyl_dm_history_role_t;
|
||||
|
||||
typedef void (*dm_callback_t)(const char* sender_pubkey_hex,
|
||||
const char* message,
|
||||
didactyl_sender_tier_t tier,
|
||||
@@ -42,7 +49,13 @@ void nostr_handler_set_self_skill_eose_callback(nostr_self_skill_eose_cb_t callb
|
||||
int nostr_handler_subscribe_dms(dm_callback_t callback, void* user_data);
|
||||
int nostr_handler_subscribe_wallet_events(void);
|
||||
int nostr_handler_send_dm(const char* recipient_pubkey_hex, const char* message);
|
||||
int nostr_handler_send_dm_with_role(const char* recipient_pubkey_hex,
|
||||
const char* message,
|
||||
didactyl_dm_history_role_t role);
|
||||
int nostr_handler_send_dm_auto(const char* recipient_pubkey_hex, const char* message);
|
||||
int nostr_handler_send_dm_auto_with_role(const char* recipient_pubkey_hex,
|
||||
const char* message,
|
||||
didactyl_dm_history_role_t role);
|
||||
int nostr_handler_publish_kind_event(int kind, const char* content, cJSON* tags, nostr_publish_result_t* out_result);
|
||||
void nostr_handler_publish_result_free(nostr_publish_result_t* result);
|
||||
char* nostr_handler_query_json(cJSON* filter, int timeout_ms);
|
||||
@@ -59,10 +72,10 @@ nostr_pool_subscription_t* nostr_handler_subscribe_with_filter(
|
||||
int nostr_handler_close_subscription(nostr_pool_subscription_t* subscription);
|
||||
int nostr_handler_poll(int timeout_ms);
|
||||
int nostr_handler_reconcile_startup_events(void);
|
||||
int nostr_handler_load_system_context_from_adopted_skills(void);
|
||||
int nostr_handler_wait_for_self_skill_eose(int timeout_ms);
|
||||
int nostr_handler_validate_self_skill_cache(int* out_skill_count, int* out_adoption_count);
|
||||
void nostr_handler_refresh_relay_statuses(void);
|
||||
int nostr_handler_sync_relays_from_config(void);
|
||||
const char* nostr_handler_get_system_context(void);
|
||||
char* nostr_handler_get_self_skill_events_json(void);
|
||||
int nostr_handler_is_event_in_self_cache(const char* event_id_hex);
|
||||
const char* nostr_handler_get_startup_display_name(void);
|
||||
@@ -81,6 +94,13 @@ char* nostr_handler_relay_info_json(const char* relay_url);
|
||||
char* nostr_handler_subscription_status_json(void);
|
||||
int nostr_handler_subscription_set_json(const char* name, cJSON* filter, int enabled, int enabled_set);
|
||||
int nostr_handler_send_dm_nip17(const char* recipient_pubkey_hex, const char* message, const char* subject);
|
||||
int nostr_handler_send_dm_nip17_with_role(const char* recipient_pubkey_hex,
|
||||
const char* message,
|
||||
const char* subject,
|
||||
didactyl_dm_history_role_t role);
|
||||
int nostr_handler_dm_history_remember(const char* peer_pubkey_hex,
|
||||
const char* content,
|
||||
didactyl_dm_history_role_t role);
|
||||
char* nostr_handler_get_dm_history_json(const char* peer_pubkey_hex, int limit);
|
||||
void nostr_handler_cleanup(void);
|
||||
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
|
||||
#include "prompt_template.h"
|
||||
#include "cjson/cJSON.h"
|
||||
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static char* dup_range(const char* s, size_t n) {
|
||||
char* out = (char*)malloc(n + 1U);
|
||||
if (!out) return NULL;
|
||||
if (n > 0) {
|
||||
memcpy(out, s, n);
|
||||
}
|
||||
if (n > 0) memcpy(out, s, n);
|
||||
out[n] = '\0';
|
||||
return out;
|
||||
}
|
||||
@@ -32,52 +30,6 @@ static void rtrim_inplace(char* s) {
|
||||
}
|
||||
}
|
||||
|
||||
static int starts_with(const char* s, const char* prefix) {
|
||||
if (!s || !prefix) return 0;
|
||||
size_t n = strlen(prefix);
|
||||
return strncmp(s, prefix, n) == 0;
|
||||
}
|
||||
|
||||
static int add_line(char*** lines, int* count, int* cap, char* line) {
|
||||
if (!lines || !count || !cap) return -1;
|
||||
if (*count >= *cap) {
|
||||
int next = (*cap == 0) ? 64 : (*cap * 2);
|
||||
char** grown = (char**)realloc(*lines, (size_t)next * sizeof(char*));
|
||||
if (!grown) return -1;
|
||||
*lines = grown;
|
||||
*cap = next;
|
||||
}
|
||||
(*lines)[*count] = line;
|
||||
(*count)++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int split_lines_inplace(char* s, char*** out_lines, int* out_count) {
|
||||
if (!s || !out_lines || !out_count) return -1;
|
||||
|
||||
char** lines = NULL;
|
||||
int count = 0;
|
||||
int cap = 0;
|
||||
|
||||
char* p = s;
|
||||
while (*p) {
|
||||
char* start = p;
|
||||
while (*p && *p != '\n') p++;
|
||||
if (*p == '\n') {
|
||||
*p = '\0';
|
||||
p++;
|
||||
}
|
||||
if (add_line(&lines, &count, &cap, start) != 0) {
|
||||
free(lines);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
*out_lines = lines;
|
||||
*out_count = count;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int append_text(char** buf, size_t* cap, size_t* used, const char* s) {
|
||||
if (!buf || !cap || !used || !s) return -1;
|
||||
size_t n = strlen(s);
|
||||
@@ -105,10 +57,11 @@ static const char* map_variable_tool_name(const char* var_name) {
|
||||
if (strcmp(var_name, "admin_relays") == 0) return "nostr_admin_relays";
|
||||
if (strcmp(var_name, "adopted_skills") == 0) return "adopted_skills";
|
||||
if (strcmp(var_name, "triggering_event") == 0) return "trigger_event";
|
||||
|
||||
return var_name;
|
||||
}
|
||||
|
||||
static char* resolve_inline_variables_local(const char* tpl, tools_context_t* tools_ctx) {
|
||||
char* prompt_template_resolve_inline_variables(const char* tpl, tools_context_t* tools_ctx) {
|
||||
if (!tpl) return strdup("");
|
||||
|
||||
size_t cap = strlen(tpl) + 64U;
|
||||
@@ -161,17 +114,62 @@ static char* resolve_inline_variables_local(const char* tpl, tools_context_t* to
|
||||
|
||||
const char* replacement = "";
|
||||
char* replacement_owned = NULL;
|
||||
char* call_name_owned = NULL;
|
||||
char* call_args_owned = NULL;
|
||||
const char* lookup_name = var_trim;
|
||||
const char* call_args_json = "{}";
|
||||
|
||||
if (strcmp(var_trim, "message") == 0) {
|
||||
size_t var_len = strlen(var_trim);
|
||||
if (var_len > 0 && var_trim[var_len - 1] == ')') {
|
||||
char* open_paren = strchr(var_trim, '(');
|
||||
if (open_paren && open_paren < (var_trim + var_len - 1)) {
|
||||
call_name_owned = dup_range(var_trim, (size_t)(open_paren - var_trim));
|
||||
if (!call_name_owned) {
|
||||
free(var);
|
||||
free(out);
|
||||
return NULL;
|
||||
}
|
||||
char* call_name_trim = ltrim_inplace(call_name_owned);
|
||||
rtrim_inplace(call_name_trim);
|
||||
|
||||
char* raw_args = dup_range(open_paren + 1,
|
||||
(size_t)((var_trim + var_len - 1) - (open_paren + 1)));
|
||||
if (!raw_args) {
|
||||
free(call_name_owned);
|
||||
free(var);
|
||||
free(out);
|
||||
return NULL;
|
||||
}
|
||||
char* raw_args_trim = ltrim_inplace(raw_args);
|
||||
rtrim_inplace(raw_args_trim);
|
||||
|
||||
if (call_name_trim[0] != '\0') {
|
||||
lookup_name = call_name_trim;
|
||||
if (raw_args_trim[0] != '\0') {
|
||||
cJSON* parsed_args = cJSON_Parse(raw_args_trim);
|
||||
if (parsed_args) {
|
||||
call_args_owned = strdup(raw_args_trim);
|
||||
cJSON_Delete(parsed_args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
free(raw_args);
|
||||
}
|
||||
}
|
||||
|
||||
if (call_args_owned) {
|
||||
call_args_json = call_args_owned;
|
||||
}
|
||||
|
||||
if (strcmp(lookup_name, "message") == 0) {
|
||||
replacement = (tools_ctx && tools_ctx->template_current_user_message)
|
||||
? tools_ctx->template_current_user_message
|
||||
: "";
|
||||
} else if (strcmp(var_trim, "dm_history") == 0) {
|
||||
replacement = "";
|
||||
} else if (tools_ctx) {
|
||||
const char* tool_name = map_variable_tool_name(var_trim);
|
||||
const char* tool_name = map_variable_tool_name(lookup_name);
|
||||
if (tool_name && tool_name[0] != '\0') {
|
||||
char* tool_result = tools_execute(tools_ctx, tool_name, "{}");
|
||||
char* tool_result = tools_execute(tools_ctx, tool_name, call_args_json);
|
||||
if (tool_result) {
|
||||
cJSON* root = cJSON_Parse(tool_result);
|
||||
if (root && cJSON_IsObject(root)) {
|
||||
@@ -189,16 +187,30 @@ static char* resolve_inline_variables_local(const char* tpl, tools_context_t* to
|
||||
free(tool_result);
|
||||
}
|
||||
}
|
||||
|
||||
if (!replacement_owned && tools_ctx->template_skill_lookup && lookup_name[0] != '\0') {
|
||||
const char* skill_content = tools_ctx->template_skill_lookup(
|
||||
tools_ctx->template_skill_lookup_user_data,
|
||||
lookup_name);
|
||||
if (skill_content && skill_content[0] != '\0') {
|
||||
replacement_owned = strdup(skill_content);
|
||||
}
|
||||
}
|
||||
|
||||
replacement = replacement_owned ? replacement_owned : "";
|
||||
}
|
||||
|
||||
if (append_text(&out, &cap, &used, replacement) != 0) {
|
||||
free(call_args_owned);
|
||||
free(call_name_owned);
|
||||
free(replacement_owned);
|
||||
free(var);
|
||||
free(out);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
free(call_args_owned);
|
||||
free(call_name_owned);
|
||||
free(replacement_owned);
|
||||
free(var);
|
||||
p = close + 2;
|
||||
@@ -206,462 +218,3 @@ static char* resolve_inline_variables_local(const char* tpl, tools_context_t* to
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
static void init_section_defaults(prompt_template_section_t* sec) {
|
||||
if (!sec) return;
|
||||
memset(sec->name, 0, sizeof(sec->name));
|
||||
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;
|
||||
sec->provider_content_template = NULL;
|
||||
}
|
||||
|
||||
static int parse_int_or_zero(const char* s) {
|
||||
if (!s) return 0;
|
||||
while (*s && isspace((unsigned char)*s)) s++;
|
||||
return atoi(s);
|
||||
}
|
||||
|
||||
int prompt_template_parse(const char* skill_content, prompt_template_t* out_template) {
|
||||
if (!skill_content || !out_template) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
memset(out_template, 0, sizeof(*out_template));
|
||||
|
||||
const char* marker = strstr(skill_content, PROMPT_TEMPLATE_MARKER);
|
||||
if (!marker) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
size_t personality_len = (size_t)(marker - skill_content);
|
||||
out_template->personality = dup_range(skill_content, personality_len);
|
||||
if (!out_template->personality) {
|
||||
return -1;
|
||||
}
|
||||
rtrim_inplace(out_template->personality);
|
||||
|
||||
const char* after = marker + strlen(PROMPT_TEMPLATE_MARKER);
|
||||
while (*after == '\r' || *after == '\n') after++;
|
||||
|
||||
char* tpl = strdup(after);
|
||||
if (!tpl) {
|
||||
prompt_template_free(out_template);
|
||||
return -1;
|
||||
}
|
||||
|
||||
char** lines = NULL;
|
||||
int line_count = 0;
|
||||
if (split_lines_inplace(tpl, &lines, &line_count) != 0) {
|
||||
free(tpl);
|
||||
prompt_template_free(out_template);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int current = -1;
|
||||
int i = 0;
|
||||
while (i < line_count) {
|
||||
char* raw = lines[i];
|
||||
rtrim_inplace(raw);
|
||||
char* line = ltrim_inplace(raw);
|
||||
|
||||
if (*line == '\0') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (starts_with(line, "- section:")) {
|
||||
if (out_template->section_count >= PROMPT_TEMPLATE_MAX_SECTIONS) {
|
||||
break;
|
||||
}
|
||||
|
||||
current = out_template->section_count;
|
||||
init_section_defaults(&out_template->sections[current]);
|
||||
out_template->section_count++;
|
||||
|
||||
char* name = line + strlen("- section:");
|
||||
name = ltrim_inplace(name);
|
||||
rtrim_inplace(name);
|
||||
snprintf(out_template->sections[current].name,
|
||||
sizeof(out_template->sections[current].name),
|
||||
"%s",
|
||||
name);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current < 0) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (starts_with(line, "role:")) {
|
||||
char* role = line + strlen("role:");
|
||||
role = ltrim_inplace(role);
|
||||
rtrim_inplace(role);
|
||||
snprintf(out_template->sections[current].role,
|
||||
sizeof(out_template->sections[current].role),
|
||||
"%s",
|
||||
(*role) ? role : "system");
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (starts_with(line, "limit:")) {
|
||||
char* lim = line + strlen("limit:");
|
||||
out_template->sections[current].limit = parse_int_or_zero(lim);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (starts_with(line, "skip_if_empty:")) {
|
||||
char* flag = line + strlen("skip_if_empty:");
|
||||
flag = ltrim_inplace(flag);
|
||||
rtrim_inplace(flag);
|
||||
out_template->sections[current].skip_if_empty =
|
||||
(strcmp(flag, "true") == 0 || strcmp(flag, "1") == 0) ? 1 : 0;
|
||||
i++;
|
||||
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);
|
||||
|
||||
free(out_template->sections[current].content_template);
|
||||
out_template->sections[current].content_template = NULL;
|
||||
|
||||
if (strcmp(val, "|") == 0) {
|
||||
char* acc = strdup("");
|
||||
size_t cap = acc ? 1U : 0U;
|
||||
size_t used = 0U;
|
||||
if (!acc) {
|
||||
free(lines);
|
||||
free(tpl);
|
||||
prompt_template_free(out_template);
|
||||
return -1;
|
||||
}
|
||||
|
||||
i++;
|
||||
while (i < line_count) {
|
||||
char* next_raw = lines[i];
|
||||
char* next_ltrim = ltrim_inplace(next_raw);
|
||||
|
||||
if (starts_with(next_ltrim, "- section:") ||
|
||||
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;
|
||||
}
|
||||
|
||||
char* piece = next_raw;
|
||||
if (strncmp(piece, " ", 4) == 0) piece += 4;
|
||||
else if (strncmp(piece, " ", 2) == 0) piece += 2;
|
||||
rtrim_inplace(piece);
|
||||
|
||||
if (append_text(&acc, &cap, &used, piece) != 0 ||
|
||||
append_text(&acc, &cap, &used, "\n") != 0) {
|
||||
free(acc);
|
||||
free(lines);
|
||||
free(tpl);
|
||||
prompt_template_free(out_template);
|
||||
return -1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
rtrim_inplace(acc);
|
||||
out_template->sections[current].content_template = acc;
|
||||
continue;
|
||||
}
|
||||
|
||||
rtrim_inplace(val);
|
||||
out_template->sections[current].content_template = strdup(val);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (starts_with(line, "provider:")) {
|
||||
i++;
|
||||
if (i >= line_count) continue;
|
||||
|
||||
char* provider_line = ltrim_inplace(lines[i]);
|
||||
rtrim_inplace(provider_line);
|
||||
char* colon = strchr(provider_line, ':');
|
||||
if (!colon) {
|
||||
continue;
|
||||
}
|
||||
|
||||
*colon = '\0';
|
||||
char* provider_name = ltrim_inplace(provider_line);
|
||||
rtrim_inplace(provider_name);
|
||||
char* provider_val = ltrim_inplace(colon + 1);
|
||||
rtrim_inplace(provider_val);
|
||||
|
||||
free(out_template->sections[current].provider_name);
|
||||
out_template->sections[current].provider_name = strdup(provider_name);
|
||||
free(out_template->sections[current].provider_content_template);
|
||||
out_template->sections[current].provider_content_template = NULL;
|
||||
|
||||
if (strcmp(provider_val, "|") == 0) {
|
||||
char* acc = strdup("");
|
||||
size_t cap = acc ? 1U : 0U;
|
||||
size_t used = 0U;
|
||||
if (!acc) {
|
||||
free(lines);
|
||||
free(tpl);
|
||||
prompt_template_free(out_template);
|
||||
return -1;
|
||||
}
|
||||
|
||||
i++;
|
||||
while (i < line_count) {
|
||||
char* next = ltrim_inplace(lines[i]);
|
||||
if (starts_with(next, "- section:") ||
|
||||
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;
|
||||
}
|
||||
char* piece = lines[i];
|
||||
if (strncmp(piece, " ", 4) == 0) piece += 4;
|
||||
else if (strncmp(piece, " ", 2) == 0) piece += 2;
|
||||
rtrim_inplace(piece);
|
||||
if (append_text(&acc, &cap, &used, piece) != 0 ||
|
||||
append_text(&acc, &cap, &used, "\n") != 0) {
|
||||
free(acc);
|
||||
free(lines);
|
||||
free(tpl);
|
||||
prompt_template_free(out_template);
|
||||
return -1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
rtrim_inplace(acc);
|
||||
out_template->sections[current].provider_content_template = acc;
|
||||
continue;
|
||||
}
|
||||
|
||||
out_template->sections[current].provider_content_template = strdup(provider_val);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
free(lines);
|
||||
free(tpl);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int append_message_object(cJSON* messages, const char* role, const char* content) {
|
||||
if (!messages || !role) return -1;
|
||||
cJSON* msg = cJSON_CreateObject();
|
||||
if (!msg) return -1;
|
||||
cJSON_AddStringToObject(msg, "role", role);
|
||||
cJSON_AddStringToObject(msg, "content", content ? content : "");
|
||||
cJSON_AddItemToArray(messages, msg);
|
||||
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,
|
||||
tools_context_t* tools_ctx,
|
||||
cJSON* dm_history_messages,
|
||||
int dm_history_default_limit,
|
||||
prompt_template_emit_hook_fn emit_hook,
|
||||
void* emit_hook_user_data) {
|
||||
if (!tmpl) return NULL;
|
||||
|
||||
cJSON* out = cJSON_CreateArray();
|
||||
if (!out) return NULL;
|
||||
|
||||
int out_idx = 0;
|
||||
if (tmpl->personality && tmpl->personality[0] != '\0') {
|
||||
if (append_message_object(out, "system", tmpl->personality) != 0) {
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
if (emit_hook) emit_hook("system_prompt", out_idx, emit_hook_user_data);
|
||||
out_idx++;
|
||||
}
|
||||
|
||||
for (int i = 0; i < tmpl->section_count; i++) {
|
||||
const prompt_template_section_t* sec = &tmpl->sections[i];
|
||||
const char* role = sec->role[0] ? sec->role : "system";
|
||||
|
||||
if (strcmp(role, "expand") == 0) {
|
||||
if (!dm_history_messages || !cJSON_IsArray(dm_history_messages)) {
|
||||
continue;
|
||||
}
|
||||
int total = cJSON_GetArraySize(dm_history_messages);
|
||||
int lim = sec->limit > 0 ? sec->limit : dm_history_default_limit;
|
||||
int start = (lim > 0 && total > lim) ? (total - lim) : 0;
|
||||
|
||||
for (int j = start; j < total; j++) {
|
||||
cJSON* item = cJSON_GetArrayItem(dm_history_messages, j);
|
||||
if (!item || !cJSON_IsObject(item)) continue;
|
||||
cJSON* dup = cJSON_Duplicate(item, 1);
|
||||
if (!dup) {
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddItemToArray(out, dup);
|
||||
if (emit_hook) emit_hook(sec->name[0] ? sec->name : "context_part", out_idx, emit_hook_user_data);
|
||||
out_idx++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
char* resolved = NULL;
|
||||
|
||||
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_inline_variables_local(tpl ? tpl : "", tools_ctx);
|
||||
}
|
||||
if (!resolved) {
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (sec->skip_if_empty) {
|
||||
char* chk = ltrim_inplace(resolved);
|
||||
if (chk && *chk == '\0') {
|
||||
free(resolved);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (append_message_object(out, role, resolved) != 0) {
|
||||
free(resolved);
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
if (emit_hook) emit_hook(sec->name[0] ? sec->name : "context_part", out_idx, emit_hook_user_data);
|
||||
out_idx++;
|
||||
free(resolved);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
void prompt_template_free(prompt_template_t* tmpl) {
|
||||
if (!tmpl) return;
|
||||
|
||||
free(tmpl->personality);
|
||||
tmpl->personality = NULL;
|
||||
|
||||
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);
|
||||
tmpl->sections[i].provider_content_template = NULL;
|
||||
tmpl->sections[i].name[0] = '\0';
|
||||
tmpl->sections[i].role[0] = '\0';
|
||||
tmpl->sections[i].limit = 0;
|
||||
tmpl->sections[i].skip_if_empty = 0;
|
||||
}
|
||||
|
||||
tmpl->section_count = 0;
|
||||
}
|
||||
@@ -1,47 +1,8 @@
|
||||
#ifndef DIDACTYL_PROMPT_TEMPLATE_H
|
||||
#define DIDACTYL_PROMPT_TEMPLATE_H
|
||||
|
||||
#include "cjson/cJSON.h"
|
||||
#include "tools/tools.h"
|
||||
|
||||
#define PROMPT_TEMPLATE_MAX_SECTIONS 32
|
||||
#define PROMPT_TEMPLATE_MAX_NAME_LEN 64
|
||||
#define PROMPT_TEMPLATE_MAX_ROLE_LEN 16
|
||||
#define PROMPT_TEMPLATE_MARKER "---template---"
|
||||
|
||||
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;
|
||||
char* provider_content_template;
|
||||
} prompt_template_section_t;
|
||||
|
||||
typedef struct {
|
||||
char* personality;
|
||||
prompt_template_section_t sections[PROMPT_TEMPLATE_MAX_SECTIONS];
|
||||
int section_count;
|
||||
} prompt_template_t;
|
||||
|
||||
typedef void (*prompt_template_emit_hook_fn)(const char* section_name,
|
||||
int message_index,
|
||||
void* user_data);
|
||||
|
||||
int prompt_template_parse(const char* skill_content, prompt_template_t* out_template);
|
||||
|
||||
cJSON* prompt_template_build_messages(const prompt_template_t* tmpl,
|
||||
const char* provider_name,
|
||||
tools_context_t* tools_ctx,
|
||||
cJSON* dm_history_messages,
|
||||
int dm_history_default_limit,
|
||||
prompt_template_emit_hook_fn emit_hook,
|
||||
void* emit_hook_user_data);
|
||||
|
||||
void prompt_template_free(prompt_template_t* tmpl);
|
||||
char* prompt_template_resolve_inline_variables(const char* tpl, tools_context_t* tools_ctx);
|
||||
|
||||
#endif
|
||||
@@ -372,17 +372,64 @@ static int build_kind10002_tags_json(const didactyl_config_t* cfg, char** out_ta
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int tags_json_get_d_tag_local(const char* tags_json, char* out, size_t out_size) {
|
||||
if (!tags_json || !out || out_size == 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
out[0] = '\0';
|
||||
cJSON* tags = cJSON_Parse(tags_json);
|
||||
if (!tags || !cJSON_IsArray(tags)) {
|
||||
cJSON_Delete(tags);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int n = cJSON_GetArraySize(tags);
|
||||
for (int i = 0; i < n; i++) {
|
||||
cJSON* tag = cJSON_GetArrayItem(tags, i);
|
||||
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) continue;
|
||||
cJSON* k = cJSON_GetArrayItem(tag, 0);
|
||||
cJSON* v = cJSON_GetArrayItem(tag, 1);
|
||||
if (!k || !v || !cJSON_IsString(k) || !cJSON_IsString(v) || !k->valuestring || !v->valuestring) continue;
|
||||
if (strcmp(k->valuestring, "d") == 0 && v->valuestring[0] != '\0') {
|
||||
snprintf(out, out_size, "%s", v->valuestring);
|
||||
cJSON_Delete(tags);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
cJSON_Delete(tags);
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int upsert_startup_event(didactyl_config_t* cfg, int kind, const char* content, const char* tags_json) {
|
||||
if (!cfg || !content || !tags_json) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int is_skill_kind = (kind == 31123 || kind == 31124);
|
||||
char incoming_d[128] = {0};
|
||||
int incoming_has_d = (is_skill_kind && tags_json_get_d_tag_local(tags_json, incoming_d, sizeof(incoming_d)) == 0);
|
||||
|
||||
for (int i = 0; i < cfg->startup_event_count; i++) {
|
||||
startup_event_t* se = &cfg->startup_events[i];
|
||||
if (se->kind != kind) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_skill_kind) {
|
||||
if (!incoming_has_d) {
|
||||
continue;
|
||||
}
|
||||
char existing_d[128] = {0};
|
||||
if (tags_json_get_d_tag_local(se->tags_json, existing_d, sizeof(existing_d)) != 0) {
|
||||
continue;
|
||||
}
|
||||
if (strcmp(existing_d, incoming_d) != 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
char* content_dup = strdup(content);
|
||||
char* tags_dup = strdup(tags_json);
|
||||
if (!content_dup || !tags_dup) {
|
||||
@@ -495,35 +542,22 @@ static int apply_default_startup_events(didactyl_config_t* cfg, const char* agen
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int configure_default_skill_for_agent(didactyl_config_t* cfg, const char* agent_name) {
|
||||
static int configure_default_skills_for_agent(didactyl_config_t* cfg, const char* agent_name) {
|
||||
if (!cfg || !agent_name || agent_name[0] == '\0') {
|
||||
return -1;
|
||||
}
|
||||
|
||||
free(cfg->default_skill.content);
|
||||
cfg->default_skill.content = NULL;
|
||||
free(cfg->default_skill.tags_json);
|
||||
cfg->default_skill.tags_json = NULL;
|
||||
|
||||
cfg->default_skill.kind = DIDACTYL_DEFAULT_SKILL_KIND;
|
||||
snprintf(cfg->default_skill.d_tag, sizeof(cfg->default_skill.d_tag), "%s", DIDACTYL_DEFAULT_SKILL_D_TAG);
|
||||
|
||||
int needed = snprintf(NULL, 0, DIDACTYL_DEFAULT_SKILL_TEMPLATE, agent_name, agent_name);
|
||||
if (needed <= 0) {
|
||||
if (upsert_startup_event(cfg,
|
||||
DIDACTYL_DEFAULT_SKILL_KIND,
|
||||
DIDACTYL_DEFAULT_SKILL_TEMPLATE,
|
||||
DIDACTYL_DEFAULT_SKILL_TAGS_JSON) != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
cfg->default_skill.content = (char*)malloc((size_t)needed + 1U);
|
||||
if (!cfg->default_skill.content) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
snprintf(cfg->default_skill.content, (size_t)needed + 1U, DIDACTYL_DEFAULT_SKILL_TEMPLATE, agent_name, agent_name);
|
||||
|
||||
cfg->default_skill.tags_json = strdup(DIDACTYL_DEFAULT_SKILL_TAGS_JSON);
|
||||
if (!cfg->default_skill.tags_json) {
|
||||
free(cfg->default_skill.content);
|
||||
cfg->default_skill.content = NULL;
|
||||
if (upsert_startup_event(cfg,
|
||||
DIDACTYL_DEFAULT_DM_HISTORY_SKILL_KIND,
|
||||
DIDACTYL_DEFAULT_DM_HISTORY_SKILL_TEMPLATE,
|
||||
DIDACTYL_DEFAULT_DM_HISTORY_SKILL_TAGS_JSON) != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -2157,8 +2191,8 @@ static int new_agent_flow(didactyl_config_t* cfg, char* genesis_path_out, size_t
|
||||
if (prompt_llm_config(cfg) != 0) return -1;
|
||||
}
|
||||
|
||||
if (configure_default_skill_for_agent(cfg, agent_name) != 0) {
|
||||
fprintf(stderr, "%sFailed to prepare default skill event content.%s\n", ANSI_RED, ANSI_RESET);
|
||||
if (configure_default_skills_for_agent(cfg, agent_name) != 0) {
|
||||
fprintf(stderr, "%sFailed to prepare default startup skill events.%s\n", ANSI_RED, ANSI_RESET);
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
@@ -48,15 +48,23 @@ char* execute_admin_identity(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
char content[768];
|
||||
snprintf(content,
|
||||
sizeof(content),
|
||||
"## Administrator Identity (source: config.admin.pubkey)\n\n"
|
||||
"This is your administrator! Admin pubkey (hex): %s\n\n"
|
||||
"%s",
|
||||
ctx->cfg->admin.pubkey[0] ? ctx->cfg->admin.pubkey : "unknown",
|
||||
tier_text);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
cJSON* identity = cJSON_CreateObject();
|
||||
if (!identity) {
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddStringToObject(identity,
|
||||
"admin_pubkey",
|
||||
ctx->cfg->admin.pubkey[0] ? ctx->cfg->admin.pubkey : "unknown");
|
||||
cJSON_AddStringToObject(identity, "sender_tier", tier_text);
|
||||
char* identity_json = cJSON_PrintUnformatted(identity);
|
||||
cJSON_Delete(identity);
|
||||
if (!identity_json) {
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddStringToObject(out, "content", identity_json);
|
||||
free(identity_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -81,19 +89,7 @@ char* execute_nostr_admin_profile(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Administrator Kind 0 Profile (source: nostr kind 0)\n\nAdministrator kind 0 profile content (JSON): ") + strlen(profile_json) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(kind0);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Administrator Kind 0 Profile (source: nostr kind 0)\n\nAdministrator kind 0 profile content (JSON): %s",
|
||||
profile_json);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", profile_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -119,19 +115,7 @@ char* execute_nostr_admin_contacts(tools_context_t* ctx, const char* args_json)
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Administrator Kind 3 Contacts (source: nostr kind 3)\n\nAdministrator contacts (JSON): ") + strlen(contacts_json) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(kind3);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Administrator Kind 3 Contacts (source: nostr kind 3)\n\nAdministrator contacts (JSON): %s",
|
||||
contacts_json);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", contacts_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -157,19 +141,7 @@ char* execute_nostr_admin_relays(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Administrator Kind 10002 Relays (source: nostr kind 10002)\n\nAdministrator relay list (JSON): ") + strlen(relays_json) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(kind10002);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Administrator Kind 10002 Relays (source: nostr kind 10002)\n\nAdministrator relay list (JSON): %s",
|
||||
relays_json);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", relays_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -195,19 +167,7 @@ char* execute_nostr_admin_notes(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Administrator Recent Kind 1 Notes\n\n") + strlen(notes_text) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(notes);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Administrator Recent Kind 1 Notes\n\n%s",
|
||||
notes_text);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", notes_text);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
|
||||
@@ -31,6 +31,25 @@ static cJSON* parse_args_local(const char* args_json) {
|
||||
return args;
|
||||
}
|
||||
|
||||
static int append_text_local(char** buf, size_t* cap, size_t* used, const char* s) {
|
||||
if (!buf || !cap || !used || !s) return -1;
|
||||
size_t n = strlen(s);
|
||||
if (*used + n + 1U > *cap) {
|
||||
size_t next = *cap;
|
||||
while (*used + n + 1U > next) {
|
||||
next = (next == 0U) ? 256U : (next * 2U);
|
||||
}
|
||||
char* grown = (char*)realloc(*buf, next);
|
||||
if (!grown) return -1;
|
||||
*buf = grown;
|
||||
*cap = next;
|
||||
}
|
||||
memcpy(*buf + *used, s, n);
|
||||
*used += n;
|
||||
(*buf)[*used] = '\0';
|
||||
return 0;
|
||||
}
|
||||
|
||||
char* execute_message_current(tools_context_t* ctx, const char* args_json) {
|
||||
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
|
||||
|
||||
@@ -63,13 +82,23 @@ char* execute_agent_identity(tools_context_t* ctx, const char* args_json) {
|
||||
if (!out) return NULL;
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
char content[384];
|
||||
snprintf(content,
|
||||
sizeof(content),
|
||||
"## Agent Identity\n\nYour pubkey (hex): %s\nYour npub: %s",
|
||||
ctx->cfg->keys.public_key_hex[0] ? ctx->cfg->keys.public_key_hex : "unknown",
|
||||
npub);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
cJSON* identity = cJSON_CreateObject();
|
||||
if (!identity) {
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddStringToObject(identity,
|
||||
"pubkey",
|
||||
ctx->cfg->keys.public_key_hex[0] ? ctx->cfg->keys.public_key_hex : "unknown");
|
||||
cJSON_AddStringToObject(identity, "npub", npub);
|
||||
char* identity_json = cJSON_PrintUnformatted(identity);
|
||||
cJSON_Delete(identity);
|
||||
if (!identity_json) {
|
||||
cJSON_Delete(out);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddStringToObject(out, "content", identity_json);
|
||||
free(identity_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -94,19 +123,7 @@ char* execute_nostr_agent_profile(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Agent Kind 0 Profile (source: nostr kind 0)\n\nAgent kind 0 profile content (JSON): ") + strlen(profile_json) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(kind0);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Agent Kind 0 Profile (source: nostr kind 0)\n\nAgent kind 0 profile content (JSON): %s",
|
||||
profile_json);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", profile_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -132,19 +149,7 @@ char* execute_nostr_agent_contacts(tools_context_t* ctx, const char* args_json)
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Agent Kind 3 Contacts (source: nostr kind 3)\n\nAgent contacts (JSON): ") + strlen(contacts_json) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(kind3);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Agent Kind 3 Contacts (source: nostr kind 3)\n\nAgent contacts (JSON): %s",
|
||||
contacts_json);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", contacts_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -170,19 +175,7 @@ char* execute_nostr_agent_relays(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Agent Kind 10002 Relays (source: nostr kind 10002)\n\nAgent relay list (JSON): ") + strlen(relays_json) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(kind10002);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Agent Kind 10002 Relays (source: nostr kind 10002)\n\nAgent relay list (JSON): %s",
|
||||
relays_json);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", relays_json);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -208,19 +201,7 @@ char* execute_nostr_agent_notes(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
|
||||
size_t content_len = strlen("## Agent Recent Kind 1 Notes\n\n") + strlen(notes_text) + 1U;
|
||||
char* content = (char*)malloc(content_len);
|
||||
if (!content) {
|
||||
cJSON_Delete(out);
|
||||
free(notes);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(content,
|
||||
content_len,
|
||||
"## Agent Recent Kind 1 Notes\n\n%s",
|
||||
notes_text);
|
||||
cJSON_AddStringToObject(out, "content", content);
|
||||
free(content);
|
||||
cJSON_AddStringToObject(out, "content", notes_text);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -300,6 +281,172 @@ char* execute_trigger_event(tools_context_t* ctx, const char* args_json) {
|
||||
return json;
|
||||
}
|
||||
|
||||
char* execute_nostr_dm_history(tools_context_t* ctx, const char* args_json) {
|
||||
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
|
||||
|
||||
cJSON* args = parse_args_local(args_json);
|
||||
if (!args) return json_error_local("invalid arguments JSON");
|
||||
|
||||
int limit = 12;
|
||||
cJSON* limit_j = cJSON_GetObjectItemCaseSensitive(args, "limit");
|
||||
if (limit_j && cJSON_IsNumber(limit_j)) {
|
||||
limit = (int)limit_j->valuedouble;
|
||||
}
|
||||
if (limit < 1) limit = 1;
|
||||
if (limit > 200) limit = 200;
|
||||
|
||||
int include_current = 0;
|
||||
cJSON* include_current_j = cJSON_GetObjectItemCaseSensitive(args, "include_current");
|
||||
if (include_current_j && cJSON_IsBool(include_current_j) && cJSON_IsTrue(include_current_j)) {
|
||||
include_current = 1;
|
||||
}
|
||||
|
||||
int format_text = 0;
|
||||
cJSON* format_j = cJSON_GetObjectItemCaseSensitive(args, "format");
|
||||
if (format_j && cJSON_IsString(format_j) && format_j->valuestring) {
|
||||
if (strcmp(format_j->valuestring, "text") == 0) {
|
||||
format_text = 1;
|
||||
}
|
||||
}
|
||||
|
||||
const char* peer_pubkey = ctx->cfg->admin.pubkey;
|
||||
cJSON* peer_j = cJSON_GetObjectItemCaseSensitive(args, "peer_pubkey");
|
||||
if (peer_j && cJSON_IsString(peer_j) && peer_j->valuestring && peer_j->valuestring[0] != '\0') {
|
||||
peer_pubkey = peer_j->valuestring;
|
||||
}
|
||||
|
||||
char* history_json = nostr_handler_get_dm_history_json(peer_pubkey, limit);
|
||||
cJSON_Delete(args);
|
||||
if (!history_json) {
|
||||
return json_error_local("failed to fetch dm history");
|
||||
}
|
||||
|
||||
cJSON* parsed = cJSON_Parse(history_json);
|
||||
free(history_json);
|
||||
if (!parsed || !cJSON_IsArray(parsed)) {
|
||||
cJSON_Delete(parsed);
|
||||
parsed = cJSON_CreateArray();
|
||||
if (!parsed) {
|
||||
return json_error_local("failed to build dm history response");
|
||||
}
|
||||
}
|
||||
|
||||
cJSON* filtered = cJSON_CreateArray();
|
||||
if (!filtered) {
|
||||
cJSON_Delete(parsed);
|
||||
return json_error_local("failed to build dm history response");
|
||||
}
|
||||
|
||||
const char* current_message = (!include_current && ctx->template_current_user_message)
|
||||
? ctx->template_current_user_message
|
||||
: NULL;
|
||||
|
||||
const char* last_role = NULL;
|
||||
const char* last_content = NULL;
|
||||
|
||||
int n = cJSON_GetArraySize(parsed);
|
||||
for (int i = 0; i < n; i++) {
|
||||
cJSON* item = cJSON_GetArrayItem(parsed, 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_role && last_content && strcmp(last_role, role_s) == 0 && strcmp(last_content, content_s) == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON* out_item = cJSON_CreateObject();
|
||||
if (!out_item) {
|
||||
continue;
|
||||
}
|
||||
cJSON_AddStringToObject(out_item, "role", role_s);
|
||||
cJSON_AddStringToObject(out_item, "content", content_s);
|
||||
if (created_at && cJSON_IsNumber(created_at)) {
|
||||
cJSON_AddNumberToObject(out_item, "created_at", created_at->valuedouble);
|
||||
}
|
||||
cJSON_AddItemToArray(filtered, out_item);
|
||||
|
||||
last_role = role_s;
|
||||
last_content = content_s;
|
||||
}
|
||||
|
||||
cJSON_Delete(parsed);
|
||||
|
||||
char* rendered = NULL;
|
||||
|
||||
if (format_text) {
|
||||
size_t cap = 256U;
|
||||
size_t used = 0U;
|
||||
rendered = (char*)malloc(cap);
|
||||
if (!rendered) {
|
||||
cJSON_Delete(filtered);
|
||||
return json_error_local("failed to serialize dm history");
|
||||
}
|
||||
rendered[0] = '\0';
|
||||
|
||||
int m = cJSON_GetArraySize(filtered);
|
||||
for (int i = 0; i < m; i++) {
|
||||
cJSON* item = cJSON_GetArrayItem(filtered, i);
|
||||
cJSON* role = item ? cJSON_GetObjectItemCaseSensitive(item, "role") : NULL;
|
||||
cJSON* content = item ? cJSON_GetObjectItemCaseSensitive(item, "content") : NULL;
|
||||
if (!role || !content || !cJSON_IsString(role) || !cJSON_IsString(content) ||
|
||||
!role->valuestring || !content->valuestring) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const char* prefix = (strcmp(role->valuestring, "user") == 0) ? "User: " : "Assistant: ";
|
||||
if (append_text_local(&rendered, &cap, &used, prefix) != 0 ||
|
||||
append_text_local(&rendered, &cap, &used, content->valuestring) != 0 ||
|
||||
append_text_local(&rendered, &cap, &used, "\n") != 0) {
|
||||
free(rendered);
|
||||
cJSON_Delete(filtered);
|
||||
return json_error_local("failed to serialize dm history");
|
||||
}
|
||||
}
|
||||
|
||||
if (used > 0U && rendered[used - 1] == '\n') {
|
||||
rendered[used - 1] = '\0';
|
||||
}
|
||||
} else {
|
||||
rendered = cJSON_PrintUnformatted(filtered);
|
||||
if (!rendered) {
|
||||
cJSON_Delete(filtered);
|
||||
return json_error_local("failed to serialize dm history");
|
||||
}
|
||||
}
|
||||
|
||||
cJSON_Delete(filtered);
|
||||
|
||||
cJSON* out = cJSON_CreateObject();
|
||||
if (!out) {
|
||||
free(rendered);
|
||||
return NULL;
|
||||
}
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
cJSON_AddStringToObject(out, "content", rendered);
|
||||
free(rendered);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
return json;
|
||||
}
|
||||
|
||||
char* execute_agent_version(const char* args_json) {
|
||||
cJSON* args = parse_args_local(args_json);
|
||||
if (!args) return json_error_local("invalid arguments JSON");
|
||||
|
||||
@@ -227,6 +227,7 @@ char* execute_nostr_pubkey(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
cJSON_AddStringToObject(out, "pubkey", ctx->cfg->keys.public_key_hex);
|
||||
cJSON_AddStringToObject(out, "content", ctx->cfg->keys.public_key_hex);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
@@ -250,6 +251,7 @@ char* execute_nostr_npub(tools_context_t* ctx, const char* args_json) {
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
cJSON_AddStringToObject(out, "npub", npub);
|
||||
cJSON_AddStringToObject(out, "content", npub);
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
|
||||
@@ -908,6 +908,315 @@ char* execute_skill_list(tools_context_t* ctx, const char* args_json) {
|
||||
return json;
|
||||
}
|
||||
|
||||
char* execute_skill_get(tools_context_t* ctx, const char* args_json) {
|
||||
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
|
||||
|
||||
cJSON* args = parse_args_local(args_json);
|
||||
if (!args) return json_error_local("invalid arguments JSON");
|
||||
|
||||
cJSON* d_tag = cJSON_GetObjectItemCaseSensitive(args, "d");
|
||||
cJSON* input = cJSON_GetObjectItemCaseSensitive(args, "input");
|
||||
const char* d_tag_value = NULL;
|
||||
if (d_tag && cJSON_IsString(d_tag) && d_tag->valuestring && validate_skill_d_tag_local(d_tag->valuestring)) {
|
||||
d_tag_value = d_tag->valuestring;
|
||||
} else if (input && cJSON_IsString(input) && input->valuestring && validate_skill_d_tag_local(input->valuestring)) {
|
||||
d_tag_value = input->valuestring;
|
||||
}
|
||||
if (!d_tag_value) {
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_get requires valid d tag");
|
||||
}
|
||||
|
||||
char* events_json = nostr_handler_get_self_skill_events_json();
|
||||
if (!events_json) {
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_get cache unavailable");
|
||||
}
|
||||
|
||||
cJSON* events = cJSON_Parse(events_json);
|
||||
free(events_json);
|
||||
if (!events || !cJSON_IsArray(events)) {
|
||||
cJSON_Delete(args);
|
||||
cJSON_Delete(events);
|
||||
return json_error_local("skill_get cache returned invalid JSON");
|
||||
}
|
||||
|
||||
cJSON* target = NULL;
|
||||
long long best_created_at = -1;
|
||||
int event_count = cJSON_GetArraySize(events);
|
||||
for (int i = 0; i < event_count; i++) {
|
||||
cJSON* ev = cJSON_GetArrayItem(events, i);
|
||||
if (!ev || !cJSON_IsObject(ev)) continue;
|
||||
|
||||
cJSON* kind = cJSON_GetObjectItemCaseSensitive(ev, "kind");
|
||||
cJSON* tags = cJSON_GetObjectItemCaseSensitive(ev, "tags");
|
||||
if (!kind || !cJSON_IsNumber(kind) || !tags || !cJSON_IsArray(tags)) continue;
|
||||
|
||||
int kind_val = (int)kind->valuedouble;
|
||||
if (kind_val != 31123 && kind_val != 31124) continue;
|
||||
|
||||
cJSON* d_val = find_tag_value_string_local(tags, "d");
|
||||
if (!d_val || !cJSON_IsString(d_val) || !d_val->valuestring) continue;
|
||||
if (strcmp(d_val->valuestring, d_tag_value) != 0) continue;
|
||||
|
||||
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(ev, "created_at");
|
||||
long long created = (created_at && cJSON_IsNumber(created_at)) ? (long long)created_at->valuedouble : 0;
|
||||
if (!target || created > best_created_at) {
|
||||
target = ev;
|
||||
best_created_at = created;
|
||||
}
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
cJSON_Delete(args);
|
||||
cJSON_Delete(events);
|
||||
return json_error_local("skill_get could not find skill with that d");
|
||||
}
|
||||
|
||||
cJSON* kind = cJSON_GetObjectItemCaseSensitive(target, "kind");
|
||||
cJSON* pubkey = cJSON_GetObjectItemCaseSensitive(target, "pubkey");
|
||||
cJSON* id = cJSON_GetObjectItemCaseSensitive(target, "id");
|
||||
cJSON* created_at = cJSON_GetObjectItemCaseSensitive(target, "created_at");
|
||||
cJSON* content = cJSON_GetObjectItemCaseSensitive(target, "content");
|
||||
cJSON* tags = cJSON_GetObjectItemCaseSensitive(target, "tags");
|
||||
|
||||
if (!kind || !cJSON_IsNumber(kind) || !pubkey || !cJSON_IsString(pubkey) || !pubkey->valuestring ||
|
||||
!content || !cJSON_IsString(content) || !content->valuestring || !tags || !cJSON_IsArray(tags)) {
|
||||
cJSON_Delete(args);
|
||||
cJSON_Delete(events);
|
||||
return json_error_local("skill_get found malformed skill event");
|
||||
}
|
||||
|
||||
int kind_val = (int)kind->valuedouble;
|
||||
cJSON* scope = find_tag_value_string_local(tags, "scope");
|
||||
|
||||
cJSON* out = cJSON_CreateObject();
|
||||
if (!out) {
|
||||
cJSON_Delete(args);
|
||||
cJSON_Delete(events);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", 1);
|
||||
cJSON_AddStringToObject(out, "d_tag", d_tag_value);
|
||||
cJSON_AddNumberToObject(out, "kind", kind_val);
|
||||
cJSON_AddStringToObject(out,
|
||||
"scope",
|
||||
(scope && cJSON_IsString(scope) && scope->valuestring)
|
||||
? scope->valuestring
|
||||
: (kind_val == 31124 ? "private" : "public"));
|
||||
cJSON_AddStringToObject(out, "owner", skill_owner_label_local(ctx->cfg, pubkey->valuestring));
|
||||
if (id && cJSON_IsString(id) && id->valuestring) {
|
||||
cJSON_AddStringToObject(out, "id", id->valuestring);
|
||||
}
|
||||
if (created_at && cJSON_IsNumber(created_at)) {
|
||||
char ts_buf[32];
|
||||
snprintf(ts_buf, sizeof(ts_buf), "%lld", (long long)created_at->valuedouble);
|
||||
cJSON* ts_raw = cJSON_CreateRaw(ts_buf);
|
||||
if (ts_raw) {
|
||||
cJSON_AddItemToObject(out, "created_at", ts_raw);
|
||||
}
|
||||
}
|
||||
cJSON_AddStringToObject(out, "content", content->valuestring);
|
||||
cJSON* tags_dup = cJSON_Duplicate(tags, 1);
|
||||
if (tags_dup) {
|
||||
cJSON_AddItemToObject(out, "tags", tags_dup);
|
||||
}
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
cJSON_Delete(args);
|
||||
cJSON_Delete(events);
|
||||
return json;
|
||||
}
|
||||
|
||||
char* execute_skill_view(tools_context_t* ctx, const char* args_json) {
|
||||
return execute_skill_get(ctx, args_json);
|
||||
}
|
||||
|
||||
char* execute_skill_set(tools_context_t* ctx, const char* args_json) {
|
||||
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
|
||||
|
||||
cJSON* args = parse_args_local(args_json);
|
||||
if (!args) return json_error_local("invalid arguments JSON");
|
||||
|
||||
cJSON* skill = cJSON_GetObjectItemCaseSensitive(args, "skill");
|
||||
cJSON* input = cJSON_GetObjectItemCaseSensitive(args, "input");
|
||||
|
||||
cJSON* parsed_input = NULL;
|
||||
cJSON* src = NULL;
|
||||
if (skill && cJSON_IsObject(skill)) {
|
||||
src = skill;
|
||||
} else if (input && cJSON_IsString(input) && input->valuestring && input->valuestring[0] != '\0') {
|
||||
parsed_input = cJSON_Parse(input->valuestring);
|
||||
if (parsed_input && cJSON_IsObject(parsed_input)) {
|
||||
src = parsed_input;
|
||||
}
|
||||
} else if (cJSON_IsObject(args)) {
|
||||
src = args;
|
||||
}
|
||||
|
||||
if (!src || !cJSON_IsObject(src)) {
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_set requires a skill object");
|
||||
}
|
||||
|
||||
cJSON* d = cJSON_GetObjectItemCaseSensitive(src, "d");
|
||||
cJSON* kind = cJSON_GetObjectItemCaseSensitive(src, "kind");
|
||||
cJSON* content = cJSON_GetObjectItemCaseSensitive(src, "content");
|
||||
cJSON* tags = cJSON_GetObjectItemCaseSensitive(src, "tags");
|
||||
cJSON* scope = cJSON_GetObjectItemCaseSensitive(src, "scope");
|
||||
|
||||
if (!d || !cJSON_IsString(d) || !d->valuestring || !validate_skill_d_tag_local(d->valuestring)) {
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_set requires valid d");
|
||||
}
|
||||
if (!content || !cJSON_IsString(content) || !content->valuestring) {
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_set requires string content");
|
||||
}
|
||||
if (!tags || !cJSON_IsArray(tags)) {
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_set requires tags array");
|
||||
}
|
||||
|
||||
int out_kind = 0;
|
||||
if (kind && cJSON_IsNumber(kind)) {
|
||||
out_kind = (int)kind->valuedouble;
|
||||
} else if (scope && cJSON_IsString(scope) && scope->valuestring) {
|
||||
out_kind = (strcmp(scope->valuestring, "private") == 0) ? 31124 : 31123;
|
||||
} else {
|
||||
cJSON* scope_tag = find_tag_value_string_local(tags, "scope");
|
||||
out_kind = (scope_tag && cJSON_IsString(scope_tag) && scope_tag->valuestring && strcmp(scope_tag->valuestring, "private") == 0)
|
||||
? 31124
|
||||
: 31123;
|
||||
}
|
||||
if (out_kind != 31123 && out_kind != 31124) {
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_set kind must be 31123 or 31124");
|
||||
}
|
||||
|
||||
cJSON* tags_out = cJSON_Duplicate(tags, 1);
|
||||
if (!tags_out || !cJSON_IsArray(tags_out)) {
|
||||
cJSON_Delete(tags_out);
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_set failed to duplicate tags");
|
||||
}
|
||||
|
||||
if (upsert_string_tag_local(tags_out, "d", d->valuestring) != 0 ||
|
||||
upsert_string_tag_local(tags_out, "app", "didactyl") != 0 ||
|
||||
upsert_string_tag_local(tags_out, "scope", out_kind == 31124 ? "private" : "public") != 0) {
|
||||
cJSON_Delete(tags_out);
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
return json_error_local("skill_set failed to normalize required tags");
|
||||
}
|
||||
|
||||
nostr_publish_result_t publish_result;
|
||||
memset(&publish_result, 0, sizeof(publish_result));
|
||||
int rc = nostr_handler_publish_kind_event(out_kind, content->valuestring, tags_out, &publish_result);
|
||||
|
||||
int trigger_registered = 0;
|
||||
if (rc == 0 && ctx->trigger_manager) {
|
||||
cJSON* trigger = find_tag_value_string_local(tags_out, "trigger");
|
||||
cJSON* filter = find_tag_value_string_local(tags_out, "filter");
|
||||
cJSON* enabled = find_tag_value_string_local(tags_out, "enabled");
|
||||
cJSON* llm = find_tag_value_string_local(tags_out, "llm");
|
||||
cJSON* tools = find_tag_value_string_local(tags_out, "tools");
|
||||
cJSON* max_tokens = find_tag_value_string_local(tags_out, "max_tokens");
|
||||
cJSON* temperature = find_tag_value_string_local(tags_out, "temperature");
|
||||
cJSON* seed = find_tag_value_string_local(tags_out, "seed");
|
||||
|
||||
int enabled_i = !(enabled && cJSON_IsString(enabled) && enabled->valuestring && strcmp(enabled->valuestring, "false") == 0);
|
||||
const char* trigger_s = (trigger && cJSON_IsString(trigger) && trigger->valuestring) ? trigger->valuestring : NULL;
|
||||
const char* filter_s = (filter && cJSON_IsString(filter) && filter->valuestring) ? filter->valuestring : NULL;
|
||||
|
||||
if (trigger_s && filter_s && enabled_i) {
|
||||
int max_tokens_set = (max_tokens && cJSON_IsString(max_tokens) && max_tokens->valuestring && max_tokens->valuestring[0] != '\0') ? 1 : 0;
|
||||
int max_tokens_v = max_tokens_set ? atoi(max_tokens->valuestring) : 0;
|
||||
int temperature_set = (temperature && cJSON_IsString(temperature) && temperature->valuestring && temperature->valuestring[0] != '\0') ? 1 : 0;
|
||||
double temperature_v = temperature_set ? atof(temperature->valuestring) : 0.0;
|
||||
int seed_set = (seed && cJSON_IsString(seed) && seed->valuestring && seed->valuestring[0] != '\0') ? 1 : 0;
|
||||
int seed_v = seed_set ? atoi(seed->valuestring) : 0;
|
||||
|
||||
if (trigger_manager_update(ctx->trigger_manager,
|
||||
d->valuestring,
|
||||
content->valuestring,
|
||||
filter_s,
|
||||
TRIGGER_ACTION_LLM,
|
||||
trigger_s,
|
||||
enabled_i,
|
||||
(llm && cJSON_IsString(llm) && llm->valuestring) ? llm->valuestring : NULL,
|
||||
(tools && cJSON_IsString(tools) && tools->valuestring) ? tools->valuestring : NULL,
|
||||
max_tokens_set,
|
||||
max_tokens_v,
|
||||
temperature_set,
|
||||
temperature_v,
|
||||
seed_set,
|
||||
seed_v) == 0 ||
|
||||
trigger_manager_add(ctx->trigger_manager,
|
||||
d->valuestring,
|
||||
content->valuestring,
|
||||
filter_s,
|
||||
TRIGGER_ACTION_LLM,
|
||||
trigger_s,
|
||||
enabled_i,
|
||||
(llm && cJSON_IsString(llm) && llm->valuestring) ? llm->valuestring : NULL,
|
||||
(tools && cJSON_IsString(tools) && tools->valuestring) ? tools->valuestring : NULL,
|
||||
max_tokens_set,
|
||||
max_tokens_v,
|
||||
temperature_set,
|
||||
temperature_v,
|
||||
seed_set,
|
||||
seed_v) == 0) {
|
||||
trigger_registered = 1;
|
||||
}
|
||||
} else {
|
||||
(void)trigger_manager_remove(ctx->trigger_manager, d->valuestring);
|
||||
}
|
||||
}
|
||||
|
||||
cJSON_Delete(tags_out);
|
||||
|
||||
if (rc != 0) {
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
nostr_handler_publish_result_free(&publish_result);
|
||||
return json_error_local("skill_set failed to publish skill event");
|
||||
}
|
||||
|
||||
cJSON* out = cJSON_CreateObject();
|
||||
if (!out) {
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
nostr_handler_publish_result_free(&publish_result);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
cJSON_AddBoolToObject(out, "success", publish_result.success ? 1 : 0);
|
||||
cJSON_AddStringToObject(out, "d_tag", d->valuestring);
|
||||
cJSON_AddNumberToObject(out, "kind", out_kind);
|
||||
cJSON_AddStringToObject(out, "scope", out_kind == 31124 ? "private" : "public");
|
||||
cJSON_AddStringToObject(out, "skill_event_id", publish_result.event_id);
|
||||
cJSON_AddBoolToObject(out, "trigger_registered", trigger_registered ? 1 : 0);
|
||||
if (publish_result.naddr_uri[0] != '\0') {
|
||||
cJSON_AddStringToObject(out, "naddr_uri", publish_result.naddr_uri);
|
||||
}
|
||||
|
||||
char* json = cJSON_PrintUnformatted(out);
|
||||
cJSON_Delete(out);
|
||||
cJSON_Delete(parsed_input);
|
||||
cJSON_Delete(args);
|
||||
nostr_handler_publish_result_free(&publish_result);
|
||||
return json;
|
||||
}
|
||||
|
||||
char* execute_skill_adopt(tools_context_t* ctx, const char* args_json) {
|
||||
if (!ctx || !ctx->cfg) return json_error_local("tool context unavailable");
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ typedef struct {
|
||||
int template_sender_tier;
|
||||
const char* template_current_user_message;
|
||||
const char* template_trigger_event_json;
|
||||
const char* (*template_skill_lookup)(void* user_data, const char* d_tag);
|
||||
void* template_skill_lookup_user_data;
|
||||
} tools_context_t;
|
||||
|
||||
int tools_init(tools_context_t* ctx, didactyl_config_t* cfg);
|
||||
|
||||
@@ -25,6 +25,8 @@ int tools_init_legacy(tools_context_t* ctx, didactyl_config_t* cfg) {
|
||||
ctx->template_sender_tier = 0;
|
||||
ctx->template_current_user_message = NULL;
|
||||
ctx->template_trigger_event_json = NULL;
|
||||
ctx->template_skill_lookup = NULL;
|
||||
ctx->template_skill_lookup_user_data = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -129,6 +131,15 @@ char* tools_execute_legacy(tools_context_t* ctx, const char* tool_name, const ch
|
||||
if (strcmp(tool_name, "skill_list") == 0) {
|
||||
return execute_skill_list(ctx, args_json);
|
||||
}
|
||||
if (strcmp(tool_name, "skill_get") == 0) {
|
||||
return execute_skill_get(ctx, args_json);
|
||||
}
|
||||
if (strcmp(tool_name, "skill_view") == 0) {
|
||||
return execute_skill_get(ctx, args_json);
|
||||
}
|
||||
if (strcmp(tool_name, "skill_set") == 0) {
|
||||
return execute_skill_set(ctx, args_json);
|
||||
}
|
||||
if (strcmp(tool_name, "skill_adopt") == 0) {
|
||||
return execute_skill_adopt(ctx, args_json);
|
||||
}
|
||||
@@ -238,6 +249,9 @@ char* tools_execute_legacy(tools_context_t* ctx, const char* tool_name, const ch
|
||||
if (strcmp(tool_name, "trigger_event") == 0) {
|
||||
return execute_trigger_event(ctx, args_json);
|
||||
}
|
||||
if (strcmp(tool_name, "nostr_dm_history") == 0) {
|
||||
return execute_nostr_dm_history(ctx, args_json);
|
||||
}
|
||||
if (strcmp(tool_name, "cashu_wallet_balance") == 0) {
|
||||
return execute_cashu_wallet_balance(ctx, args_json);
|
||||
}
|
||||
|
||||
@@ -57,6 +57,9 @@ char* execute_nostr_post_readme(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_nostr_file_md_to_longform_post(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_create(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_list(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_get(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_view(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_set(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_adopt(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_remove(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_skill_edit(tools_context_t* ctx, const char* args_json);
|
||||
@@ -70,6 +73,7 @@ char* execute_config_store(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_config_recall(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_adopted_skills(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_trigger_event(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_nostr_dm_history(tools_context_t* ctx, const char* args_json);
|
||||
|
||||
char* execute_cashu_wallet_balance(tools_context_t* ctx, const char* args_json);
|
||||
char* execute_cashu_wallet_info(tools_context_t* ctx, const char* args_json);
|
||||
|
||||
@@ -843,6 +843,89 @@ char* tools_build_openai_schema_json_legacy(const tools_context_t* ctx) {
|
||||
cJSON_AddItemToObject(t23, "function", t23_fn);
|
||||
cJSON_AddItemToArray(tools, t23);
|
||||
|
||||
cJSON* t24a = cJSON_CreateObject();
|
||||
cJSON* t24a_fn = cJSON_CreateObject();
|
||||
cJSON* t24a_params = cJSON_CreateObject();
|
||||
cJSON* t24a_props = cJSON_CreateObject();
|
||||
cJSON* t24a_required = cJSON_CreateArray();
|
||||
|
||||
cJSON_AddStringToObject(t24a, "type", "function");
|
||||
cJSON_AddStringToObject(t24a_fn, "name", "skill_get");
|
||||
cJSON_AddStringToObject(t24a_fn, "description", "Get full skill JSON by d tag from local cache; JSON: {\"d\":\"identity_and_rules\"} (slash shorthand also works: /skill_get identity_and_rules)");
|
||||
cJSON_AddStringToObject(t24a_params, "type", "object");
|
||||
cJSON_AddItemToObject(t24a_params, "properties", t24a_props);
|
||||
cJSON_AddItemToObject(t24a_params, "required", t24a_required);
|
||||
|
||||
cJSON* p_skill_get_d = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_skill_get_d, "type", "string");
|
||||
cJSON_AddStringToObject(p_skill_get_d, "description", "Skill d tag (preferred JSON key)");
|
||||
cJSON_AddItemToObject(t24a_props, "d", p_skill_get_d);
|
||||
|
||||
cJSON* p_skill_get_input = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_skill_get_input, "type", "string");
|
||||
cJSON_AddStringToObject(p_skill_get_input, "description", "Slash shorthand fallback key when args are passed as plain text");
|
||||
cJSON_AddItemToObject(t24a_props, "input", p_skill_get_input);
|
||||
|
||||
cJSON_AddItemToArray(t24a_required, cJSON_CreateString("d"));
|
||||
|
||||
cJSON_AddItemToObject(t24a_fn, "parameters", t24a_params);
|
||||
cJSON_AddItemToObject(t24a, "function", t24a_fn);
|
||||
cJSON_AddItemToArray(tools, t24a);
|
||||
|
||||
cJSON* t24b = cJSON_CreateObject();
|
||||
cJSON* t24b_fn = cJSON_CreateObject();
|
||||
cJSON* t24b_params = cJSON_CreateObject();
|
||||
cJSON* t24b_props = cJSON_CreateObject();
|
||||
cJSON* t24b_required = cJSON_CreateArray();
|
||||
|
||||
cJSON_AddStringToObject(t24b, "type", "function");
|
||||
cJSON_AddStringToObject(t24b_fn, "name", "skill_view");
|
||||
cJSON_AddStringToObject(t24b_fn, "description", "Compatibility alias for skill_get; JSON: {\"d\":\"identity_and_rules\"}");
|
||||
cJSON_AddStringToObject(t24b_params, "type", "object");
|
||||
cJSON_AddItemToObject(t24b_params, "properties", t24b_props);
|
||||
cJSON_AddItemToObject(t24b_params, "required", t24b_required);
|
||||
|
||||
cJSON* p_skill_view_d = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_skill_view_d, "type", "string");
|
||||
cJSON_AddItemToObject(t24b_props, "d", p_skill_view_d);
|
||||
|
||||
cJSON* p_skill_view_input = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_skill_view_input, "type", "string");
|
||||
cJSON_AddItemToObject(t24b_props, "input", p_skill_view_input);
|
||||
|
||||
cJSON_AddItemToArray(t24b_required, cJSON_CreateString("d"));
|
||||
|
||||
cJSON_AddItemToObject(t24b_fn, "parameters", t24b_params);
|
||||
cJSON_AddItemToObject(t24b, "function", t24b_fn);
|
||||
cJSON_AddItemToArray(tools, t24b);
|
||||
|
||||
cJSON* t24c = cJSON_CreateObject();
|
||||
cJSON* t24c_fn = cJSON_CreateObject();
|
||||
cJSON* t24c_params = cJSON_CreateObject();
|
||||
cJSON* t24c_props = cJSON_CreateObject();
|
||||
|
||||
cJSON_AddStringToObject(t24c, "type", "function");
|
||||
cJSON_AddStringToObject(t24c_fn, "name", "skill_set");
|
||||
cJSON_AddStringToObject(t24c_fn,
|
||||
"description",
|
||||
"Set/publish a full skill JSON payload and refresh runtime cache; JSON: {\"skill\":{\"d\":\"identity_and_rules\",\"kind\":31124,\"scope\":\"private\",\"content\":\"...\",\"tags\":[[\"d\",\"identity_and_rules\"],[\"app\",\"didactyl\"],[\"scope\",\"private\"]]}}");
|
||||
cJSON_AddStringToObject(t24c_params, "type", "object");
|
||||
cJSON_AddItemToObject(t24c_params, "properties", t24c_props);
|
||||
|
||||
cJSON* p_skill_set_skill = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_skill_set_skill, "type", "object");
|
||||
cJSON_AddStringToObject(p_skill_set_skill, "description", "Full skill object from skill_get output content");
|
||||
cJSON_AddItemToObject(t24c_props, "skill", p_skill_set_skill);
|
||||
|
||||
cJSON* p_skill_set_input = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_skill_set_input, "type", "string");
|
||||
cJSON_AddStringToObject(p_skill_set_input, "description", "Raw JSON string for slash shorthand or manual paste");
|
||||
cJSON_AddItemToObject(t24c_props, "input", p_skill_set_input);
|
||||
|
||||
cJSON_AddItemToObject(t24c_fn, "parameters", t24c_params);
|
||||
cJSON_AddItemToObject(t24c, "function", t24c_fn);
|
||||
cJSON_AddItemToArray(tools, t24c);
|
||||
|
||||
cJSON* t24 = cJSON_CreateObject();
|
||||
cJSON* t24_fn = cJSON_CreateObject();
|
||||
cJSON* t24_params = cJSON_CreateObject();
|
||||
@@ -1395,6 +1478,45 @@ char* tools_build_openai_schema_json_legacy(const tools_context_t* ctx) {
|
||||
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", "nostr_dm_history");
|
||||
cJSON_AddStringToObject(t43_fn,
|
||||
"description",
|
||||
"Fetch recent DM history for template/context usage; JSON: {\"limit\":12,\"include_current\":false,\"format\":\"json\"} or with explicit peer {\"peer_pubkey\":\"<hex64>\",\"limit\":20,\"format\":\"text\"}; template usage: {{nostr_dm_history({\"limit\":12,\"format\":\"text\"})}}");
|
||||
cJSON_AddStringToObject(t43_params, "type", "object");
|
||||
cJSON_AddItemToObject(t43_params, "properties", t43_props);
|
||||
|
||||
cJSON* p_dm_history_limit = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_dm_history_limit, "type", "integer");
|
||||
cJSON_AddStringToObject(p_dm_history_limit, "description", "Max message turns to return (1-200, default 12)");
|
||||
cJSON_AddItemToObject(t43_props, "limit", p_dm_history_limit);
|
||||
|
||||
cJSON* p_dm_history_include_current = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_dm_history_include_current, "type", "boolean");
|
||||
cJSON_AddStringToObject(p_dm_history_include_current, "description", "When true, keep a trailing user message that matches the current live message");
|
||||
cJSON_AddItemToObject(t43_props, "include_current", p_dm_history_include_current);
|
||||
|
||||
cJSON* p_dm_history_peer = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_dm_history_peer, "type", "string");
|
||||
cJSON_AddStringToObject(p_dm_history_peer, "description", "Optional peer pubkey hex (defaults to configured admin pubkey)");
|
||||
cJSON_AddItemToObject(t43_props, "peer_pubkey", p_dm_history_peer);
|
||||
|
||||
cJSON* p_dm_history_format = cJSON_CreateObject();
|
||||
cJSON_AddStringToObject(p_dm_history_format, "type", "string");
|
||||
cJSON_AddStringToObject(p_dm_history_format,
|
||||
"description",
|
||||
"Output format: 'json' (default) or 'text' (User:/Assistant: lines)");
|
||||
cJSON_AddItemToObject(t43_props, "format", p_dm_history_format);
|
||||
|
||||
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();
|
||||
|
||||
@@ -490,7 +490,7 @@ static cJSON* find_tag_value_string(cJSON* tags, const char* key) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int parse_address_tag(const char* addr, int* out_kind, char out_pubkey[65], char out_d_tag[65]) {
|
||||
static __attribute__((unused)) int parse_address_tag(const char* addr, int* out_kind, char out_pubkey[65], char out_d_tag[65]) {
|
||||
if (!addr || !out_kind || !out_pubkey || !out_d_tag) {
|
||||
return -1;
|
||||
}
|
||||
@@ -594,15 +594,28 @@ static void apply_trigger_runtime_to_llm_config(const active_trigger_t* t, llm_c
|
||||
|
||||
if (t->llm_spec[0] != '\0') {
|
||||
const char* spec = t->llm_spec;
|
||||
while (*spec && isspace((unsigned char)*spec)) spec++;
|
||||
|
||||
const char* comma = strchr(spec, ',');
|
||||
size_t len = comma ? (size_t)(comma - spec) : strlen(spec);
|
||||
while (len > 0 && isspace((unsigned char)spec[len - 1])) len--;
|
||||
while (*spec && isspace((unsigned char)*spec)) spec++;
|
||||
|
||||
const char* slash = memchr(spec, '/', len);
|
||||
if (slash) {
|
||||
size_t provider_len = (size_t)(slash - spec);
|
||||
const char* model = slash + 1;
|
||||
size_t model_len = len - (size_t)(model - spec);
|
||||
|
||||
while (provider_len > 0 && isspace((unsigned char)spec[provider_len - 1])) provider_len--;
|
||||
while (model_len > 0 && isspace((unsigned char)*model)) {
|
||||
model++;
|
||||
model_len--;
|
||||
}
|
||||
while (model_len > 0 && isspace((unsigned char)model[model_len - 1])) model_len--;
|
||||
|
||||
if (provider_len > 0 && provider_len < sizeof(cfg->provider)) {
|
||||
snprintf(cfg->provider, sizeof(cfg->provider), "%.*s", (int)provider_len, spec);
|
||||
}
|
||||
if (model_len > 0 && model_len < sizeof(cfg->model)) {
|
||||
snprintf(cfg->model, sizeof(cfg->model), "%.*s", (int)model_len, model);
|
||||
}
|
||||
@@ -807,137 +820,61 @@ int trigger_manager_load_from_skills(trigger_manager_t* mgr) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
char* adoption_json = nostr_handler_get_self_events_by_kind_json(10123);
|
||||
if (!adoption_json) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
cJSON* adoption_events = cJSON_Parse(adoption_json);
|
||||
free(adoption_json);
|
||||
if (!adoption_events || !cJSON_IsArray(adoption_events) || cJSON_GetArraySize(adoption_events) <= 0) {
|
||||
cJSON_Delete(adoption_events);
|
||||
return 0;
|
||||
}
|
||||
|
||||
cJSON* list_event = cJSON_GetArrayItem(adoption_events, 0);
|
||||
cJSON* list_tags = list_event ? cJSON_GetObjectItemCaseSensitive(list_event, "tags") : NULL;
|
||||
if (!list_tags || !cJSON_IsArray(list_tags)) {
|
||||
cJSON_Delete(adoption_events);
|
||||
return 0;
|
||||
}
|
||||
|
||||
int loaded = 0;
|
||||
int tn = cJSON_GetArraySize(list_tags);
|
||||
for (int i = 0; i < tn; i++) {
|
||||
cJSON* tag = cJSON_GetArrayItem(list_tags, i);
|
||||
if (!tag || !cJSON_IsArray(tag) || cJSON_GetArraySize(tag) < 2) continue;
|
||||
int considered = 0;
|
||||
const int kinds[2] = {31123, 31124};
|
||||
|
||||
cJSON* key = cJSON_GetArrayItem(tag, 0);
|
||||
cJSON* val = cJSON_GetArrayItem(tag, 1);
|
||||
if (!key || !val || !cJSON_IsString(key) || !cJSON_IsString(val) ||
|
||||
!key->valuestring || !val->valuestring || strcmp(key->valuestring, "a") != 0) {
|
||||
for (int k = 0; k < 2; k++) {
|
||||
char* skill_json = nostr_handler_get_self_events_by_kind_json(kinds[k]);
|
||||
if (!skill_json) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int kind = 0;
|
||||
char pubkey[65] = {0};
|
||||
char d_tag[65] = {0};
|
||||
if (parse_address_tag(val->valuestring, &kind, pubkey, d_tag) != 0) {
|
||||
cJSON* skill_events = cJSON_Parse(skill_json);
|
||||
free(skill_json);
|
||||
if (!skill_events || !cJSON_IsArray(skill_events)) {
|
||||
cJSON_Delete(skill_events);
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON* skill_events = NULL;
|
||||
if (strcmp(pubkey, mgr->cfg->keys.public_key_hex) == 0) {
|
||||
char* skill_json = nostr_handler_get_self_events_by_kind_json(kind);
|
||||
if (skill_json) {
|
||||
cJSON* all_events = cJSON_Parse(skill_json);
|
||||
free(skill_json);
|
||||
if (all_events && cJSON_IsArray(all_events)) {
|
||||
skill_events = cJSON_CreateArray();
|
||||
if (skill_events) {
|
||||
int all_n = cJSON_GetArraySize(all_events);
|
||||
for (int ai = 0; ai < all_n; ai++) {
|
||||
cJSON* ev = cJSON_GetArrayItem(all_events, ai);
|
||||
cJSON* ev_pubkey = ev ? cJSON_GetObjectItemCaseSensitive(ev, "pubkey") : NULL;
|
||||
cJSON* ev_tags = ev ? cJSON_GetObjectItemCaseSensitive(ev, "tags") : NULL;
|
||||
cJSON* ev_d = find_tag_value_string(ev_tags, "d");
|
||||
if (!ev_pubkey || !cJSON_IsString(ev_pubkey) || !ev_pubkey->valuestring ||
|
||||
strcmp(ev_pubkey->valuestring, pubkey) != 0 ||
|
||||
!ev_d || !cJSON_IsString(ev_d) || !ev_d->valuestring ||
|
||||
strcmp(ev_d->valuestring, d_tag) != 0) {
|
||||
continue;
|
||||
}
|
||||
cJSON* dup = cJSON_Duplicate(ev, 1);
|
||||
if (dup) {
|
||||
cJSON_AddItemToArray(skill_events, dup);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cJSON_Delete(all_events);
|
||||
}
|
||||
} else {
|
||||
cJSON* skill_filter = cJSON_CreateObject();
|
||||
cJSON* sk_kinds = cJSON_CreateArray();
|
||||
cJSON* sk_authors = cJSON_CreateArray();
|
||||
cJSON* d_values = cJSON_CreateArray();
|
||||
if (!skill_filter || !sk_kinds || !sk_authors || !d_values) {
|
||||
cJSON_Delete(skill_filter);
|
||||
cJSON_Delete(sk_kinds);
|
||||
cJSON_Delete(sk_authors);
|
||||
cJSON_Delete(d_values);
|
||||
int sn = cJSON_GetArraySize(skill_events);
|
||||
for (int i = 0; i < sn; i++) {
|
||||
cJSON* skill_event = cJSON_GetArrayItem(skill_events, i);
|
||||
cJSON* content = skill_event ? cJSON_GetObjectItemCaseSensitive(skill_event, "content") : NULL;
|
||||
cJSON* tags = skill_event ? cJSON_GetObjectItemCaseSensitive(skill_event, "tags") : NULL;
|
||||
if (!content || !cJSON_IsString(content) || !content->valuestring || !tags || !cJSON_IsArray(tags)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON_AddItemToArray(sk_kinds, cJSON_CreateNumber(kind));
|
||||
cJSON_AddItemToObject(skill_filter, "kinds", sk_kinds);
|
||||
cJSON_AddItemToArray(sk_authors, cJSON_CreateString(pubkey));
|
||||
cJSON_AddItemToObject(skill_filter, "authors", sk_authors);
|
||||
cJSON_AddItemToArray(d_values, cJSON_CreateString(d_tag));
|
||||
cJSON_AddItemToObject(skill_filter, "#d", d_values);
|
||||
cJSON_AddNumberToObject(skill_filter, "limit", 1);
|
||||
cJSON* d = find_tag_value_string(tags, "d");
|
||||
cJSON* trigger = find_tag_value_string(tags, "trigger");
|
||||
cJSON* filter = find_tag_value_string(tags, "filter");
|
||||
cJSON* action = find_tag_value_string(tags, "action");
|
||||
|
||||
char* skill_json = nostr_handler_query_json(skill_filter, 2000);
|
||||
cJSON_Delete(skill_filter);
|
||||
if (skill_json) {
|
||||
skill_events = cJSON_Parse(skill_json);
|
||||
free(skill_json);
|
||||
const char* d_tag = (d && cJSON_IsString(d) && d->valuestring) ? d->valuestring : NULL;
|
||||
const char* trigger_s = (trigger && cJSON_IsString(trigger) && trigger->valuestring) ? trigger->valuestring : NULL;
|
||||
const char* filter_s = (filter && cJSON_IsString(filter) && filter->valuestring) ? filter->valuestring : NULL;
|
||||
const char* action_s = (action && cJSON_IsString(action) && action->valuestring) ? action->valuestring : "llm";
|
||||
|
||||
considered++;
|
||||
if (!d_tag || d_tag[0] == '\0') {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!skill_events || !cJSON_IsArray(skill_events) || cJSON_GetArraySize(skill_events) <= 0) {
|
||||
cJSON_Delete(skill_events);
|
||||
continue;
|
||||
}
|
||||
int trigger_supported = trigger_s &&
|
||||
(strcmp(trigger_s, "nostr-subscription") == 0 ||
|
||||
strcmp(trigger_s, "webhook") == 0 ||
|
||||
strcmp(trigger_s, "cron") == 0 ||
|
||||
strcmp(trigger_s, "chain") == 0 ||
|
||||
strcmp(trigger_s, "dm") == 0);
|
||||
if (!trigger_supported || !filter_s || filter_s[0] == '\0') {
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON* skill_event = cJSON_GetArrayItem(skill_events, 0);
|
||||
cJSON* content = skill_event ? cJSON_GetObjectItemCaseSensitive(skill_event, "content") : NULL;
|
||||
cJSON* tags = skill_event ? cJSON_GetObjectItemCaseSensitive(skill_event, "tags") : NULL;
|
||||
if (!content || !cJSON_IsString(content) || !content->valuestring || !tags || !cJSON_IsArray(tags)) {
|
||||
cJSON_Delete(skill_events);
|
||||
continue;
|
||||
}
|
||||
|
||||
cJSON* trigger = find_tag_value_string(tags, "trigger");
|
||||
cJSON* filter = find_tag_value_string(tags, "filter");
|
||||
cJSON* action = find_tag_value_string(tags, "action");
|
||||
cJSON* enabled = find_tag_value_string(tags, "enabled");
|
||||
|
||||
const char* trigger_s = (trigger && cJSON_IsString(trigger) && trigger->valuestring) ? trigger->valuestring : NULL;
|
||||
const char* filter_s = (filter && cJSON_IsString(filter) && filter->valuestring) ? filter->valuestring : NULL;
|
||||
const char* action_s = (action && cJSON_IsString(action) && action->valuestring) ? action->valuestring : "llm";
|
||||
const char* enabled_s = (enabled && cJSON_IsString(enabled) && enabled->valuestring) ? enabled->valuestring : "true";
|
||||
|
||||
int trigger_supported = trigger_s &&
|
||||
(strcmp(trigger_s, "nostr-subscription") == 0 ||
|
||||
strcmp(trigger_s, "webhook") == 0 ||
|
||||
strcmp(trigger_s, "cron") == 0 ||
|
||||
strcmp(trigger_s, "chain") == 0 ||
|
||||
strcmp(trigger_s, "dm") == 0);
|
||||
if (trigger_supported && filter_s && filter_s[0] != '\0') {
|
||||
if (strcmp(action_s, "template") == 0) {
|
||||
DEBUG_WARN("[didactyl] trigger action template is deprecated; forcing llm for d_tag=%s", d_tag);
|
||||
}
|
||||
|
||||
const char* llm_s = NULL;
|
||||
const char* tools_s = NULL;
|
||||
int has_max_tokens = 0;
|
||||
@@ -956,14 +893,13 @@ int trigger_manager_load_from_skills(trigger_manager_t* mgr) {
|
||||
&has_seed,
|
||||
&seed);
|
||||
|
||||
int is_enabled = (strcmp(enabled_s, "false") == 0 || strcmp(enabled_s, "0") == 0) ? 0 : 1;
|
||||
if (trigger_manager_add(mgr,
|
||||
d_tag,
|
||||
content->valuestring,
|
||||
filter_s,
|
||||
TRIGGER_ACTION_LLM,
|
||||
trigger_s,
|
||||
is_enabled,
|
||||
1,
|
||||
llm_s,
|
||||
tools_s,
|
||||
has_max_tokens,
|
||||
@@ -979,8 +915,7 @@ int trigger_manager_load_from_skills(trigger_manager_t* mgr) {
|
||||
cJSON_Delete(skill_events);
|
||||
}
|
||||
|
||||
cJSON_Delete(adoption_events);
|
||||
DEBUG_INFO("[didactyl] trigger manager loaded %d trigger(s) from skills", loaded);
|
||||
DEBUG_INFO("[didactyl] trigger manager loaded %d trigger(s) from self skills (considered=%d)", loaded, considered);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1542,33 +1477,22 @@ static int dm_filter_matches_tier(const char* filter_json, didactyl_sender_tier_
|
||||
return match;
|
||||
}
|
||||
|
||||
int trigger_manager_fire_dm(trigger_manager_t* mgr,
|
||||
const char* sender_pubkey_hex,
|
||||
const char* message,
|
||||
didactyl_sender_tier_t tier,
|
||||
const char* source_label) {
|
||||
if (!mgr || !sender_pubkey_hex || !message) {
|
||||
int trigger_manager_get_dm_skills(trigger_manager_t* mgr,
|
||||
const char* sender_pubkey_hex,
|
||||
didactyl_sender_tier_t tier,
|
||||
char** out_d_tags,
|
||||
int max_d_tags) {
|
||||
(void)sender_pubkey_hex;
|
||||
|
||||
if (!mgr || !out_d_tags || max_d_tags <= 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON* event = cJSON_CreateObject();
|
||||
if (!event) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
cJSON_AddStringToObject(event, "type", "dm");
|
||||
cJSON_AddStringToObject(event, "sender_pubkey", sender_pubkey_hex);
|
||||
cJSON_AddStringToObject(event, "message", message);
|
||||
cJSON_AddStringToObject(event, "tier",
|
||||
tier == DIDACTYL_SENDER_ADMIN ? "admin" :
|
||||
(tier == DIDACTYL_SENDER_WOT ? "wot" : "stranger"));
|
||||
cJSON_AddNumberToObject(event, "created_at", (double)time(NULL));
|
||||
|
||||
int fired_total = 0;
|
||||
int count = 0;
|
||||
|
||||
pthread_mutex_lock(&mgr->mutex);
|
||||
int count_snapshot = mgr->count;
|
||||
for (int i = 0; i < count_snapshot; i++) {
|
||||
for (int i = 0; i < count_snapshot && count < max_d_tags; i++) {
|
||||
active_trigger_t* t = &mgr->triggers[i];
|
||||
if (!t->enabled || t->trigger_type != TRIGGER_TYPE_DM) {
|
||||
continue;
|
||||
@@ -1577,15 +1501,11 @@ int trigger_manager_fire_dm(trigger_manager_t* mgr,
|
||||
continue;
|
||||
}
|
||||
|
||||
int fired = maybe_fire_trigger_locked(mgr, i, event, source_label ? source_label : "dm");
|
||||
if (fired > 0) {
|
||||
fired_total += fired;
|
||||
}
|
||||
out_d_tags[count++] = t->skill_d_tag;
|
||||
}
|
||||
pthread_mutex_unlock(&mgr->mutex);
|
||||
|
||||
cJSON_Delete(event);
|
||||
return fired_total;
|
||||
return count;
|
||||
}
|
||||
|
||||
char* trigger_manager_status_json(trigger_manager_t* mgr) {
|
||||
|
||||
@@ -105,11 +105,11 @@ int trigger_manager_fire_chains(trigger_manager_t* mgr,
|
||||
const char* source_skill_d_tag,
|
||||
cJSON* source_event,
|
||||
const char* source_label);
|
||||
int trigger_manager_fire_dm(trigger_manager_t* mgr,
|
||||
const char* sender_pubkey_hex,
|
||||
const char* message,
|
||||
didactyl_sender_tier_t tier,
|
||||
const char* source_label);
|
||||
int trigger_manager_get_dm_skills(trigger_manager_t* mgr,
|
||||
const char* sender_pubkey_hex,
|
||||
didactyl_sender_tier_t tier,
|
||||
char** out_d_tags,
|
||||
int max_d_tags);
|
||||
int trigger_manager_active_count(trigger_manager_t* mgr);
|
||||
int trigger_manager_poll(trigger_manager_t* mgr);
|
||||
char* trigger_manager_status_json(trigger_manager_t* mgr);
|
||||
|
||||
Reference in New Issue
Block a user