libmock.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. package playground
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/url"
  8. "path"
  9. "regexp"
  10. "sort"
  11. "strings"
  12. "time"
  13. "unicode/utf8"
  14. "github.com/robertkrimen/otto"
  15. )
  16. // Mocks hold the answers the page's tool windows set for services the
  17. // playground cannot reach.
  18. type Mocks struct {
  19. HTTP HTTPMock `json:"http"`
  20. LLM LLMMock `json:"llm"`
  21. CNN CNNMock `json:"cnn"`
  22. SQLite []SQLRule `json:"sqlite"`
  23. Sysinfo SysinfoMock `json:"sysinfo"`
  24. Generic map[string]string `json:"generic"` // "git.status" -> JSON it returns
  25. WS WSMock `json:"ws"`
  26. SchedulerDenied bool `json:"schedulerDenied"`
  27. }
  28. type HTTPMock struct {
  29. Rules []HTTPRule `json:"rules"`
  30. // Fallback answers a request no rule matches: "error" (the request
  31. // fails, as without network) or "404".
  32. Fallback string `json:"fallback"`
  33. }
  34. // HTTPRule answers requests whose method and URL match. URL is an exact URL,
  35. // a pattern with * wildcards, or a /regular expression/.
  36. type HTTPRule struct {
  37. Name string `json:"name"`
  38. Method string `json:"method"` // "" or "ANY" for every method
  39. URL string `json:"url"`
  40. Status int `json:"status"`
  41. Headers map[string]string `json:"headers"`
  42. Body string `json:"body"` // may use {{method}}, {{url}}, {{body}}
  43. Base64 bool `json:"base64"`
  44. Error string `json:"error"` // fail the request with this message
  45. DelayMs int `json:"delayMs"`
  46. }
  47. type LLMMock struct {
  48. Mode string `json:"mode"` // "fixed", "echo" or "rules"
  49. Reply string `json:"reply"`
  50. Reasoning string `json:"reasoning"`
  51. Rules []TextRule `json:"rules"`
  52. Error string `json:"error"`
  53. Model string `json:"model"`
  54. Models []string `json:"models"`
  55. ChunkSize int `json:"chunkSize"`
  56. ChunkDelayMs int `json:"chunkDelayMs"`
  57. }
  58. // TextRule matches text by substring (case-insensitive) or /regex/.
  59. type TextRule struct {
  60. Match string `json:"match"`
  61. Reply string `json:"reply"`
  62. }
  63. type CNNMock struct {
  64. Responses map[string]string `json:"responses"` // function -> JSON envelope
  65. Error string `json:"error"`
  66. }
  67. type SQLRule struct {
  68. Fn string `json:"fn"` // exec, query, queryRow, tables, schema
  69. Match string `json:"match"`
  70. Result string `json:"result"`
  71. }
  72. type SysinfoMock struct {
  73. CPU string `json:"cpu"`
  74. RAM string `json:"ram"`
  75. Network string `json:"network"`
  76. Disks string `json:"disks"`
  77. }
  78. // matchURL: exact, * wildcards or /regex/.
  79. func matchURL(pattern, s string) bool {
  80. pattern = strings.TrimSpace(pattern)
  81. if re, ok := slashRegex(pattern); ok {
  82. return re.MatchString(s)
  83. }
  84. if strings.Contains(pattern, "*") {
  85. parts := strings.Split(pattern, "*")
  86. for i := range parts {
  87. parts[i] = regexp.QuoteMeta(parts[i])
  88. }
  89. re, err := regexp.Compile("^" + strings.Join(parts, ".*") + "$")
  90. return err == nil && re.MatchString(s)
  91. }
  92. return pattern == s || strings.TrimSuffix(pattern, "/") == strings.TrimSuffix(s, "/")
  93. }
  94. // matchText: substring (case-insensitive) or /regex/; empty matches all.
  95. func matchText(pattern, s string) bool {
  96. if strings.TrimSpace(pattern) == "" {
  97. return true
  98. }
  99. if re, ok := slashRegex(pattern); ok {
  100. return re.MatchString(s)
  101. }
  102. return strings.Contains(strings.ToLower(s), strings.ToLower(pattern))
  103. }
  104. func slashRegex(p string) (*regexp.Regexp, bool) {
  105. if len(p) > 2 && strings.HasPrefix(p, "/") {
  106. if i := strings.LastIndex(p, "/"); i > 0 {
  107. flags := p[i+1:]
  108. expr := p[1:i]
  109. if strings.Contains(flags, "i") {
  110. expr = "(?i)" + expr
  111. }
  112. re, err := regexp.Compile(expr)
  113. if err == nil && strings.Trim(flags, "gimsuy") == "" {
  114. return re, true
  115. }
  116. }
  117. }
  118. return nil, false
  119. }
  120. func clip(s string, n int) string {
  121. if len(s) <= n {
  122. return s
  123. }
  124. cut := n
  125. for cut > 0 && !utf8.RuneStart(s[cut]) {
  126. cut--
  127. }
  128. return s[:cut] + fmt.Sprintf("... (%d bytes)", len(s))
  129. }
  130. // ---- http ----
  131. type httpOptions struct {
  132. URL string `json:"url"`
  133. Method string `json:"method"`
  134. Headers map[string]string `json:"headers"`
  135. Body string `json:"body"`
  136. BodyBase64 string `json:"bodyBase64"`
  137. Form map[string]string `json:"form"`
  138. JSON json.RawMessage `json:"json"`
  139. ContentType string `json:"contentType"`
  140. ResponseType string `json:"responseType"`
  141. }
  142. type httpResponse struct {
  143. Ok bool `json:"ok"`
  144. Status int `json:"status"`
  145. StatusText string `json:"statusText"`
  146. Headers map[string][]string `json:"headers"`
  147. Body string `json:"body"`
  148. Error string `json:"error"`
  149. raw []byte
  150. }
  151. var statusText = map[int]string{
  152. 200: "OK", 201: "Created", 202: "Accepted", 204: "No Content", 301: "Moved Permanently", 302: "Found",
  153. 304: "Not Modified", 307: "Temporary Redirect", 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized",
  154. 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 418: "I'm a teapot",
  155. 422: "Unprocessable Entity", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway",
  156. 503: "Service Unavailable", 504: "Gateway Timeout",
  157. }
  158. func canonicalHeader(k string) string {
  159. parts := strings.Split(strings.ToLower(k), "-")
  160. for i, p := range parts {
  161. if p != "" {
  162. parts[i] = strings.ToUpper(p[:1]) + p[1:]
  163. }
  164. }
  165. return strings.Join(parts, "-")
  166. }
  167. // doHTTP answers a request from the rules; fn names the AGI function for
  168. // the call log.
  169. func (r *run) doHTTP(fn string, opt httpOptions) httpResponse {
  170. method := strings.ToUpper(strings.TrimSpace(opt.Method))
  171. if method == "" {
  172. method = "GET"
  173. }
  174. body := opt.Body
  175. switch {
  176. case opt.BodyBase64 != "":
  177. b, _ := base64.StdEncoding.DecodeString(opt.BodyBase64)
  178. body = string(b)
  179. case len(opt.Form) > 0:
  180. body = encodeForm(opt.Form)
  181. case len(opt.JSON) > 0 && string(opt.JSON) != "null":
  182. body = string(opt.JSON)
  183. }
  184. args := method + " " + opt.URL
  185. if body != "" {
  186. args += "\n" + clip(body, 400)
  187. }
  188. if opt.URL == "" {
  189. resp := httpResponse{Error: "url is required"}
  190. r.call("http", fn, args, "error: "+resp.Error, "")
  191. return resp
  192. }
  193. if _, err := url.Parse(opt.URL); err != nil {
  194. resp := httpResponse{Error: err.Error()}
  195. r.call("http", fn, args, "error: "+resp.Error, "")
  196. return resp
  197. }
  198. for i, rule := range r.req.Mocks.HTTP.Rules {
  199. m := strings.ToUpper(strings.TrimSpace(rule.Method))
  200. if m != "" && m != "ANY" && m != method {
  201. continue
  202. }
  203. if !matchURL(rule.URL, opt.URL) {
  204. continue
  205. }
  206. name := rule.Name
  207. if name == "" {
  208. name = fmt.Sprintf("rule %d", i+1)
  209. }
  210. if rule.DelayMs > 0 {
  211. time.Sleep(time.Duration(rule.DelayMs) * time.Millisecond)
  212. }
  213. if rule.Error != "" {
  214. resp := httpResponse{Error: rule.Error}
  215. r.call("http", fn, args, "error: "+rule.Error, name)
  216. return resp
  217. }
  218. status := rule.Status
  219. if status == 0 {
  220. status = 200
  221. }
  222. text := strings.NewReplacer("{{method}}", method, "{{url}}", opt.URL, "{{body}}", body).Replace(rule.Body)
  223. raw := []byte(text)
  224. if rule.Base64 {
  225. if b, err := base64.StdEncoding.DecodeString(strings.TrimSpace(text)); err == nil {
  226. raw = b
  227. }
  228. }
  229. headers := map[string][]string{}
  230. for k, v := range rule.Headers {
  231. headers[canonicalHeader(k)] = []string{v}
  232. }
  233. if _, ok := headers["Content-Type"]; !ok {
  234. ct := "text/plain; charset=utf-8"
  235. if t := strings.TrimSpace(text); strings.HasPrefix(t, "{") || strings.HasPrefix(t, "[") {
  236. ct = "application/json"
  237. }
  238. if rule.Base64 {
  239. ct = "application/octet-stream"
  240. }
  241. headers["Content-Type"] = []string{ct}
  242. }
  243. resp := httpResponse{Ok: status >= 200 && status < 300, Status: status, StatusText: fmt.Sprintf("%d %s", status, statusText[status]), Headers: headers, raw: raw}
  244. if opt.ResponseType == "base64" {
  245. resp.Body = base64.StdEncoding.EncodeToString(raw)
  246. } else {
  247. resp.Body = string(raw)
  248. }
  249. r.call("http", fn, args, fmt.Sprintf("%d\n%s", status, clip(string(raw), 400)), name)
  250. return resp
  251. }
  252. if r.req.Mocks.HTTP.Fallback == "404" {
  253. resp := httpResponse{Status: 404, StatusText: "404 Not Found", Headers: map[string][]string{"Content-Type": {"text/plain; charset=utf-8"}}, Body: "404 page not found", raw: []byte("404 page not found")}
  254. r.call("http", fn, args, "404 (no rule)", "")
  255. return resp
  256. }
  257. msg := "the playground has no network: no mock answers " + method + " " + opt.URL + " (add one in the HTTP window)"
  258. r.call("http", fn, args, "error: no rule", "")
  259. r.log("agi", "warn", msg)
  260. return httpResponse{Error: msg}
  261. }
  262. func (r *run) injectHTTP(vm *otto.Otto) {
  263. vm.Set("_http_request", func(call otto.FunctionCall) otto.Value {
  264. opt := httpOptions{}
  265. s, _ := call.Argument(0).ToString()
  266. if s = strings.TrimSpace(s); s != "" && s != "undefined" && s != "null" {
  267. if err := json.Unmarshal([]byte(s), &opt); err != nil {
  268. return r.raise(vm, "HTTPError", errors.New("invalid request options: "+err.Error()))
  269. }
  270. }
  271. //A request that gets no reply throws; a reply with any status is
  272. //returned
  273. resp := r.doHTTP("request", opt)
  274. if resp.Error != "" {
  275. return r.raise(vm, "HTTPError", errors.New(resp.Error))
  276. }
  277. if resp.Headers == nil {
  278. resp.Headers = map[string][]string{}
  279. }
  280. out, _ := json.Marshal(resp)
  281. v, _ := vm.ToValue(string(out))
  282. return v
  283. })
  284. //simple sends a request for the one-call helpers and throws when it gets
  285. //no reply
  286. simple := func(fn, method string, call otto.FunctionCall) httpResponse {
  287. u, _ := call.Argument(0).ToString()
  288. opt := httpOptions{URL: u, Method: method}
  289. if method == "POST" {
  290. opt.Body = optString(call, 1)
  291. opt.ContentType = "application/json"
  292. }
  293. resp := r.doHTTP(fn, opt)
  294. if resp.Error != "" {
  295. r.raise(vm, "HTTPError", errors.New(resp.Error))
  296. }
  297. return resp
  298. }
  299. vm.Set("_http_get", func(call otto.FunctionCall) otto.Value {
  300. resp := simple("get", "GET", call)
  301. v, _ := vm.ToValue(string(resp.raw))
  302. return v
  303. })
  304. vm.Set("_http_post", func(call otto.FunctionCall) otto.Value {
  305. resp := simple("post", "POST", call)
  306. v, _ := vm.ToValue(string(resp.raw))
  307. return v
  308. })
  309. vm.Set("_http_head", func(call otto.FunctionCall) otto.Value {
  310. resp := simple("head", "GET", call)
  311. key, err := call.Argument(1).ToString()
  312. var b []byte
  313. if err != nil || key == "undefined" {
  314. b, _ = json.Marshal(resp.Headers)
  315. } else {
  316. val := ""
  317. if vs := resp.Headers[canonicalHeader(key)]; len(vs) > 0 {
  318. val = vs[0]
  319. }
  320. b, _ = json.Marshal(val)
  321. }
  322. v, _ := vm.ToValue(string(b))
  323. return v
  324. })
  325. vm.Set("_http_code", func(call otto.FunctionCall) otto.Value {
  326. resp := simple("getCode", "GET", call)
  327. loc := ""
  328. if vs := resp.Headers["Location"]; len(vs) > 0 && resp.Status >= 300 && resp.Status < 400 {
  329. loc = vs[0]
  330. }
  331. b, _ := json.Marshal(loc)
  332. vm.Run(`var _location = ` + string(b) + `;`)
  333. v, _ := vm.ToValue(resp.Status)
  334. return v
  335. })
  336. vm.Set("_http_download", func(call otto.FunctionCall) otto.Value {
  337. raw, _ := call.Argument(0).ToString()
  338. decoded, _ := url.QueryUnescape(raw)
  339. dir, _ := call.Argument(1).ToString()
  340. name, err := call.Argument(2).ToString()
  341. if err != nil || name == "undefined" {
  342. name = path.Base(decoded)
  343. if u, err := url.Parse(decoded); err == nil {
  344. name = path.Base(u.Path)
  345. }
  346. }
  347. if !r.canWrite(dir) {
  348. r.denied(vm, dir)
  349. }
  350. if !r.fs.IsDir(dir) {
  351. return r.raise(vm, "HTTPError", errors.New(dir+" is not a folder"))
  352. }
  353. resp := r.doHTTP("download", httpOptions{URL: decoded, Method: "GET"})
  354. if resp.Error != "" {
  355. return r.raise(vm, "HTTPError", errors.New(resp.Error))
  356. }
  357. if err := r.fs.WriteFile(Clean(dir+"/"+path.Base(name)), resp.raw); err != nil {
  358. return r.raise(vm, "HTTPError", err)
  359. }
  360. return otto.TrueValue()
  361. })
  362. vm.Set("_http_getb64", func(call otto.FunctionCall) otto.Value {
  363. resp := simple("getb64", "GET", call)
  364. v, _ := vm.ToValue(base64.StdEncoding.EncodeToString(resp.raw))
  365. return v
  366. })
  367. vm.Set("_http_redirect", func(call otto.FunctionCall) otto.Value {
  368. target, _ := call.Argument(0).ToString()
  369. code, err := call.Argument(1).ToInteger()
  370. if err != nil {
  371. code = 307
  372. }
  373. r.mu.Lock()
  374. r.headers["Location"] = target
  375. r.status = int(code)
  376. r.mu.Unlock()
  377. return otto.TrueValue()
  378. })
  379. vm.Run(`
  380. var http = {};
  381. http.request = function(options){
  382. return JSON.parse(_http_request(JSON.stringify(options || {})));
  383. };
  384. http.get = function(url, headers){
  385. if (typeof headers == "undefined"){
  386. return _http_get(url);
  387. }
  388. return http.request({url: url, method: "GET", headers: headers}).body;
  389. };
  390. http.post = function(url, body, headers, contentType){
  391. if (typeof headers == "undefined" && typeof contentType == "undefined"){
  392. return _http_post(url, body);
  393. }
  394. return http.request({
  395. url: url, method: "POST", body: body,
  396. headers: headers, contentType: contentType
  397. }).body;
  398. };
  399. http.put = function(url, body, headers, contentType){
  400. return http.request({url: url, method: "PUT", body: body, headers: headers, contentType: contentType});
  401. };
  402. http.patch = function(url, body, headers, contentType){
  403. return http.request({url: url, method: "PATCH", body: body, headers: headers, contentType: contentType});
  404. };
  405. http.delete = function(url, headers){
  406. return http.request({url: url, method: "DELETE", headers: headers});
  407. };
  408. http.postForm = function(url, form, headers){
  409. return http.request({url: url, method: "POST", form: form, headers: headers});
  410. };
  411. http.postJSON = function(url, obj, headers){
  412. return http.request({url: url, method: "POST", json: obj, headers: headers});
  413. };
  414. http.head = _http_head;
  415. http.download = _http_download;
  416. http.getb64 = _http_getb64;
  417. http.getCode = _http_code;
  418. http.redirect = function(t, c){
  419. if (typeof(c) == "undefined"){
  420. c = 307;
  421. }
  422. _http_redirect(t,c);
  423. };
  424. `)
  425. }
  426. // ---- llm ----
  427. type llmMessage struct {
  428. Role string `json:"role"`
  429. Content json.RawMessage `json:"content"`
  430. }
  431. type llmOptions struct {
  432. Model string `json:"model"`
  433. System string `json:"system"`
  434. }
  435. // text flattens a message's content (a string or OpenAI content parts).
  436. func (m llmMessage) text() string {
  437. var s string
  438. if json.Unmarshal(m.Content, &s) == nil {
  439. return s
  440. }
  441. var parts []map[string]interface{}
  442. if json.Unmarshal(m.Content, &parts) == nil {
  443. var out []string
  444. for _, p := range parts {
  445. if t, ok := p["text"].(string); ok {
  446. out = append(out, t)
  447. } else if p["type"] == "image_url" {
  448. out = append(out, "[image]")
  449. }
  450. }
  451. return strings.Join(out, "\n")
  452. }
  453. return string(m.Content)
  454. }
  455. const defaultLLMReply = "This is a mock reply from the playground. Set what the model answers in the LLM window."
  456. func tokens(s string) int { return (utf8.RuneCountInString(s) + 3) / 4 }
  457. // llmAnswer decides the mock reply and builds the response object.
  458. func (r *run) llmAnswer(fn string, msgs []llmMessage, opt llmOptions, vm *otto.Otto) map[string]interface{} {
  459. m := r.req.Mocks.LLM
  460. model := opt.Model
  461. if model == "" {
  462. model = m.Model
  463. }
  464. if model == "" {
  465. model = "mock-model"
  466. }
  467. var prompt, all string
  468. for _, msg := range msgs {
  469. t := msg.text()
  470. all += t + "\n"
  471. if msg.Role == "user" {
  472. prompt = t
  473. }
  474. }
  475. args := clip(prompt, 400)
  476. if m.Error != "" {
  477. r.call("llm", fn, args, "LLMError: "+m.Error, "LLM window")
  478. panic(vm.MakeCustomError("LLMError", m.Error))
  479. }
  480. reply, rule := m.Reply, "fixed reply"
  481. switch m.Mode {
  482. case "echo":
  483. reply, rule = "Echo: "+prompt, "echo"
  484. case "rules":
  485. rule = "fallback reply"
  486. for i, tr := range m.Rules {
  487. if matchText(tr.Match, prompt) {
  488. reply, rule = tr.Reply, fmt.Sprintf("rule %d", i+1)
  489. break
  490. }
  491. }
  492. }
  493. if reply == "" {
  494. reply = defaultLLMReply
  495. }
  496. reply = strings.NewReplacer("{{prompt}}", prompt, "{{model}}", model).Replace(reply)
  497. pt, ct := tokens(all), tokens(reply)+tokens(m.Reasoning)
  498. r.mu.Lock()
  499. r.state.LLMUsage.TotalTokens += int64(pt + ct)
  500. r.state.LLMUsage.TotalRequests++
  501. r.state.LLMUsage.PerModel[model] += int64(pt + ct)
  502. r.mu.Unlock()
  503. r.call("llm", fn, args, clip(reply, 400), rule)
  504. return map[string]interface{}{
  505. "id": "chatcmpl-" + newUUID()[:8], "object": "chat.completion", "created": time.Now().Unix(), "model": model,
  506. "choices": []map[string]interface{}{{
  507. "index": 0, "finish_reason": "stop",
  508. "message": map[string]interface{}{"role": "assistant", "content": reply, "reasoning_content": m.Reasoning},
  509. }},
  510. "usage": map[string]int{"prompt_tokens": pt, "completion_tokens": ct, "total_tokens": pt + ct},
  511. }
  512. }
  513. func (r *run) llmFileParts(vm *otto.Otto, script string, files []string) []map[string]interface{} {
  514. var parts []map[string]interface{}
  515. for _, f := range files {
  516. p := r.relPath(script, f)
  517. if !r.canRead(p) {
  518. r.denied(vm, p)
  519. }
  520. b, err := r.fs.ReadFile(p)
  521. if err != nil {
  522. panic(vm.MakeCustomError("LLMError", fsErr("open", p, err).Error()))
  523. }
  524. switch strings.ToLower(path.Ext(p)) {
  525. case ".png", ".jpg", ".jpeg", ".gif", ".webp":
  526. mime := "image/" + strings.TrimPrefix(strings.ToLower(path.Ext(p)), ".")
  527. if mime == "image/jpg" {
  528. mime = "image/jpeg"
  529. }
  530. parts = append(parts, map[string]interface{}{"type": "image_url", "image_url": map[string]string{"url": "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(b)}})
  531. default:
  532. parts = append(parts, map[string]interface{}{"type": "text", "text": "[File: " + path.Base(p) + "]\n" + string(b)})
  533. }
  534. }
  535. return parts
  536. }
  537. func (r *run) injectLLM(vm *otto.Otto, script string) {
  538. opts := func(call otto.FunctionCall, i int) llmOptions {
  539. var o llmOptions
  540. s, _ := call.Argument(i).ToString()
  541. json.Unmarshal([]byte(s), &o)
  542. return o
  543. }
  544. strList := func(call otto.FunctionCall, i int) []string {
  545. var list []string
  546. s, _ := call.Argument(i).ToString()
  547. json.Unmarshal([]byte(s), &list)
  548. return list
  549. }
  550. textMsg := func(role, text string) llmMessage {
  551. b, _ := json.Marshal(text)
  552. return llmMessage{Role: role, Content: b}
  553. }
  554. content := func(resp map[string]interface{}) string {
  555. return resp["choices"].([]map[string]interface{})[0]["message"].(map[string]interface{})["content"].(string)
  556. }
  557. vm.Set("_llm_chat", func(call otto.FunctionCall) otto.Value {
  558. prompt, _ := call.Argument(0).ToString()
  559. o := opts(call, 1)
  560. var msgs []llmMessage
  561. if strings.TrimSpace(o.System) != "" {
  562. msgs = append(msgs, textMsg("system", o.System))
  563. }
  564. msgs = append(msgs, textMsg("user", prompt))
  565. v, _ := vm.ToValue(content(r.llmAnswer("chat", msgs, o, vm)))
  566. return v
  567. })
  568. vm.Set("_llm_chatWithFile", func(call otto.FunctionCall) otto.Value {
  569. prompt, _ := call.Argument(0).ToString()
  570. parts := r.llmFileParts(vm, script, strList(call, 1))
  571. o := opts(call, 2)
  572. parts = append([]map[string]interface{}{{"type": "text", "text": prompt}}, parts...)
  573. b, _ := json.Marshal(parts)
  574. var msgs []llmMessage
  575. if strings.TrimSpace(o.System) != "" {
  576. msgs = append(msgs, textMsg("system", o.System))
  577. }
  578. msgs = append(msgs, llmMessage{Role: "user", Content: b})
  579. v, _ := vm.ToValue(content(r.llmAnswer("chatWithFile", msgs, o, vm)))
  580. return v
  581. })
  582. messages := func(call otto.FunctionCall) []llmMessage {
  583. var msgs []llmMessage
  584. s, _ := call.Argument(0).ToString()
  585. if err := json.Unmarshal([]byte(s), &msgs); err != nil {
  586. panic(vm.MakeCustomError("LLMError", "invalid messages array: "+err.Error()))
  587. }
  588. return msgs
  589. }
  590. vm.Set("_llm_request", func(call otto.FunctionCall) otto.Value {
  591. b, _ := json.Marshal(r.llmAnswer("request", messages(call), opts(call, 1), vm))
  592. v, _ := vm.ToValue(string(b))
  593. return v
  594. })
  595. vm.Set("_llm_streamRequest", func(call otto.FunctionCall) otto.Value {
  596. resp := r.llmAnswer("streamRequest", messages(call), opts(call, 1), vm)
  597. onDelta := call.Argument(2)
  598. m := r.req.Mocks.LLM
  599. size := m.ChunkSize
  600. if size <= 0 {
  601. size = 12
  602. }
  603. wait := time.Duration(m.ChunkDelayMs) * time.Millisecond
  604. if m.ChunkDelayMs == 0 {
  605. wait = 30 * time.Millisecond
  606. }
  607. emit := func(text, field string) {
  608. runes := []rune(text)
  609. for i := 0; i < len(runes); i += size {
  610. chunk := string(runes[i:min(i+size, len(runes))])
  611. if onDelta.IsFunction() {
  612. d := map[string]string{"content": "", "reasoning": ""}
  613. d[field] = chunk
  614. arg, _ := vm.ToValue(d)
  615. if _, err := onDelta.Call(otto.NullValue(), arg); err != nil {
  616. panic(err)
  617. }
  618. }
  619. time.Sleep(wait)
  620. }
  621. }
  622. emit(m.Reasoning, "reasoning")
  623. emit(content(resp), "content")
  624. b, _ := json.Marshal(resp)
  625. v, _ := vm.ToValue(string(b))
  626. return v
  627. })
  628. vm.Set("_llm_usage", func(call otto.FunctionCall) otto.Value {
  629. r.mu.Lock()
  630. u := r.state.LLMUsage
  631. per := map[string]interface{}{}
  632. for k, t := range u.PerModel {
  633. per[k] = map[string]interface{}{"tokens": t, "cost": 0}
  634. }
  635. b, _ := json.Marshal(map[string]interface{}{"totalTokens": u.TotalTokens, "totalCost": 0, "totalRequests": u.TotalRequests, "perModel": per, "currency": "USD"})
  636. r.mu.Unlock()
  637. v, _ := vm.ToValue(string(b))
  638. return v
  639. })
  640. models := func() (string, []string) {
  641. m := r.req.Mocks.LLM
  642. def := m.Model
  643. if def == "" {
  644. def = "mock-model"
  645. }
  646. list := m.Models
  647. if len(list) == 0 {
  648. list = []string{def}
  649. }
  650. return def, list
  651. }
  652. vm.Set("_llm_models", func(call otto.FunctionCall) otto.Value {
  653. def, list := models()
  654. b, _ := json.Marshal(map[string]interface{}{"default": def, "models": list})
  655. r.call("llm", "models", "", string(b), "LLM window")
  656. v, _ := vm.ToValue(string(b))
  657. return v
  658. })
  659. vm.Set("_llm_listModels", func(call otto.FunctionCall) otto.Value {
  660. _, list := models()
  661. b, _ := json.Marshal(map[string]interface{}{"models": list})
  662. r.call("llm", "listModels", "", string(b), "LLM window")
  663. v, _ := vm.ToValue(string(b))
  664. return v
  665. })
  666. vm.Set("_llm_fileParts", func(call otto.FunctionCall) otto.Value {
  667. b, _ := json.Marshal(r.llmFileParts(vm, script, strList(call, 0)))
  668. v, _ := vm.ToValue(string(b))
  669. return v
  670. })
  671. vm.Run(`
  672. var llm = {};
  673. llm.chat = function(prompt, options){
  674. return _llm_chat(prompt, JSON.stringify(options || {}));
  675. };
  676. llm.chatWithFile = function(prompt, files, options){
  677. if (typeof files === "string"){ files = [files]; }
  678. return _llm_chatWithFile(prompt, JSON.stringify(files || []), JSON.stringify(options || {}));
  679. };
  680. llm.request = function(messages, options){
  681. return JSON.parse(_llm_request(JSON.stringify(messages || []), JSON.stringify(options || {})));
  682. };
  683. llm.streamRequest = function(messages, options, onDelta){
  684. return JSON.parse(_llm_streamRequest(JSON.stringify(messages || []), JSON.stringify(options || {}), onDelta || null));
  685. };
  686. llm.usage = function(){ return JSON.parse(_llm_usage()); };
  687. llm.models = function(){ return JSON.parse(_llm_models()); };
  688. llm.listModels = function(){ return JSON.parse(_llm_listModels()); };
  689. llm.fileParts = function(files){
  690. if (typeof files === "string"){ files = [files]; }
  691. return JSON.parse(_llm_fileParts(JSON.stringify(files || [])));
  692. };
  693. `)
  694. }
  695. // ---- cnn ----
  696. // CNNDefaults are the answers the CNN window starts from, shaped like the
  697. // CXNNAIO server's envelopes.
  698. var CNNDefaults = map[string]string{
  699. "classify": `{"object":"classification","model":"mobilenet-v2","created":0,"image":{"width":640,"height":480},"timing_ms":{"preprocess":2.1,"inference":11.4,"postprocess":0.3},"data":[{"label":"tabby cat","index":281,"score":0.82},{"label":"tiger cat","index":282,"score":0.11},{"label":"Egyptian cat","index":285,"score":0.04}]}`,
  700. "detect": `{"object":"detection","model":"yolo11n","created":0,"image":{"width":640,"height":480},"timing_ms":{"inference":18.2},"data":[{"label":"person","class_id":0,"score":0.91,"box":{"x1":120,"y1":40,"x2":260,"y2":420}},{"label":"bicycle","class_id":1,"score":0.77,"box":{"x1":250,"y1":220,"x2":520,"y2":440}}]}`,
  701. "segment": `{"object":"segmentation","model":"yolo11n-seg","created":0,"image":{"width":640,"height":480},"data":[{"label":"person","class_id":0,"score":0.9,"box":{"x1":120,"y1":40,"x2":260,"y2":420},"polygon":[[120,40],[260,40],[260,420],[120,420]]}]}`,
  702. "pose": `{"object":"pose","model":"yolo11n-pose","created":0,"image":{"width":640,"height":480},"data":[{"score":0.88,"box":{"x1":120,"y1":40,"x2":260,"y2":420},"keypoints":[{"name":"nose","x":190,"y":80,"score":0.97},{"name":"left_shoulder","x":160,"y":140,"score":0.93},{"name":"right_shoulder","x":222,"y":141,"score":0.94}]}]}`,
  703. "oriented": `{"object":"oriented_detection","model":"yolo11n-obb","created":0,"image":{"width":640,"height":480},"data":[{"label":"plane","class_id":0,"score":0.8,"obb":{"cx":300,"cy":200,"w":120,"h":40,"angle":0.35}}]}`,
  704. "faceDetect": `{"object":"face_detection","model":"scrfd","created":0,"image":{"width":640,"height":480},"data":[{"score":0.98,"box":{"x1":210,"y1":90,"x2":330,"y2":250},"landmarks":[[245,150],[296,149],[271,180],[250,212],[292,211]]}]}`,
  705. "faceLandmarks": `{"object":"face_landmarks","model":"2d106det","created":0,"image":{"width":640,"height":480},"data":[{"box":{"x1":210,"y1":90,"x2":330,"y2":250},"landmarks":[[220,120],[228,140],[236,160]]}]}`,
  706. "faceEmbedding": `{"object":"face_embedding","model":"arcface","created":0,"image":{"width":640,"height":480},"data":[{"box":{"x1":210,"y1":90,"x2":330,"y2":250},"dim":512,"embedding":[0.021,-0.114,0.087,0.003,-0.052,0.131,-0.009,0.064]}]}`,
  707. "faceAttributes": `{"object":"face_attributes","model":"genderage","created":0,"image":{"width":640,"height":480},"data":[{"box":{"x1":210,"y1":90,"x2":330,"y2":250},"age":31,"gender":"female","gender_score":0.93}]}`,
  708. "faceCompare": `{"object":"face_compare","model":"arcface","similarity":0.72,"threshold":0.5,"same":true}`,
  709. "models": `{"object":"list","data":[{"id":"mobilenet-v2","object":"model","task":"classify","classes":1000,"input":[224,224]},{"id":"yolo11n","object":"model","task":"detect","classes":80,"input":[640,640]},{"id":"scrfd","object":"model","task":"faces","classes":1,"input":[640,640]}]}`,
  710. "health": `{"status":"ok","version":"playground","models_loaded":3,"sessions":1,"uptime_s":3600}`,
  711. }
  712. // analyzeTasks maps cnn.analyze task names to the functions whose answers
  713. // they reuse.
  714. var analyzeTasks = map[string]string{
  715. "classify": "classify", "detect": "detect", "segment": "segment", "pose": "pose", "oriented": "oriented",
  716. "faces": "faceDetect", "landmarks": "faceLandmarks", "attributes": "faceAttributes",
  717. }
  718. func (r *run) cnnAnswer(fn string) (json.RawMessage, string) {
  719. if s := strings.TrimSpace(r.req.Mocks.CNN.Responses[fn]); s != "" && json.Valid([]byte(s)) {
  720. return json.RawMessage(s), "CNN window"
  721. }
  722. return json.RawMessage(CNNDefaults[fn]), "default"
  723. }
  724. func (r *run) injectCNN(vm *otto.Otto, script string) {
  725. file := func(call otto.FunctionCall, i int) string {
  726. p, _ := argString(call, i)
  727. p = r.relPath(script, p)
  728. if !r.canRead(p) {
  729. r.denied(vm, p)
  730. }
  731. if !r.fs.Exists(p) || r.fs.IsDir(p) {
  732. panic(vm.MakeCustomError("CNNError", fsErr("open", p, errNotExist).Error()))
  733. }
  734. return p
  735. }
  736. fail := func(fn, args string) {
  737. if e := r.req.Mocks.CNN.Error; e != "" {
  738. r.call("cnn", fn, args, "CNNError: "+e, "CNN window")
  739. panic(vm.MakeCustomError("CNNError", e))
  740. }
  741. }
  742. finish := func(fn, args string, body json.RawMessage, rule string, async bool) otto.Value {
  743. if async {
  744. id := "job_" + newUUID()[:12]
  745. job, _ := json.Marshal(map[string]interface{}{"id": id, "object": "job", "status": "succeeded", "created": time.Now().Unix(), "result": body, "error": nil})
  746. r.mu.Lock()
  747. r.state.Jobs[id] = job
  748. r.mu.Unlock()
  749. body = job
  750. }
  751. r.call("cnn", fn, args, clip(string(body), 400), rule)
  752. v, _ := vm.ToValue(string(body))
  753. return v
  754. }
  755. asyncOpt := func(call otto.FunctionCall, i int) bool {
  756. var o struct {
  757. Async bool `json:"async"`
  758. }
  759. s, _ := call.Argument(i).ToString()
  760. json.Unmarshal([]byte(s), &o)
  761. return o.Async
  762. }
  763. for _, fn := range []string{"classify", "detect", "segment", "pose", "oriented", "faceDetect", "faceLandmarks", "faceEmbedding", "faceAttributes"} {
  764. fn := fn
  765. vm.Set("_cnn_"+fn, func(call otto.FunctionCall) otto.Value {
  766. p := file(call, 0)
  767. fail(fn, p)
  768. body, rule := r.cnnAnswer(fn)
  769. return finish(fn, p, body, rule, asyncOpt(call, 1))
  770. })
  771. }
  772. vm.Set("_cnn_faceCompare", func(call otto.FunctionCall) otto.Value {
  773. a, b := file(call, 0), file(call, 1)
  774. fail("faceCompare", a+", "+b)
  775. body, rule := r.cnnAnswer("faceCompare")
  776. return finish("faceCompare", a+", "+b, body, rule, false)
  777. })
  778. vm.Set("_cnn_analyze", func(call otto.FunctionCall) otto.Value {
  779. p := file(call, 0)
  780. var tasks []string
  781. s, _ := call.Argument(1).ToString()
  782. json.Unmarshal([]byte(s), &tasks)
  783. fail("analyze", p)
  784. results := map[string]json.RawMessage{}
  785. for _, t := range tasks {
  786. if fn, ok := analyzeTasks[t]; ok {
  787. results[t], _ = r.cnnAnswer(fn)
  788. }
  789. }
  790. body, _ := json.Marshal(map[string]interface{}{"object": "analysis", "created": time.Now().Unix(), "tasks": tasks, "results": results})
  791. return finish("analyze", p+" "+s, body, "per-task answers", asyncOpt(call, 2))
  792. })
  793. vm.Set("_cnn_job", func(call otto.FunctionCall) otto.Value {
  794. id, _ := call.Argument(0).ToString()
  795. r.mu.Lock()
  796. job, ok := r.state.Jobs[id]
  797. r.mu.Unlock()
  798. if !ok {
  799. panic(vm.MakeCustomError("CNNError", "job not found: "+id))
  800. }
  801. v, _ := vm.ToValue(string(job))
  802. return v
  803. })
  804. for _, fn := range []string{"models", "health"} {
  805. fn := fn
  806. vm.Set("_cnn_"+fn, func(call otto.FunctionCall) otto.Value {
  807. fail(fn, "")
  808. body, rule := r.cnnAnswer(fn)
  809. return finish(fn, "", body, rule, false)
  810. })
  811. }
  812. vm.Run(`
  813. var cnn = {};
  814. ["classify","detect","segment","pose","oriented","faceDetect","faceLandmarks","faceEmbedding","faceAttributes"].forEach(function(n){
  815. var native = this["_cnn_" + n];
  816. cnn[n] = function(file, options){ return JSON.parse(native(file, JSON.stringify(options || {}))); };
  817. }, this);
  818. cnn.faceCompare = function(fileA, fileB, options){
  819. return JSON.parse(_cnn_faceCompare(fileA, fileB, JSON.stringify(options || {})));
  820. };
  821. cnn.analyze = function(file, tasks, options){
  822. return JSON.parse(_cnn_analyze(file, JSON.stringify(tasks || []), JSON.stringify(options || {})));
  823. };
  824. cnn.job = function(id){ return JSON.parse(_cnn_job(id)); };
  825. cnn.models = function(){ return JSON.parse(_cnn_models()); };
  826. cnn.health = function(){ return JSON.parse(_cnn_health()); };
  827. `)
  828. }
  829. // ---- sqlite ----
  830. var sqliteDefaults = map[string]string{
  831. "exec": `{"lastInsertId":0,"rowsAffected":0}`, "query": `[]`, "queryRow": `null`, "tables": `[]`, "schema": `[]`,
  832. }
  833. func (r *run) injectSQLite(vm *otto.Otto, script string) {
  834. answer := func(fn, sql, db string) string {
  835. for i, rule := range r.req.Mocks.SQLite {
  836. if rule.Fn != fn || !matchText(rule.Match, sql) {
  837. continue
  838. }
  839. if json.Valid([]byte(rule.Result)) {
  840. r.call("sqlite", fn, db+": "+sql, clip(rule.Result, 400), fmt.Sprintf("rule %d", i+1))
  841. return rule.Result
  842. }
  843. }
  844. r.call("sqlite", fn, db+": "+sql, sqliteDefaults[fn], "default")
  845. return sqliteDefaults[fn]
  846. }
  847. vm.Set("_sqlite_open", func(call otto.FunctionCall) otto.Value {
  848. p, _ := argString(call, 0)
  849. p = r.relPath(script, p)
  850. if !r.canWrite(p) {
  851. r.denied(vm, p)
  852. }
  853. if !r.fs.Exists(p) {
  854. if err := r.fs.WriteFile(p, []byte("SQLite format 3\x00")); err != nil {
  855. panic(vm.MakeCustomError("SQLiteError", fsErr("open", p, err).Error()))
  856. }
  857. }
  858. v, _ := vm.ToValue(p)
  859. return v
  860. })
  861. vm.Set("_sqlite_call", func(call otto.FunctionCall) otto.Value {
  862. fn, _ := call.Argument(0).ToString()
  863. db, _ := call.Argument(1).ToString()
  864. sql, _ := call.Argument(2).ToString()
  865. v, _ := vm.ToValue(answer(fn, sql, db))
  866. return v
  867. })
  868. vm.Run(`
  869. var sqlite = {};
  870. sqlite.open = function(vpath){
  871. var handle = _sqlite_open(vpath);
  872. var closed = false;
  873. function q(fn, sql){
  874. if (closed) throw new Error("database is closed");
  875. return JSON.parse(_sqlite_call(fn, handle, sql || ""));
  876. }
  877. var db = {
  878. exec: function(sql, params){ return q("exec", sql); },
  879. query: function(sql, params){ return q("query", sql); },
  880. queryRow: function(sql, params){ return q("queryRow", sql); },
  881. tables: function(){ return q("tables", ""); },
  882. schema: function(table){ return q("schema", table); },
  883. transaction: function(fn){ return fn(db); },
  884. close: function(){ closed = true; return true; }
  885. };
  886. return db;
  887. };
  888. `)
  889. }
  890. // ---- libraries the playground cannot run ----
  891. // injectGeneric builds a library from its api.json function names; every
  892. // function returns the JSON set for it in the Services window (null when
  893. // none) and is recorded.
  894. func (r *run) injectGeneric(vm *otto.Otto, lib string, fns []string) {
  895. vm.Set("_mock_call", func(call otto.FunctionCall) otto.Value {
  896. name, _ := call.Argument(0).ToString()
  897. args, _ := call.Argument(1).ToString()
  898. ans := strings.TrimSpace(r.req.Mocks.Generic[name])
  899. rule := "Services window"
  900. if ans == "" || !json.Valid([]byte(ans)) {
  901. ans, rule = "null", "not set (null)"
  902. }
  903. dot := strings.Index(name, ".")
  904. r.call(name[:dot], name[dot+1:], clip(args, 400), clip(ans, 400), rule)
  905. v, _ := vm.ToValue(ans)
  906. return v
  907. })
  908. sort.Strings(fns)
  909. var js strings.Builder
  910. fmt.Fprintf(&js, "var %s = {};\n", lib)
  911. made := map[string]bool{lib: true}
  912. for _, full := range fns {
  913. parts := strings.Split(full, ".")
  914. for i := 2; i < len(parts); i++ {
  915. obj := strings.Join(parts[:i], ".")
  916. if !made[obj] {
  917. made[obj] = true
  918. fmt.Fprintf(&js, "%s = %s || {};\n", obj, obj)
  919. }
  920. }
  921. b, _ := json.Marshal(full)
  922. fmt.Fprintf(&js, "%s = function(){ return JSON.parse(_mock_call(%s, JSON.stringify(Array.prototype.slice.call(arguments)))); };\n", full, b)
  923. }
  924. if _, err := vm.Run(js.String()); err != nil {
  925. r.log("agi", "error", "could not build the "+lib+" mock: "+err.Error())
  926. }
  927. r.log("agi", "warn", lib+" is mocked in the playground: its functions return what the Services window sets")
  928. }