// Dragon AI Connect (dragon_ai_connect.lsl) - connects a prim to Dragon AI Connect: linking, the token, HTTP, pushes, and local chat. // On its own it's a chatbot: say its name in local chat and it answers. Add parts of the Dragon Library // (dragon_presence, dragon_dialog, dragon_give, dragon_effects, dragon_sense, dragon_watch, dragon_motion, // dragon_shape) for more senses and hands, or your own scripts. Full guide: https://dragonaiconnect.com/docs/api/script // // ---- Link messages --------------------------------------------------------------------- // 9100 you -> API ask the AI: JSON {"prompt": ...}; id = your request id (the reply is yours to use) // 9101 API -> all reply JSON; id = your request id 9102 API -> all error {"code","error"} // 9103 API -> all status: ready | pairing | unpaired // 9104 you -> API link again (same agent) 9105 you -> API become a new agent (copies) // Library parts: 9112 hello "dragon-, N KB free" -> API; 9113 API -> parts "announce yourself"; // 9110 API -> parts actions; 9114 API -> parts settings; 9119 part -> API a sense (arrival, tip, menu // answer...) that the API asks about and answers itself; 9111 world, 9116 notecard, 9117 query result, // 9118 hello / watch event -> API (forwarded to the server). // ------------------------------------------------------------------------------------------ string SERVER = "https://dragonaiconnect.com"; // no trailing slash (older scripts use 157-245-163-20.sslip.io: still served) string LSD_PASS = "Gk2CUuEu4hYfLRci-SxCR5lE"; integer ENGAGE_SECS = 90; // after its name is said, follow-ups don't need it integer OPEN_GAP = 4; // open mode: at most one overheard line every 4 s string gMode = "unpaired"; string gDeviceId; string gToken; string gPairCode; string gPollSecret; integer gDeadline; key gPairReq; key gPollReq; key gBeatReq; key gStatusReq; key gCloneReq; key gInReq; list gPending; // strided [request key, caller id]: asks from your scripts (9100) list gMine; // strided [request key, body, tries]: our own asks (chat, senses) list gEvents; // Library event requests whose answers may carry actions list gEvQ; // Library events waiting to go: sent about one a second (Second Life throttles HTTP) float gLastEv; string gPushURL; string gPushSecret; list gParts; // Library parts that said hello (presence, dialog...) integer gCustom; // a script that isn't a Dragon part said hello: offer every action string gConfig; string gName; string gChat = "name"; integer gModerate; list gEngaged; // strided [avatar, until] integer gLastOpen; integer gLastMod; integer gMenuChan; integer gMenuListen; integer gCmdListen; integer gChatListen; integer gThinking; integer gStatusOn; integer gStatusUntil; // a work status on the sign ("Building hut: 12/40") string gPhase; string gPhaseRest; integer gDots; // a phase ending in "..." whose dots keep moving integer gTick; key post(string path, string body) { list o = [HTTP_METHOD, "POST", HTTP_MIMETYPE, "application/json", HTTP_BODY_MAXLENGTH, 4096, HTTP_VERIFY_CERT, TRUE]; if (gToken != "") o += [HTTP_CUSTOM_HEADER, "X-Session-Token", gToken]; return llHTTPRequest(SERVER + path, o, body); } mode(string m) { if (m != gMode) { gMode = m; llMessageLinked(LINK_SET, 9103, m, NULL_KEY); } } sendEvent() // the next queued Library event; one the throttle refuses stays queued and the timer tries again { // (no sleeping here: a sleeping script misses messages, and Second Life drops what doesn't fit) if (gEvQ == []) return; if (gMode != "ready") return; key r = post("/v1/toolkit/event", llList2String(gEvQ, 0)); gLastEv = llGetTime(); if (r == NULL_KEY) return; // throttled: the timer tries again gEvQ = llDeleteSubList(gEvQ, 0, 0); gEvents = llList2List(gEvents + [r], -10, -1); } string err(string c, string m) { return llList2Json(JSON_OBJECT, ["error", m, "code", c]); } integer gone(string c) { return c == "INVALID_TOKEN" || c == "TOKEN_EXPIRED" || c == "DEVICE_REVOKED"; } pairing() { gToken = ""; llLinksetDataDeleteProtected("slm_token", LSD_PASS); mode("pairing"); gPairReq = post("/v1/pair/start", llList2Json(JSON_OBJECT, ["device_id", gDeviceId, "owner_username", llGetUsername(llGetOwner())])); // checked against the account holder's signed agreement } ready() { if (gPushURL != "") llReleaseURL(gPushURL); gPushURL = ""; llRequestSecureURL(); mode("ready"); gBeatReq = post("/v1/heartbeat", "{}"); llMessageLinked(LINK_THIS, 9113, "", NULL_KEY); // library: send hello + world again } token(string t) { gToken = t; llLinksetDataWriteProtected("slm_token", t, LSD_PASS); } config(string c) { if (c == JSON_INVALID || c == "" || c == gConfig) return; gConfig = c; string n = llJsonGetValue(c, ["name"]); if (n != JSON_INVALID && n != "") gName = n; gChat = llJsonGetValue(c, ["chat_mode"]); gModerate = llJsonGetValue(c, ["moderate"]) == JSON_TRUE; if (gChatListen) llListenRemove(gChatListen); gChatListen = 0; if (gChat != "off") gChatListen = llListen(0, "", NULL_KEY, ""); llMessageLinked(LINK_THIS, 9114, c, NULL_KEY); } // ---------------- asking: local chat and the parts' senses ---------------- string words(string t) { return " " + llDumpList2String(llParseString2List(llToLower(t), [" ", ",", ".", "!", "?", ":", ";", "\"", "(", ")"], []), " ") + " "; } string nearby() { list out; integer i; list ag = llGetAgentList(AGENT_LIST_REGION, []); vector me = llGetPos(); for (i = 0; i < llGetListLength(ag) && llGetListLength(out) < 12; ++i) { key k = llList2Key(ag, i); integer d = (integer)llVecDist(me, llList2Vector(llGetObjectDetails(k, [OBJECT_POS]), 0)); if (d <= 20) out += llList2Json(JSON_OBJECT, ["n", llGetDisplayName(k), "k", k, "d", d]); } return llList2Json(JSON_ARRAY, out); } string caps(string b) // which hands this object has, so the AI is only offered what can really happen { if (gCustom) return llJsonSetValue(b, ["caps"], "[\"actions\"]"); return llJsonSetValue(llJsonSetValue(b, ["caps"], "[\"actions\"]"), ["parts"], llList2Json(JSON_ARRAY, gParts)); } send(string b, integer tries) { key r = post("/v1/chat", b); if (r == NULL_KEY) return; gMine = llList2List(gMine + [r, b, tries], -30, -1); thinking(TRUE); } ask(string b) // b: {"prompt","speaker","speaker_name",...}; the API fills in the rest { if (gMode != "ready") return; key who = (key)llJsonGetValue(b, ["speaker"]); if (llJsonGetValue(b, ["max_tokens"]) == JSON_INVALID) b = llJsonSetValue(b, ["max_tokens"], "200"); b = llJsonSetValue(b, ["max_chars"], "1000"); b = llJsonSetValue(b, ["same_group"], llList2String([JSON_FALSE, JSON_TRUE], llSameGroup(who))); if (gModerate) b = llJsonSetValue(b, ["moderate"], JSON_TRUE); b = llJsonSetValue(b, ["world", "nearby"], nearby()); send(caps(b), 0); } hear(string name, key id, string msg) { integer now = llGetUnixTime(); integer i = llListFindList(gEngaged, [id]); integer named = FALSE; if (gName != "") named = llSubStringIndex(words(msg), words(gName)) != -1; integer following = FALSE; if (i != -1) following = llList2Integer(gEngaged, i + 1) > now; string b = llList2Json(JSON_OBJECT, ["prompt", msg, "speaker", id, "speaker_name", name]); if (named || following) { if (i != -1) gEngaged = llDeleteSubList(gEngaged, i, i + 1); gEngaged = llList2List(gEngaged + [id, now + ENGAGE_SECS], -20, -1); ask(b); } else if (gChat == "open" && now - gLastOpen >= OPEN_GAP) { gLastOpen = now; ask(llJsonSetValue(b, ["overheard"], JSON_TRUE)); } else if (gModerate && now - gLastMod >= 2) { gLastMod = now; ask(llJsonSetValue(b, ["overheard"], JSON_TRUE)); } } // ---------------- the API's own hands: speech, owner IM, your scripts, the owner menu ---------------- // The owner's own sign (set_text) lives in linkset data, never read back from the prim: what the prim shows may // be a status that missed its clear. With no sign of their own the text is truly cleared (Second Life keeps the // last text otherwise). own_sign() { string s = llLinksetDataRead("slm_sign"); if (s == "") llSetText(" ", ZERO_VECTOR, 0.0); else llSetText(s, <1.0, 1.0, 1.0>, 1.0); } status(string t) // what it's working on, on its sign; "" puts the owner's sign back (or clears it) { if (t != "" && t != JSON_INVALID) { gStatusOn = TRUE; gStatusUntil = llGetUnixTime() + 600; // never stuck: it clears itself after 10 minutes integer nl = llSubStringIndex(t, "\n"); string first = t; gPhaseRest = ""; if (nl >= 0) { first = llGetSubString(t, 0, nl - 1); gPhaseRest = llGetSubString(t, nl, -1); } if (llGetSubString(first, -3, -1) == "...") { // working: the dots move, like a progress bar gPhase = llGetSubString(first, 0, -4); gDots = 3; llSensorRepeat("dragon-no-such-avatar", NULL_KEY, AGENT, 0.1, 0.1, 0.6); // a second, faster timer } else { gPhase = ""; llSensorRemove(); } llSetText(t, <1.0, 0.8, 0.35>, 1.0); return; } gPhase = ""; llSensorRemove(); gStatusOn = FALSE; // always: a clear is never skipped if (gThinking) llSetText("...", <0.4, 0.9, 0.85>, 1.0); else own_sign(); } speak(string acts) // runs for every action list on 9110: from the server (via act) or from your scripts { integer i; string a = llJsonGetValue(acts, [0]); while (a != JSON_INVALID && i < 8) { string w = llJsonGetValue(a, ["do"]); string t = llJsonGetValue(a, ["text"]); key to = (key)llJsonGetValue(a, ["to"]); if (w == "say") llSay(0, t); else if (w == "whisper") llWhisper(0, t); else if (w == "shout") llShout(0, t); else if (w == "notify_owner") llInstantMessage(llGetOwner(), t); else if (w == "say_to") { if (to) llRegionSayTo(to, 0, t); } else if (w == "link_message") llMessageLinked(LINK_SET, (integer)llJsonGetValue(a, ["num"]), t, to); else if (w == "config") config(a); else if (w == "menu") menu(); else if (w == "status") status(t); a = llJsonGetValue(acts, [++i]); } } // Every script in this prim gets it, this one too (speak), and each part carries out its own actions. act(string acts, key caller) { if (llJsonValueType(acts, []) == JSON_ARRAY && acts != "[]") llMessageLinked(LINK_THIS, 9110, acts, caller); } menu() { if (gMenuListen) llListenRemove(gMenuListen); gMenuChan = -1000000 - (integer)llFrand(1000000000.0); gMenuListen = llListen(gMenuChan, "", llGetOwner(), ""); llDialog(llGetOwner(), "Dragon AI Connect: " + gMode + "\n\nRe-link: link again (keeps name, personality, memory)." + "\nNew device: make this object its own agent (use on copies).", ["Status", "Re-link", "New device", "Cancel"], gMenuChan); } thinking(integer on) { if (on) { if (gThinking++ == 0) { if (!gStatusOn) llSetText("...", <0.4, 0.9, 0.85>, 1.0); // a status owns the sign: leave it showing } } else if (gThinking > 0) { if (--gThinking == 0) { if (!gStatusOn) own_sign(); } } } init() { llSetTimerEvent(5.0); own_sign(); // a reset never leaves an old status showing if (gCmdListen) llListenRemove(gCmdListen); gCmdListen = llListen(88, "", llGetOwner(), ""); string owner = llLinksetDataRead("slm_owner"); // given or sold: forget the old account if (owner != "" && owner != (string)llGetOwner()) { llLinksetDataDelete("slm_device_id"); llLinksetDataDeleteProtected("slm_token", LSD_PASS); } llLinksetDataWrite("slm_owner", (string)llGetOwner()); gDeviceId = llLinksetDataRead("slm_device_id"); if (gDeviceId == "") { gDeviceId = (string)llGenerateKey(); llLinksetDataWrite("slm_device_id", gDeviceId); } gToken = llLinksetDataReadProtected("slm_token", LSD_PASS); gMode = ""; gParts = []; gCustom = FALSE; gName = llGetObjectName(); if (!gChatListen) gChatListen = llListen(0, "", NULL_KEY, ""); if (gToken != "") ready(); else { mode("unpaired"); pairing(); } } default { state_entry() { init(); } on_rez(integer p) { init(); } changed(integer c) { if (c & CHANGED_OWNER) { init(); return; } if (c & (CHANGED_REGION_START | CHANGED_REGION | CHANGED_TELEPORT)) { if (gMode == "ready") ready(); } } no_sensor() // the moving dots of a working phase (the sensor never finds anyone: it's just a fast tick) { if (!gStatusOn || gPhase == "") { llSensorRemove(); return; } gDots = (gDots + 1) % 4; llSetText(gPhase + llList2String(["", ".", "..", "..."], gDots) + gPhaseRest, <1.0, 0.8, 0.35>, 1.0); } timer() { ++gTick; // 5-second ticks if (gStatusOn) { if (llGetUnixTime() > gStatusUntil) status(""); } if (gEvQ != []) sendEvent(); // retry anything the throttle held back if (gMode == "pairing" && gPairCode != "") { if (llGetUnixTime() > gDeadline) { mode("unpaired"); gPairCode = ""; llOwnerSay("Linking timed out. Type /88 settings, Re-link."); } else gPollReq = post("/v1/pair/poll", llList2Json(JSON_OBJECT, ["code", gPairCode, "poll_secret", gPollSecret])); } if (gMode == "ready" && gTick % 4320 == 0) gBeatReq = post("/v1/heartbeat", "{}"); // every 6 h } listen(integer ch, string name, key id, string msg) { if (ch == 0) { if (llGetAgentSize(id) != ZERO_VECTOR) hear(name, id, msg); return; } // avatars only if (ch == 88) { if (llToLower(llStringTrim(msg, STRING_TRIM)) == "settings") menu(); return; } llListenRemove(gMenuListen); gMenuListen = 0; if (msg == "Status") { string p = "none (add parts of the Dragon Library for more abilities)"; if (gParts != []) p = llDumpList2String(gParts, ", "); if (gCustom) p += " + your own scripts"; llOwnerSay("Dragon AI Connect: " + gMode + ", " + (string)(llGetFreeMemory() / 1024) + " KB free. Library parts: " + p + "."); if (gMode == "ready") gStatusReq = post("/v1/heartbeat", "{}"); llMessageLinked(LINK_THIS, 9113, "status", NULL_KEY); // each part reports its own memory } else if (msg == "Re-link") pairing(); else if (msg == "New device") { gDeviceId = (string)llGenerateKey(); llLinksetDataWrite("slm_device_id", gDeviceId); if (gToken != "") gCloneReq = post("/v1/pair/clone", llList2Json(JSON_OBJECT, ["new_device_id", gDeviceId])); else pairing(); } } link_message(integer sender, integer num, string str, key id) { if (num == 9100) { if (gMode != "ready") { llMessageLinked(LINK_SET, 9102, err("NOT_PAIRED", "Not linked yet."), id); return; } if (gParts != [] || gCustom) str = caps(str); key r = post("/v1/chat", str); if (r == NULL_KEY) { llMessageLinked(LINK_SET, 9102, err("THROTTLED", "Too many requests; slow down."), id); return; } gPending = llList2List(gPending + [r, id], -40, -1); thinking(TRUE); } else if (num == 9110) speak(str); else if (num == 9119) ask(str); else if (num == 9112) { string p = llList2String(llParseString2List(str, [","], []), 0); if (llGetSubString(p, 0, 6) == "dragon-" && p != "dragon-library") { p = llGetSubString(p, 7, -1); if (llListFindList(gParts, [p]) == -1) gParts += p; } else gCustom = TRUE; if (gConfig != "") llMessageLinked(LINK_THIS, 9114, gConfig, NULL_KEY); } else if (num == 9111) { if (gMode == "ready") post("/v1/world", str); } else if (num == 9116) { if (gMode == "ready") post("/v1/notecard", str); } else if (num == 9117) { if (gMode == "ready") post("/v1/toolkit/result", str); } else if (num == 9118) { if (gMode == "ready") { gEvQ = llList2List(gEvQ + [str], -12, -1); // small: this script has 64 KB if (llGetFreeMemory() < 12000) gEvQ = llList2List(gEvQ, -3, -1); // never run out of memory if (llGetListLength(gEvQ) == 1) sendEvent(); } } else if (num == 9115) menu(); else if (num == 9104) pairing(); else if (num == 9105) { gDeviceId = (string)llGenerateKey(); llLinksetDataWrite("slm_device_id", gDeviceId); if (gToken != "") gCloneReq = post("/v1/pair/clone", llList2Json(JSON_OBJECT, ["new_device_id", gDeviceId])); else pairing(); } } http_request(key id, string method, string body) { if (method == URL_REQUEST_GRANTED) { gPushURL = body; gPushSecret = (string)llGenerateKey() + (string)llGenerateKey(); gInReq = post("/v1/inbound", llList2Json(JSON_OBJECT, ["url", body, "secret", gPushSecret])); return; } if (method == URL_REQUEST_DENIED) return; if (gPushSecret == "" || llGetHTTPHeader(id, "x-query-string") != "s=" + gPushSecret) { llHTTPResponse(id, 403, "no"); return; } llHTTPResponse(id, 200, "ok"); string t = llJsonGetValue(body, ["text"]); if (t != "" && t != JSON_INVALID) llSay(0, t); act(llJsonGetValue(body, ["actions"]), NULL_KEY); } http_response(key req, integer status, list meta, string body) { string code = llJsonGetValue(body, ["code"]); if (req == gPairReq) { if (status != 200) { mode("unpaired"); llOwnerSay("Couldn't start linking (" + (string)status + ")."); return; } gPairCode = code; gPollSecret = llJsonGetValue(body, ["poll_secret"]); gDeadline = llGetUnixTime() + (integer)llJsonGetValue(body, ["expires_in"]); llLoadURL(llGetOwner(), "Link this object to your Dragon AI Connect account", llJsonGetValue(body, ["url"])); llOwnerSay("Link me to your account: " + llJsonGetValue(body, ["url"])); return; } if (req == gPollReq) { if (status == 200 && llJsonGetValue(body, ["status"]) == "approved") { string nd = llJsonGetValue(body, ["device_id"]); // linked as one of the owner's existing agents if (nd != JSON_INVALID && nd != "" && nd != gDeviceId) { gDeviceId = nd; llLinksetDataWrite("slm_device_id", nd); } token(llJsonGetValue(body, ["token"])); gPairCode = ""; llOwnerSay("Linked! I'm ready."); ready(); } else if (status == 410 || status == 404) { mode("unpaired"); gPairCode = ""; llOwnerSay("Linking expired. Type /88 settings, Re-link."); } return; } if (req == gCloneReq) { if (status == 200) { token(llJsonGetValue(body, ["token"])); llOwnerSay("Done! I'm my own agent now."); ready(); } else pairing(); return; } if (req == gInReq) return; integer e = llListFindList(gEvents, [req]); if (e != -1) { // a Library event: the server may answer with actions (rules, a reply, an IM...) gEvents = llDeleteSubList(gEvents, e, e); if (status == 200) act(llJsonGetValue(body, ["actions"]), NULL_KEY); sendEvent(); // the next one in line return; } if (req == gBeatReq || req == gStatusReq) { if (status == 200) { config(llJsonGetValue(body, ["config"])); if (req == gStatusReq) llOwnerSay("Spent $" + llJsonGetValue(body, ["spent_usd"]) + " of $" + llJsonGetValue(body, ["limit_usd"]) + "."); } else if (gone(code)) pairing(); return; } integer m = llListFindList(gMine, [req]); if (m != -1) { // our own ask: speak the reply and carry out its actions if (m % 3) return; string b = llList2String(gMine, m + 1); integer tries = llList2Integer(gMine, m + 2); gMine = llDeleteSubList(gMine, m, m + 2); thinking(FALSE); if (status == 200) { config(llJsonGetValue(body, ["config"])); string t = llJsonGetValue(body, ["text"]); if (t != "" && t != JSON_INVALID && llJsonGetValue(body, ["silent"]) != JSON_TRUE) llSay(0, t); act(llJsonGetValue(body, ["actions"]), NULL_KEY); return; } if (tries == 0 && (status >= 500 || status == 499 || code == "UPSTREAM_TIMEOUT")) { llSleep(3.0); send(b, 1); return; } if (gone(code)) { llOwnerSay("My link was revoked; re-linking..."); pairing(); return; } llOwnerSay("Dragon error: " + code); if (llJsonGetValue(b, ["overheard"]) != JSON_TRUE && llJsonGetValue(b, ["event"]) == JSON_INVALID) llSay(0, "Sorry, I couldn't think just now. Please try again."); return; } integer i = llListFindList(gPending, [req]); if (i == -1 || i % 2) return; key caller = llList2Key(gPending, i + 1); gPending = llDeleteSubList(gPending, i, i + 1); thinking(FALSE); if (status == 200) { config(llJsonGetValue(body, ["config"])); llMessageLinked(LINK_SET, 9101, body, caller); act(llJsonGetValue(body, ["actions"]), caller); return; } if (llJsonValueType(body, []) != JSON_OBJECT) body = err("HTTP_" + (string)status, "Request failed."); llMessageLinked(LINK_SET, 9102, body, caller); if (gone(code)) { llOwnerSay("My link was revoked; re-linking..."); pairing(); } } }