libmock.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. out, _ := json.Marshal(httpResponse{Error: "invalid request options: " + err.Error()})
  269. v, _ := vm.ToValue(string(out))
  270. return v
  271. }
  272. }
  273. resp := r.doHTTP("request", opt)
  274. if resp.Headers == nil {
  275. resp.Headers = map[string][]string{}
  276. }
  277. out, _ := json.Marshal(resp)
  278. v, _ := vm.ToValue(string(out))
  279. return v
  280. })
  281. simple := func(fn, method string, call otto.FunctionCall) (httpResponse, bool) {
  282. u, err := call.Argument(0).ToString()
  283. if err != nil {
  284. return httpResponse{}, false
  285. }
  286. opt := httpOptions{URL: u, Method: method}
  287. if method == "POST" {
  288. opt.Body, _ = call.Argument(1).ToString()
  289. opt.ContentType = "application/json"
  290. }
  291. resp := r.doHTTP(fn, opt)
  292. return resp, resp.Error == ""
  293. }
  294. vm.Set("_http_get", func(call otto.FunctionCall) otto.Value {
  295. resp, ok := simple("get", "GET", call)
  296. if !ok {
  297. return otto.NullValue()
  298. }
  299. v, _ := vm.ToValue(string(resp.raw))
  300. return v
  301. })
  302. vm.Set("_http_post", func(call otto.FunctionCall) otto.Value {
  303. resp, ok := simple("post", "POST", call)
  304. if !ok {
  305. return otto.NullValue()
  306. }
  307. v, _ := vm.ToValue(string(resp.raw))
  308. return v
  309. })
  310. vm.Set("_http_head", func(call otto.FunctionCall) otto.Value {
  311. resp, ok := simple("head", "GET", call)
  312. if !ok {
  313. return otto.NullValue()
  314. }
  315. key, err := call.Argument(1).ToString()
  316. var b []byte
  317. if err != nil || key == "undefined" {
  318. b, _ = json.Marshal(resp.Headers)
  319. } else {
  320. val := ""
  321. if vs := resp.Headers[canonicalHeader(key)]; len(vs) > 0 {
  322. val = vs[0]
  323. }
  324. b, _ = json.Marshal(val)
  325. }
  326. v, _ := vm.ToValue(string(b))
  327. return v
  328. })
  329. vm.Set("_http_code", func(call otto.FunctionCall) otto.Value {
  330. resp, ok := simple("getCode", "GET", call)
  331. if !ok {
  332. return otto.FalseValue()
  333. }
  334. loc := ""
  335. if vs := resp.Headers["Location"]; len(vs) > 0 && resp.Status >= 300 && resp.Status < 400 {
  336. loc = vs[0]
  337. }
  338. b, _ := json.Marshal(loc)
  339. vm.Run(`var _location = ` + string(b) + `;`)
  340. v, _ := vm.ToValue(resp.Status)
  341. return v
  342. })
  343. vm.Set("_http_download", func(call otto.FunctionCall) otto.Value {
  344. raw, _ := call.Argument(0).ToString()
  345. decoded, _ := url.QueryUnescape(raw)
  346. dir, _ := call.Argument(1).ToString()
  347. name, err := call.Argument(2).ToString()
  348. if err != nil || name == "undefined" {
  349. name = path.Base(decoded)
  350. if u, err := url.Parse(decoded); err == nil {
  351. name = path.Base(u.Path)
  352. }
  353. }
  354. if !r.canWrite(dir) {
  355. r.raise(errors.New("Permission Denied"))
  356. return otto.FalseValue()
  357. }
  358. if !r.fs.IsDir(dir) {
  359. r.raise(errors.New(dir + " is a file not a directory."))
  360. return otto.FalseValue()
  361. }
  362. resp := r.doHTTP("download", httpOptions{URL: decoded, Method: "GET"})
  363. if resp.Error != "" {
  364. return otto.FalseValue()
  365. }
  366. if err := r.fs.WriteFile(Clean(dir+"/"+name), resp.raw); err != nil {
  367. return otto.FalseValue()
  368. }
  369. return otto.TrueValue()
  370. })
  371. vm.Set("_http_getb64", func(call otto.FunctionCall) otto.Value {
  372. resp, ok := simple("getb64", "GET", call)
  373. if !ok {
  374. return otto.NullValue()
  375. }
  376. v, _ := vm.ToValue(base64.StdEncoding.EncodeToString(resp.raw))
  377. return v
  378. })
  379. vm.Set("_http_redirect", func(call otto.FunctionCall) otto.Value {
  380. target, err := call.Argument(0).ToString()
  381. if err != nil {
  382. return otto.NullValue()
  383. }
  384. code, err := call.Argument(1).ToInteger()
  385. if err != nil {
  386. code = 307
  387. }
  388. r.mu.Lock()
  389. r.headers["Location"] = target
  390. r.status = int(code)
  391. r.mu.Unlock()
  392. return otto.TrueValue()
  393. })
  394. vm.Run(`
  395. var http = {};
  396. http.request = function(options){
  397. return JSON.parse(_http_request(JSON.stringify(options || {})));
  398. };
  399. http.get = function(url, headers){
  400. if (typeof headers == "undefined"){
  401. return _http_get(url);
  402. }
  403. return http.request({url: url, method: "GET", headers: headers}).body;
  404. };
  405. http.post = function(url, body, headers, contentType){
  406. if (typeof headers == "undefined" && typeof contentType == "undefined"){
  407. return _http_post(url, body);
  408. }
  409. return http.request({
  410. url: url, method: "POST", body: body,
  411. headers: headers, contentType: contentType
  412. }).body;
  413. };
  414. http.put = function(url, body, headers, contentType){
  415. return http.request({url: url, method: "PUT", body: body, headers: headers, contentType: contentType});
  416. };
  417. http.patch = function(url, body, headers, contentType){
  418. return http.request({url: url, method: "PATCH", body: body, headers: headers, contentType: contentType});
  419. };
  420. http.delete = function(url, headers){
  421. return http.request({url: url, method: "DELETE", headers: headers});
  422. };
  423. http.postForm = function(url, form, headers){
  424. return http.request({url: url, method: "POST", form: form, headers: headers});
  425. };
  426. http.postJSON = function(url, obj, headers){
  427. return http.request({url: url, method: "POST", json: obj, headers: headers});
  428. };
  429. http.head = _http_head;
  430. http.download = _http_download;
  431. http.getb64 = _http_getb64;
  432. http.getCode = _http_code;
  433. http.redirect = function(t, c){
  434. if (typeof(c) == "undefined"){
  435. c = 307;
  436. }
  437. _http_redirect(t,c);
  438. };
  439. `)
  440. }
  441. // ---- llm ----
  442. type llmMessage struct {
  443. Role string `json:"role"`
  444. Content json.RawMessage `json:"content"`
  445. }
  446. type llmOptions struct {
  447. Model string `json:"model"`
  448. System string `json:"system"`
  449. }
  450. // text flattens a message's content (a string or OpenAI content parts).
  451. func (m llmMessage) text() string {
  452. var s string
  453. if json.Unmarshal(m.Content, &s) == nil {
  454. return s
  455. }
  456. var parts []map[string]interface{}
  457. if json.Unmarshal(m.Content, &parts) == nil {
  458. var out []string
  459. for _, p := range parts {
  460. if t, ok := p["text"].(string); ok {
  461. out = append(out, t)
  462. } else if p["type"] == "image_url" {
  463. out = append(out, "[image]")
  464. }
  465. }
  466. return strings.Join(out, "\n")
  467. }
  468. return string(m.Content)
  469. }
  470. const defaultLLMReply = "This is a mock reply from the playground. Set what the model answers in the LLM window."
  471. func tokens(s string) int { return (utf8.RuneCountInString(s) + 3) / 4 }
  472. // llmAnswer decides the mock reply and builds the response object.
  473. func (r *run) llmAnswer(fn string, msgs []llmMessage, opt llmOptions, vm *otto.Otto) map[string]interface{} {
  474. m := r.req.Mocks.LLM
  475. model := opt.Model
  476. if model == "" {
  477. model = m.Model
  478. }
  479. if model == "" {
  480. model = "mock-model"
  481. }
  482. var prompt, all string
  483. for _, msg := range msgs {
  484. t := msg.text()
  485. all += t + "\n"
  486. if msg.Role == "user" {
  487. prompt = t
  488. }
  489. }
  490. args := clip(prompt, 400)
  491. if m.Error != "" {
  492. r.call("llm", fn, args, "LLMError: "+m.Error, "LLM window")
  493. panic(vm.MakeCustomError("LLMError", m.Error))
  494. }
  495. reply, rule := m.Reply, "fixed reply"
  496. switch m.Mode {
  497. case "echo":
  498. reply, rule = "Echo: "+prompt, "echo"
  499. case "rules":
  500. rule = "fallback reply"
  501. for i, tr := range m.Rules {
  502. if matchText(tr.Match, prompt) {
  503. reply, rule = tr.Reply, fmt.Sprintf("rule %d", i+1)
  504. break
  505. }
  506. }
  507. }
  508. if reply == "" {
  509. reply = defaultLLMReply
  510. }
  511. reply = strings.NewReplacer("{{prompt}}", prompt, "{{model}}", model).Replace(reply)
  512. pt, ct := tokens(all), tokens(reply)+tokens(m.Reasoning)
  513. r.mu.Lock()
  514. r.state.LLMUsage.TotalTokens += int64(pt + ct)
  515. r.state.LLMUsage.TotalRequests++
  516. r.state.LLMUsage.PerModel[model] += int64(pt + ct)
  517. r.mu.Unlock()
  518. r.call("llm", fn, args, clip(reply, 400), rule)
  519. return map[string]interface{}{
  520. "id": "chatcmpl-" + newUUID()[:8], "object": "chat.completion", "created": time.Now().Unix(), "model": model,
  521. "choices": []map[string]interface{}{{
  522. "index": 0, "finish_reason": "stop",
  523. "message": map[string]interface{}{"role": "assistant", "content": reply, "reasoning_content": m.Reasoning},
  524. }},
  525. "usage": map[string]int{"prompt_tokens": pt, "completion_tokens": ct, "total_tokens": pt + ct},
  526. }
  527. }
  528. func (r *run) llmFileParts(vm *otto.Otto, script string, files []string) []map[string]interface{} {
  529. var parts []map[string]interface{}
  530. for _, f := range files {
  531. p := r.relPath(script, f)
  532. if !r.canRead(p) {
  533. denied(vm, "Path access denied: "+p)
  534. }
  535. b, err := r.fs.ReadFile(p)
  536. if err != nil {
  537. panic(vm.MakeCustomError("LLMError", fsErr("open", p, err).Error()))
  538. }
  539. switch strings.ToLower(path.Ext(p)) {
  540. case ".png", ".jpg", ".jpeg", ".gif", ".webp":
  541. mime := "image/" + strings.TrimPrefix(strings.ToLower(path.Ext(p)), ".")
  542. if mime == "image/jpg" {
  543. mime = "image/jpeg"
  544. }
  545. parts = append(parts, map[string]interface{}{"type": "image_url", "image_url": map[string]string{"url": "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(b)}})
  546. default:
  547. parts = append(parts, map[string]interface{}{"type": "text", "text": "[File: " + path.Base(p) + "]\n" + string(b)})
  548. }
  549. }
  550. return parts
  551. }
  552. func (r *run) injectLLM(vm *otto.Otto, script string) {
  553. opts := func(call otto.FunctionCall, i int) llmOptions {
  554. var o llmOptions
  555. s, _ := call.Argument(i).ToString()
  556. json.Unmarshal([]byte(s), &o)
  557. return o
  558. }
  559. strList := func(call otto.FunctionCall, i int) []string {
  560. var list []string
  561. s, _ := call.Argument(i).ToString()
  562. json.Unmarshal([]byte(s), &list)
  563. return list
  564. }
  565. textMsg := func(role, text string) llmMessage {
  566. b, _ := json.Marshal(text)
  567. return llmMessage{Role: role, Content: b}
  568. }
  569. content := func(resp map[string]interface{}) string {
  570. return resp["choices"].([]map[string]interface{})[0]["message"].(map[string]interface{})["content"].(string)
  571. }
  572. vm.Set("_llm_chat", func(call otto.FunctionCall) otto.Value {
  573. prompt, _ := call.Argument(0).ToString()
  574. o := opts(call, 1)
  575. var msgs []llmMessage
  576. if strings.TrimSpace(o.System) != "" {
  577. msgs = append(msgs, textMsg("system", o.System))
  578. }
  579. msgs = append(msgs, textMsg("user", prompt))
  580. v, _ := vm.ToValue(content(r.llmAnswer("chat", msgs, o, vm)))
  581. return v
  582. })
  583. vm.Set("_llm_chatWithFile", func(call otto.FunctionCall) otto.Value {
  584. prompt, _ := call.Argument(0).ToString()
  585. parts := r.llmFileParts(vm, script, strList(call, 1))
  586. o := opts(call, 2)
  587. parts = append([]map[string]interface{}{{"type": "text", "text": prompt}}, parts...)
  588. b, _ := json.Marshal(parts)
  589. var msgs []llmMessage
  590. if strings.TrimSpace(o.System) != "" {
  591. msgs = append(msgs, textMsg("system", o.System))
  592. }
  593. msgs = append(msgs, llmMessage{Role: "user", Content: b})
  594. v, _ := vm.ToValue(content(r.llmAnswer("chatWithFile", msgs, o, vm)))
  595. return v
  596. })
  597. messages := func(call otto.FunctionCall) []llmMessage {
  598. var msgs []llmMessage
  599. s, _ := call.Argument(0).ToString()
  600. if err := json.Unmarshal([]byte(s), &msgs); err != nil {
  601. panic(vm.MakeCustomError("LLMError", "invalid messages array: "+err.Error()))
  602. }
  603. return msgs
  604. }
  605. vm.Set("_llm_request", func(call otto.FunctionCall) otto.Value {
  606. b, _ := json.Marshal(r.llmAnswer("request", messages(call), opts(call, 1), vm))
  607. v, _ := vm.ToValue(string(b))
  608. return v
  609. })
  610. vm.Set("_llm_streamRequest", func(call otto.FunctionCall) otto.Value {
  611. resp := r.llmAnswer("streamRequest", messages(call), opts(call, 1), vm)
  612. onDelta := call.Argument(2)
  613. m := r.req.Mocks.LLM
  614. size := m.ChunkSize
  615. if size <= 0 {
  616. size = 12
  617. }
  618. wait := time.Duration(m.ChunkDelayMs) * time.Millisecond
  619. if m.ChunkDelayMs == 0 {
  620. wait = 30 * time.Millisecond
  621. }
  622. emit := func(text, field string) {
  623. runes := []rune(text)
  624. for i := 0; i < len(runes); i += size {
  625. chunk := string(runes[i:min(i+size, len(runes))])
  626. if onDelta.IsFunction() {
  627. d := map[string]string{"content": "", "reasoning": ""}
  628. d[field] = chunk
  629. arg, _ := vm.ToValue(d)
  630. if _, err := onDelta.Call(otto.NullValue(), arg); err != nil {
  631. panic(err)
  632. }
  633. }
  634. time.Sleep(wait)
  635. }
  636. }
  637. emit(m.Reasoning, "reasoning")
  638. emit(content(resp), "content")
  639. b, _ := json.Marshal(resp)
  640. v, _ := vm.ToValue(string(b))
  641. return v
  642. })
  643. vm.Set("_llm_usage", func(call otto.FunctionCall) otto.Value {
  644. r.mu.Lock()
  645. u := r.state.LLMUsage
  646. per := map[string]interface{}{}
  647. for k, t := range u.PerModel {
  648. per[k] = map[string]interface{}{"tokens": t, "cost": 0}
  649. }
  650. b, _ := json.Marshal(map[string]interface{}{"totalTokens": u.TotalTokens, "totalCost": 0, "totalRequests": u.TotalRequests, "perModel": per, "currency": "USD"})
  651. r.mu.Unlock()
  652. v, _ := vm.ToValue(string(b))
  653. return v
  654. })
  655. models := func() (string, []string) {
  656. m := r.req.Mocks.LLM
  657. def := m.Model
  658. if def == "" {
  659. def = "mock-model"
  660. }
  661. list := m.Models
  662. if len(list) == 0 {
  663. list = []string{def}
  664. }
  665. return def, list
  666. }
  667. vm.Set("_llm_models", func(call otto.FunctionCall) otto.Value {
  668. def, list := models()
  669. b, _ := json.Marshal(map[string]interface{}{"default": def, "models": list})
  670. r.call("llm", "models", "", string(b), "LLM window")
  671. v, _ := vm.ToValue(string(b))
  672. return v
  673. })
  674. vm.Set("_llm_listModels", func(call otto.FunctionCall) otto.Value {
  675. _, list := models()
  676. b, _ := json.Marshal(map[string]interface{}{"models": list})
  677. r.call("llm", "listModels", "", string(b), "LLM window")
  678. v, _ := vm.ToValue(string(b))
  679. return v
  680. })
  681. vm.Set("_llm_fileParts", func(call otto.FunctionCall) otto.Value {
  682. b, _ := json.Marshal(r.llmFileParts(vm, script, strList(call, 0)))
  683. v, _ := vm.ToValue(string(b))
  684. return v
  685. })
  686. vm.Run(`
  687. var llm = {};
  688. llm.chat = function(prompt, options){
  689. return _llm_chat(prompt, JSON.stringify(options || {}));
  690. };
  691. llm.chatWithFile = function(prompt, files, options){
  692. if (typeof files === "string"){ files = [files]; }
  693. return _llm_chatWithFile(prompt, JSON.stringify(files || []), JSON.stringify(options || {}));
  694. };
  695. llm.request = function(messages, options){
  696. return JSON.parse(_llm_request(JSON.stringify(messages || []), JSON.stringify(options || {})));
  697. };
  698. llm.streamRequest = function(messages, options, onDelta){
  699. return JSON.parse(_llm_streamRequest(JSON.stringify(messages || []), JSON.stringify(options || {}), onDelta || null));
  700. };
  701. llm.usage = function(){ return JSON.parse(_llm_usage()); };
  702. llm.models = function(){ return JSON.parse(_llm_models()); };
  703. llm.listModels = function(){ return JSON.parse(_llm_listModels()); };
  704. llm.fileParts = function(files){
  705. if (typeof files === "string"){ files = [files]; }
  706. return JSON.parse(_llm_fileParts(JSON.stringify(files || [])));
  707. };
  708. `)
  709. }
  710. // ---- cnn ----
  711. // CNNDefaults are the answers the CNN window starts from, shaped like the
  712. // CXNNAIO server's envelopes.
  713. var CNNDefaults = map[string]string{
  714. "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}]}`,
  715. "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}}]}`,
  716. "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]]}]}`,
  717. "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}]}]}`,
  718. "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}}]}`,
  719. "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]]}]}`,
  720. "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]]}]}`,
  721. "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]}]}`,
  722. "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}]}`,
  723. "faceCompare": `{"object":"face_compare","model":"arcface","similarity":0.72,"threshold":0.5,"same":true}`,
  724. "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]}]}`,
  725. "health": `{"status":"ok","version":"playground","models_loaded":3,"sessions":1,"uptime_s":3600}`,
  726. }
  727. // analyzeTasks maps cnn.analyze task names to the functions whose answers
  728. // they reuse.
  729. var analyzeTasks = map[string]string{
  730. "classify": "classify", "detect": "detect", "segment": "segment", "pose": "pose", "oriented": "oriented",
  731. "faces": "faceDetect", "landmarks": "faceLandmarks", "attributes": "faceAttributes",
  732. }
  733. func (r *run) cnnAnswer(fn string) (json.RawMessage, string) {
  734. if s := strings.TrimSpace(r.req.Mocks.CNN.Responses[fn]); s != "" && json.Valid([]byte(s)) {
  735. return json.RawMessage(s), "CNN window"
  736. }
  737. return json.RawMessage(CNNDefaults[fn]), "default"
  738. }
  739. func (r *run) injectCNN(vm *otto.Otto, script string) {
  740. file := func(call otto.FunctionCall, i int) string {
  741. p, _ := argString(call, i)
  742. p = r.relPath(script, p)
  743. if !r.canRead(p) {
  744. denied(vm, "Path access denied: "+p)
  745. }
  746. if !r.fs.Exists(p) || r.fs.IsDir(p) {
  747. panic(vm.MakeCustomError("CNNError", fsErr("open", p, errNotExist).Error()))
  748. }
  749. return p
  750. }
  751. fail := func(fn, args string) {
  752. if e := r.req.Mocks.CNN.Error; e != "" {
  753. r.call("cnn", fn, args, "CNNError: "+e, "CNN window")
  754. panic(vm.MakeCustomError("CNNError", e))
  755. }
  756. }
  757. finish := func(fn, args string, body json.RawMessage, rule string, async bool) otto.Value {
  758. if async {
  759. id := "job_" + newUUID()[:12]
  760. job, _ := json.Marshal(map[string]interface{}{"id": id, "object": "job", "status": "succeeded", "created": time.Now().Unix(), "result": body, "error": nil})
  761. r.mu.Lock()
  762. r.state.Jobs[id] = job
  763. r.mu.Unlock()
  764. body = job
  765. }
  766. r.call("cnn", fn, args, clip(string(body), 400), rule)
  767. v, _ := vm.ToValue(string(body))
  768. return v
  769. }
  770. asyncOpt := func(call otto.FunctionCall, i int) bool {
  771. var o struct {
  772. Async bool `json:"async"`
  773. }
  774. s, _ := call.Argument(i).ToString()
  775. json.Unmarshal([]byte(s), &o)
  776. return o.Async
  777. }
  778. for _, fn := range []string{"classify", "detect", "segment", "pose", "oriented", "faceDetect", "faceLandmarks", "faceEmbedding", "faceAttributes"} {
  779. fn := fn
  780. vm.Set("_cnn_"+fn, func(call otto.FunctionCall) otto.Value {
  781. p := file(call, 0)
  782. fail(fn, p)
  783. body, rule := r.cnnAnswer(fn)
  784. return finish(fn, p, body, rule, asyncOpt(call, 1))
  785. })
  786. }
  787. vm.Set("_cnn_faceCompare", func(call otto.FunctionCall) otto.Value {
  788. a, b := file(call, 0), file(call, 1)
  789. fail("faceCompare", a+", "+b)
  790. body, rule := r.cnnAnswer("faceCompare")
  791. return finish("faceCompare", a+", "+b, body, rule, false)
  792. })
  793. vm.Set("_cnn_analyze", func(call otto.FunctionCall) otto.Value {
  794. p := file(call, 0)
  795. var tasks []string
  796. s, _ := call.Argument(1).ToString()
  797. json.Unmarshal([]byte(s), &tasks)
  798. fail("analyze", p)
  799. results := map[string]json.RawMessage{}
  800. for _, t := range tasks {
  801. if fn, ok := analyzeTasks[t]; ok {
  802. results[t], _ = r.cnnAnswer(fn)
  803. }
  804. }
  805. body, _ := json.Marshal(map[string]interface{}{"object": "analysis", "created": time.Now().Unix(), "tasks": tasks, "results": results})
  806. return finish("analyze", p+" "+s, body, "per-task answers", asyncOpt(call, 2))
  807. })
  808. vm.Set("_cnn_job", func(call otto.FunctionCall) otto.Value {
  809. id, _ := call.Argument(0).ToString()
  810. r.mu.Lock()
  811. job, ok := r.state.Jobs[id]
  812. r.mu.Unlock()
  813. if !ok {
  814. panic(vm.MakeCustomError("CNNError", "job not found: "+id))
  815. }
  816. v, _ := vm.ToValue(string(job))
  817. return v
  818. })
  819. for _, fn := range []string{"models", "health"} {
  820. fn := fn
  821. vm.Set("_cnn_"+fn, func(call otto.FunctionCall) otto.Value {
  822. fail(fn, "")
  823. body, rule := r.cnnAnswer(fn)
  824. return finish(fn, "", body, rule, false)
  825. })
  826. }
  827. vm.Run(`
  828. var cnn = {};
  829. ["classify","detect","segment","pose","oriented","faceDetect","faceLandmarks","faceEmbedding","faceAttributes"].forEach(function(n){
  830. var native = this["_cnn_" + n];
  831. cnn[n] = function(file, options){ return JSON.parse(native(file, JSON.stringify(options || {}))); };
  832. }, this);
  833. cnn.faceCompare = function(fileA, fileB, options){
  834. return JSON.parse(_cnn_faceCompare(fileA, fileB, JSON.stringify(options || {})));
  835. };
  836. cnn.analyze = function(file, tasks, options){
  837. return JSON.parse(_cnn_analyze(file, JSON.stringify(tasks || []), JSON.stringify(options || {})));
  838. };
  839. cnn.job = function(id){ return JSON.parse(_cnn_job(id)); };
  840. cnn.models = function(){ return JSON.parse(_cnn_models()); };
  841. cnn.health = function(){ return JSON.parse(_cnn_health()); };
  842. `)
  843. }
  844. // ---- sqlite ----
  845. var sqliteDefaults = map[string]string{
  846. "exec": `{"lastInsertId":0,"rowsAffected":0}`, "query": `[]`, "queryRow": `null`, "tables": `[]`, "schema": `[]`,
  847. }
  848. func (r *run) injectSQLite(vm *otto.Otto, script string) {
  849. answer := func(fn, sql, db string) string {
  850. for i, rule := range r.req.Mocks.SQLite {
  851. if rule.Fn != fn || !matchText(rule.Match, sql) {
  852. continue
  853. }
  854. if json.Valid([]byte(rule.Result)) {
  855. r.call("sqlite", fn, db+": "+sql, clip(rule.Result, 400), fmt.Sprintf("rule %d", i+1))
  856. return rule.Result
  857. }
  858. }
  859. r.call("sqlite", fn, db+": "+sql, sqliteDefaults[fn], "default")
  860. return sqliteDefaults[fn]
  861. }
  862. vm.Set("_sqlite_open", func(call otto.FunctionCall) otto.Value {
  863. p, _ := argString(call, 0)
  864. p = r.relPath(script, p)
  865. if !r.canWrite(p) {
  866. denied(vm, "Path access denied: "+p)
  867. }
  868. if !r.fs.Exists(p) {
  869. if err := r.fs.WriteFile(p, []byte("SQLite format 3\x00")); err != nil {
  870. panic(vm.MakeCustomError("SQLiteError", fsErr("open", p, err).Error()))
  871. }
  872. }
  873. v, _ := vm.ToValue(p)
  874. return v
  875. })
  876. vm.Set("_sqlite_call", func(call otto.FunctionCall) otto.Value {
  877. fn, _ := call.Argument(0).ToString()
  878. db, _ := call.Argument(1).ToString()
  879. sql, _ := call.Argument(2).ToString()
  880. v, _ := vm.ToValue(answer(fn, sql, db))
  881. return v
  882. })
  883. vm.Run(`
  884. var sqlite = {};
  885. sqlite.open = function(vpath){
  886. var handle = _sqlite_open(vpath);
  887. var closed = false;
  888. function q(fn, sql){
  889. if (closed) throw new Error("database is closed");
  890. return JSON.parse(_sqlite_call(fn, handle, sql || ""));
  891. }
  892. var db = {
  893. exec: function(sql, params){ return q("exec", sql); },
  894. query: function(sql, params){ return q("query", sql); },
  895. queryRow: function(sql, params){ return q("queryRow", sql); },
  896. tables: function(){ return q("tables", ""); },
  897. schema: function(table){ return q("schema", table); },
  898. transaction: function(fn){ return fn(db); },
  899. close: function(){ closed = true; return true; }
  900. };
  901. return db;
  902. };
  903. `)
  904. }
  905. // ---- libraries the playground cannot run ----
  906. // injectGeneric builds a library from its api.json function names; every
  907. // function returns the JSON set for it in the Services window (null when
  908. // none) and is recorded.
  909. func (r *run) injectGeneric(vm *otto.Otto, lib string, fns []string) {
  910. vm.Set("_mock_call", func(call otto.FunctionCall) otto.Value {
  911. name, _ := call.Argument(0).ToString()
  912. args, _ := call.Argument(1).ToString()
  913. ans := strings.TrimSpace(r.req.Mocks.Generic[name])
  914. rule := "Services window"
  915. if ans == "" || !json.Valid([]byte(ans)) {
  916. ans, rule = "null", "not set (null)"
  917. }
  918. dot := strings.Index(name, ".")
  919. r.call(name[:dot], name[dot+1:], clip(args, 400), clip(ans, 400), rule)
  920. v, _ := vm.ToValue(ans)
  921. return v
  922. })
  923. sort.Strings(fns)
  924. var js strings.Builder
  925. fmt.Fprintf(&js, "var %s = {};\n", lib)
  926. made := map[string]bool{lib: true}
  927. for _, full := range fns {
  928. parts := strings.Split(full, ".")
  929. for i := 2; i < len(parts); i++ {
  930. obj := strings.Join(parts[:i], ".")
  931. if !made[obj] {
  932. made[obj] = true
  933. fmt.Fprintf(&js, "%s = %s || {};\n", obj, obj)
  934. }
  935. }
  936. b, _ := json.Marshal(full)
  937. fmt.Fprintf(&js, "%s = function(){ return JSON.parse(_mock_call(%s, JSON.stringify(Array.prototype.slice.call(arguments)))); };\n", full, b)
  938. }
  939. if _, err := vm.Run(js.String()); err != nil {
  940. r.log("agi", "error", "could not build the "+lib+" mock: "+err.Error())
  941. }
  942. r.log("agi", "warn", lib+" is mocked in the playground: its functions return what the Services window sets")
  943. }