| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968 |
- package playground
- import (
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "net/url"
- "path"
- "regexp"
- "sort"
- "strings"
- "time"
- "unicode/utf8"
- "github.com/robertkrimen/otto"
- )
- // Mocks hold the answers the page's tool windows set for services the
- // playground cannot reach.
- type Mocks struct {
- HTTP HTTPMock `json:"http"`
- LLM LLMMock `json:"llm"`
- CNN CNNMock `json:"cnn"`
- SQLite []SQLRule `json:"sqlite"`
- Sysinfo SysinfoMock `json:"sysinfo"`
- Generic map[string]string `json:"generic"` // "git.status" -> JSON it returns
- WS WSMock `json:"ws"`
- SchedulerDenied bool `json:"schedulerDenied"`
- }
- type HTTPMock struct {
- Rules []HTTPRule `json:"rules"`
- // Fallback answers a request no rule matches: "error" (the request
- // fails, as without network) or "404".
- Fallback string `json:"fallback"`
- }
- // HTTPRule answers requests whose method and URL match. URL is an exact URL,
- // a pattern with * wildcards, or a /regular expression/.
- type HTTPRule struct {
- Name string `json:"name"`
- Method string `json:"method"` // "" or "ANY" for every method
- URL string `json:"url"`
- Status int `json:"status"`
- Headers map[string]string `json:"headers"`
- Body string `json:"body"` // may use {{method}}, {{url}}, {{body}}
- Base64 bool `json:"base64"`
- Error string `json:"error"` // fail the request with this message
- DelayMs int `json:"delayMs"`
- }
- type LLMMock struct {
- Mode string `json:"mode"` // "fixed", "echo" or "rules"
- Reply string `json:"reply"`
- Reasoning string `json:"reasoning"`
- Rules []TextRule `json:"rules"`
- Error string `json:"error"`
- Model string `json:"model"`
- Models []string `json:"models"`
- ChunkSize int `json:"chunkSize"`
- ChunkDelayMs int `json:"chunkDelayMs"`
- }
- // TextRule matches text by substring (case-insensitive) or /regex/.
- type TextRule struct {
- Match string `json:"match"`
- Reply string `json:"reply"`
- }
- type CNNMock struct {
- Responses map[string]string `json:"responses"` // function -> JSON envelope
- Error string `json:"error"`
- }
- type SQLRule struct {
- Fn string `json:"fn"` // exec, query, queryRow, tables, schema
- Match string `json:"match"`
- Result string `json:"result"`
- }
- type SysinfoMock struct {
- CPU string `json:"cpu"`
- RAM string `json:"ram"`
- Network string `json:"network"`
- Disks string `json:"disks"`
- }
- // matchURL: exact, * wildcards or /regex/.
- func matchURL(pattern, s string) bool {
- pattern = strings.TrimSpace(pattern)
- if re, ok := slashRegex(pattern); ok {
- return re.MatchString(s)
- }
- if strings.Contains(pattern, "*") {
- parts := strings.Split(pattern, "*")
- for i := range parts {
- parts[i] = regexp.QuoteMeta(parts[i])
- }
- re, err := regexp.Compile("^" + strings.Join(parts, ".*") + "$")
- return err == nil && re.MatchString(s)
- }
- return pattern == s || strings.TrimSuffix(pattern, "/") == strings.TrimSuffix(s, "/")
- }
- // matchText: substring (case-insensitive) or /regex/; empty matches all.
- func matchText(pattern, s string) bool {
- if strings.TrimSpace(pattern) == "" {
- return true
- }
- if re, ok := slashRegex(pattern); ok {
- return re.MatchString(s)
- }
- return strings.Contains(strings.ToLower(s), strings.ToLower(pattern))
- }
- func slashRegex(p string) (*regexp.Regexp, bool) {
- if len(p) > 2 && strings.HasPrefix(p, "/") {
- if i := strings.LastIndex(p, "/"); i > 0 {
- flags := p[i+1:]
- expr := p[1:i]
- if strings.Contains(flags, "i") {
- expr = "(?i)" + expr
- }
- re, err := regexp.Compile(expr)
- if err == nil && strings.Trim(flags, "gimsuy") == "" {
- return re, true
- }
- }
- }
- return nil, false
- }
- func clip(s string, n int) string {
- if len(s) <= n {
- return s
- }
- cut := n
- for cut > 0 && !utf8.RuneStart(s[cut]) {
- cut--
- }
- return s[:cut] + fmt.Sprintf("... (%d bytes)", len(s))
- }
- // ---- http ----
- type httpOptions struct {
- URL string `json:"url"`
- Method string `json:"method"`
- Headers map[string]string `json:"headers"`
- Body string `json:"body"`
- BodyBase64 string `json:"bodyBase64"`
- Form map[string]string `json:"form"`
- JSON json.RawMessage `json:"json"`
- ContentType string `json:"contentType"`
- ResponseType string `json:"responseType"`
- }
- type httpResponse struct {
- Ok bool `json:"ok"`
- Status int `json:"status"`
- StatusText string `json:"statusText"`
- Headers map[string][]string `json:"headers"`
- Body string `json:"body"`
- Error string `json:"error"`
- raw []byte
- }
- var statusText = map[int]string{
- 200: "OK", 201: "Created", 202: "Accepted", 204: "No Content", 301: "Moved Permanently", 302: "Found",
- 304: "Not Modified", 307: "Temporary Redirect", 308: "Permanent Redirect", 400: "Bad Request", 401: "Unauthorized",
- 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 409: "Conflict", 418: "I'm a teapot",
- 422: "Unprocessable Entity", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway",
- 503: "Service Unavailable", 504: "Gateway Timeout",
- }
- func canonicalHeader(k string) string {
- parts := strings.Split(strings.ToLower(k), "-")
- for i, p := range parts {
- if p != "" {
- parts[i] = strings.ToUpper(p[:1]) + p[1:]
- }
- }
- return strings.Join(parts, "-")
- }
- // doHTTP answers a request from the rules; fn names the AGI function for
- // the call log.
- func (r *run) doHTTP(fn string, opt httpOptions) httpResponse {
- method := strings.ToUpper(strings.TrimSpace(opt.Method))
- if method == "" {
- method = "GET"
- }
- body := opt.Body
- switch {
- case opt.BodyBase64 != "":
- b, _ := base64.StdEncoding.DecodeString(opt.BodyBase64)
- body = string(b)
- case len(opt.Form) > 0:
- body = encodeForm(opt.Form)
- case len(opt.JSON) > 0 && string(opt.JSON) != "null":
- body = string(opt.JSON)
- }
- args := method + " " + opt.URL
- if body != "" {
- args += "\n" + clip(body, 400)
- }
- if opt.URL == "" {
- resp := httpResponse{Error: "url is required"}
- r.call("http", fn, args, "error: "+resp.Error, "")
- return resp
- }
- if _, err := url.Parse(opt.URL); err != nil {
- resp := httpResponse{Error: err.Error()}
- r.call("http", fn, args, "error: "+resp.Error, "")
- return resp
- }
- for i, rule := range r.req.Mocks.HTTP.Rules {
- m := strings.ToUpper(strings.TrimSpace(rule.Method))
- if m != "" && m != "ANY" && m != method {
- continue
- }
- if !matchURL(rule.URL, opt.URL) {
- continue
- }
- name := rule.Name
- if name == "" {
- name = fmt.Sprintf("rule %d", i+1)
- }
- if rule.DelayMs > 0 {
- time.Sleep(time.Duration(rule.DelayMs) * time.Millisecond)
- }
- if rule.Error != "" {
- resp := httpResponse{Error: rule.Error}
- r.call("http", fn, args, "error: "+rule.Error, name)
- return resp
- }
- status := rule.Status
- if status == 0 {
- status = 200
- }
- text := strings.NewReplacer("{{method}}", method, "{{url}}", opt.URL, "{{body}}", body).Replace(rule.Body)
- raw := []byte(text)
- if rule.Base64 {
- if b, err := base64.StdEncoding.DecodeString(strings.TrimSpace(text)); err == nil {
- raw = b
- }
- }
- headers := map[string][]string{}
- for k, v := range rule.Headers {
- headers[canonicalHeader(k)] = []string{v}
- }
- if _, ok := headers["Content-Type"]; !ok {
- ct := "text/plain; charset=utf-8"
- if t := strings.TrimSpace(text); strings.HasPrefix(t, "{") || strings.HasPrefix(t, "[") {
- ct = "application/json"
- }
- if rule.Base64 {
- ct = "application/octet-stream"
- }
- headers["Content-Type"] = []string{ct}
- }
- resp := httpResponse{Ok: status >= 200 && status < 300, Status: status, StatusText: fmt.Sprintf("%d %s", status, statusText[status]), Headers: headers, raw: raw}
- if opt.ResponseType == "base64" {
- resp.Body = base64.StdEncoding.EncodeToString(raw)
- } else {
- resp.Body = string(raw)
- }
- r.call("http", fn, args, fmt.Sprintf("%d\n%s", status, clip(string(raw), 400)), name)
- return resp
- }
- if r.req.Mocks.HTTP.Fallback == "404" {
- 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")}
- r.call("http", fn, args, "404 (no rule)", "")
- return resp
- }
- msg := "the playground has no network: no mock answers " + method + " " + opt.URL + " (add one in the HTTP window)"
- r.call("http", fn, args, "error: no rule", "")
- r.log("agi", "warn", msg)
- return httpResponse{Error: msg}
- }
- func (r *run) injectHTTP(vm *otto.Otto) {
- vm.Set("_http_request", func(call otto.FunctionCall) otto.Value {
- opt := httpOptions{}
- s, _ := call.Argument(0).ToString()
- if s = strings.TrimSpace(s); s != "" && s != "undefined" && s != "null" {
- if err := json.Unmarshal([]byte(s), &opt); err != nil {
- return r.raise(vm, "HTTPError", errors.New("invalid request options: "+err.Error()))
- }
- }
- //A request that gets no reply throws; a reply with any status is
- //returned
- resp := r.doHTTP("request", opt)
- if resp.Error != "" {
- return r.raise(vm, "HTTPError", errors.New(resp.Error))
- }
- if resp.Headers == nil {
- resp.Headers = map[string][]string{}
- }
- out, _ := json.Marshal(resp)
- v, _ := vm.ToValue(string(out))
- return v
- })
- //simple sends a request for the one-call helpers and throws when it gets
- //no reply
- simple := func(fn, method string, call otto.FunctionCall) httpResponse {
- u, _ := call.Argument(0).ToString()
- opt := httpOptions{URL: u, Method: method}
- if method == "POST" {
- opt.Body = optString(call, 1)
- opt.ContentType = "application/json"
- }
- resp := r.doHTTP(fn, opt)
- if resp.Error != "" {
- r.raise(vm, "HTTPError", errors.New(resp.Error))
- }
- return resp
- }
- vm.Set("_http_get", func(call otto.FunctionCall) otto.Value {
- resp := simple("get", "GET", call)
- v, _ := vm.ToValue(string(resp.raw))
- return v
- })
- vm.Set("_http_post", func(call otto.FunctionCall) otto.Value {
- resp := simple("post", "POST", call)
- v, _ := vm.ToValue(string(resp.raw))
- return v
- })
- vm.Set("_http_head", func(call otto.FunctionCall) otto.Value {
- resp := simple("head", "GET", call)
- key, err := call.Argument(1).ToString()
- var b []byte
- if err != nil || key == "undefined" {
- b, _ = json.Marshal(resp.Headers)
- } else {
- val := ""
- if vs := resp.Headers[canonicalHeader(key)]; len(vs) > 0 {
- val = vs[0]
- }
- b, _ = json.Marshal(val)
- }
- v, _ := vm.ToValue(string(b))
- return v
- })
- vm.Set("_http_code", func(call otto.FunctionCall) otto.Value {
- resp := simple("getCode", "GET", call)
- loc := ""
- if vs := resp.Headers["Location"]; len(vs) > 0 && resp.Status >= 300 && resp.Status < 400 {
- loc = vs[0]
- }
- b, _ := json.Marshal(loc)
- vm.Run(`var _location = ` + string(b) + `;`)
- v, _ := vm.ToValue(resp.Status)
- return v
- })
- vm.Set("_http_download", func(call otto.FunctionCall) otto.Value {
- raw, _ := call.Argument(0).ToString()
- decoded, _ := url.QueryUnescape(raw)
- dir, _ := call.Argument(1).ToString()
- name, err := call.Argument(2).ToString()
- if err != nil || name == "undefined" {
- name = path.Base(decoded)
- if u, err := url.Parse(decoded); err == nil {
- name = path.Base(u.Path)
- }
- }
- if !r.canWrite(dir) {
- r.denied(vm, dir)
- }
- if !r.fs.IsDir(dir) {
- return r.raise(vm, "HTTPError", errors.New(dir+" is not a folder"))
- }
- resp := r.doHTTP("download", httpOptions{URL: decoded, Method: "GET"})
- if resp.Error != "" {
- return r.raise(vm, "HTTPError", errors.New(resp.Error))
- }
- if err := r.fs.WriteFile(Clean(dir+"/"+path.Base(name)), resp.raw); err != nil {
- return r.raise(vm, "HTTPError", err)
- }
- return otto.TrueValue()
- })
- vm.Set("_http_getb64", func(call otto.FunctionCall) otto.Value {
- resp := simple("getb64", "GET", call)
- v, _ := vm.ToValue(base64.StdEncoding.EncodeToString(resp.raw))
- return v
- })
- vm.Set("_http_redirect", func(call otto.FunctionCall) otto.Value {
- target, _ := call.Argument(0).ToString()
- code, err := call.Argument(1).ToInteger()
- if err != nil {
- code = 307
- }
- r.mu.Lock()
- r.headers["Location"] = target
- r.status = int(code)
- r.mu.Unlock()
- return otto.TrueValue()
- })
- vm.Run(`
- var http = {};
- http.request = function(options){
- return JSON.parse(_http_request(JSON.stringify(options || {})));
- };
- http.get = function(url, headers){
- if (typeof headers == "undefined"){
- return _http_get(url);
- }
- return http.request({url: url, method: "GET", headers: headers}).body;
- };
- http.post = function(url, body, headers, contentType){
- if (typeof headers == "undefined" && typeof contentType == "undefined"){
- return _http_post(url, body);
- }
- return http.request({
- url: url, method: "POST", body: body,
- headers: headers, contentType: contentType
- }).body;
- };
- http.put = function(url, body, headers, contentType){
- return http.request({url: url, method: "PUT", body: body, headers: headers, contentType: contentType});
- };
- http.patch = function(url, body, headers, contentType){
- return http.request({url: url, method: "PATCH", body: body, headers: headers, contentType: contentType});
- };
- http.delete = function(url, headers){
- return http.request({url: url, method: "DELETE", headers: headers});
- };
- http.postForm = function(url, form, headers){
- return http.request({url: url, method: "POST", form: form, headers: headers});
- };
- http.postJSON = function(url, obj, headers){
- return http.request({url: url, method: "POST", json: obj, headers: headers});
- };
- http.head = _http_head;
- http.download = _http_download;
- http.getb64 = _http_getb64;
- http.getCode = _http_code;
- http.redirect = function(t, c){
- if (typeof(c) == "undefined"){
- c = 307;
- }
- _http_redirect(t,c);
- };
- `)
- }
- // ---- llm ----
- type llmMessage struct {
- Role string `json:"role"`
- Content json.RawMessage `json:"content"`
- }
- type llmOptions struct {
- Model string `json:"model"`
- System string `json:"system"`
- }
- // text flattens a message's content (a string or OpenAI content parts).
- func (m llmMessage) text() string {
- var s string
- if json.Unmarshal(m.Content, &s) == nil {
- return s
- }
- var parts []map[string]interface{}
- if json.Unmarshal(m.Content, &parts) == nil {
- var out []string
- for _, p := range parts {
- if t, ok := p["text"].(string); ok {
- out = append(out, t)
- } else if p["type"] == "image_url" {
- out = append(out, "[image]")
- }
- }
- return strings.Join(out, "\n")
- }
- return string(m.Content)
- }
- const defaultLLMReply = "This is a mock reply from the playground. Set what the model answers in the LLM window."
- func tokens(s string) int { return (utf8.RuneCountInString(s) + 3) / 4 }
- // llmAnswer decides the mock reply and builds the response object.
- func (r *run) llmAnswer(fn string, msgs []llmMessage, opt llmOptions, vm *otto.Otto) map[string]interface{} {
- m := r.req.Mocks.LLM
- model := opt.Model
- if model == "" {
- model = m.Model
- }
- if model == "" {
- model = "mock-model"
- }
- var prompt, all string
- for _, msg := range msgs {
- t := msg.text()
- all += t + "\n"
- if msg.Role == "user" {
- prompt = t
- }
- }
- args := clip(prompt, 400)
- if m.Error != "" {
- r.call("llm", fn, args, "LLMError: "+m.Error, "LLM window")
- panic(vm.MakeCustomError("LLMError", m.Error))
- }
- reply, rule := m.Reply, "fixed reply"
- switch m.Mode {
- case "echo":
- reply, rule = "Echo: "+prompt, "echo"
- case "rules":
- rule = "fallback reply"
- for i, tr := range m.Rules {
- if matchText(tr.Match, prompt) {
- reply, rule = tr.Reply, fmt.Sprintf("rule %d", i+1)
- break
- }
- }
- }
- if reply == "" {
- reply = defaultLLMReply
- }
- reply = strings.NewReplacer("{{prompt}}", prompt, "{{model}}", model).Replace(reply)
- pt, ct := tokens(all), tokens(reply)+tokens(m.Reasoning)
- r.mu.Lock()
- r.state.LLMUsage.TotalTokens += int64(pt + ct)
- r.state.LLMUsage.TotalRequests++
- r.state.LLMUsage.PerModel[model] += int64(pt + ct)
- r.mu.Unlock()
- r.call("llm", fn, args, clip(reply, 400), rule)
- return map[string]interface{}{
- "id": "chatcmpl-" + newUUID()[:8], "object": "chat.completion", "created": time.Now().Unix(), "model": model,
- "choices": []map[string]interface{}{{
- "index": 0, "finish_reason": "stop",
- "message": map[string]interface{}{"role": "assistant", "content": reply, "reasoning_content": m.Reasoning},
- }},
- "usage": map[string]int{"prompt_tokens": pt, "completion_tokens": ct, "total_tokens": pt + ct},
- }
- }
- func (r *run) llmFileParts(vm *otto.Otto, script string, files []string) []map[string]interface{} {
- var parts []map[string]interface{}
- for _, f := range files {
- p := r.relPath(script, f)
- if !r.canRead(p) {
- r.denied(vm, p)
- }
- b, err := r.fs.ReadFile(p)
- if err != nil {
- panic(vm.MakeCustomError("LLMError", fsErr("open", p, err).Error()))
- }
- switch strings.ToLower(path.Ext(p)) {
- case ".png", ".jpg", ".jpeg", ".gif", ".webp":
- mime := "image/" + strings.TrimPrefix(strings.ToLower(path.Ext(p)), ".")
- if mime == "image/jpg" {
- mime = "image/jpeg"
- }
- parts = append(parts, map[string]interface{}{"type": "image_url", "image_url": map[string]string{"url": "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(b)}})
- default:
- parts = append(parts, map[string]interface{}{"type": "text", "text": "[File: " + path.Base(p) + "]\n" + string(b)})
- }
- }
- return parts
- }
- func (r *run) injectLLM(vm *otto.Otto, script string) {
- opts := func(call otto.FunctionCall, i int) llmOptions {
- var o llmOptions
- s, _ := call.Argument(i).ToString()
- json.Unmarshal([]byte(s), &o)
- return o
- }
- strList := func(call otto.FunctionCall, i int) []string {
- var list []string
- s, _ := call.Argument(i).ToString()
- json.Unmarshal([]byte(s), &list)
- return list
- }
- textMsg := func(role, text string) llmMessage {
- b, _ := json.Marshal(text)
- return llmMessage{Role: role, Content: b}
- }
- content := func(resp map[string]interface{}) string {
- return resp["choices"].([]map[string]interface{})[0]["message"].(map[string]interface{})["content"].(string)
- }
- vm.Set("_llm_chat", func(call otto.FunctionCall) otto.Value {
- prompt, _ := call.Argument(0).ToString()
- o := opts(call, 1)
- var msgs []llmMessage
- if strings.TrimSpace(o.System) != "" {
- msgs = append(msgs, textMsg("system", o.System))
- }
- msgs = append(msgs, textMsg("user", prompt))
- v, _ := vm.ToValue(content(r.llmAnswer("chat", msgs, o, vm)))
- return v
- })
- vm.Set("_llm_chatWithFile", func(call otto.FunctionCall) otto.Value {
- prompt, _ := call.Argument(0).ToString()
- parts := r.llmFileParts(vm, script, strList(call, 1))
- o := opts(call, 2)
- parts = append([]map[string]interface{}{{"type": "text", "text": prompt}}, parts...)
- b, _ := json.Marshal(parts)
- var msgs []llmMessage
- if strings.TrimSpace(o.System) != "" {
- msgs = append(msgs, textMsg("system", o.System))
- }
- msgs = append(msgs, llmMessage{Role: "user", Content: b})
- v, _ := vm.ToValue(content(r.llmAnswer("chatWithFile", msgs, o, vm)))
- return v
- })
- messages := func(call otto.FunctionCall) []llmMessage {
- var msgs []llmMessage
- s, _ := call.Argument(0).ToString()
- if err := json.Unmarshal([]byte(s), &msgs); err != nil {
- panic(vm.MakeCustomError("LLMError", "invalid messages array: "+err.Error()))
- }
- return msgs
- }
- vm.Set("_llm_request", func(call otto.FunctionCall) otto.Value {
- b, _ := json.Marshal(r.llmAnswer("request", messages(call), opts(call, 1), vm))
- v, _ := vm.ToValue(string(b))
- return v
- })
- vm.Set("_llm_streamRequest", func(call otto.FunctionCall) otto.Value {
- resp := r.llmAnswer("streamRequest", messages(call), opts(call, 1), vm)
- onDelta := call.Argument(2)
- m := r.req.Mocks.LLM
- size := m.ChunkSize
- if size <= 0 {
- size = 12
- }
- wait := time.Duration(m.ChunkDelayMs) * time.Millisecond
- if m.ChunkDelayMs == 0 {
- wait = 30 * time.Millisecond
- }
- emit := func(text, field string) {
- runes := []rune(text)
- for i := 0; i < len(runes); i += size {
- chunk := string(runes[i:min(i+size, len(runes))])
- if onDelta.IsFunction() {
- d := map[string]string{"content": "", "reasoning": ""}
- d[field] = chunk
- arg, _ := vm.ToValue(d)
- if _, err := onDelta.Call(otto.NullValue(), arg); err != nil {
- panic(err)
- }
- }
- time.Sleep(wait)
- }
- }
- emit(m.Reasoning, "reasoning")
- emit(content(resp), "content")
- b, _ := json.Marshal(resp)
- v, _ := vm.ToValue(string(b))
- return v
- })
- vm.Set("_llm_usage", func(call otto.FunctionCall) otto.Value {
- r.mu.Lock()
- u := r.state.LLMUsage
- per := map[string]interface{}{}
- for k, t := range u.PerModel {
- per[k] = map[string]interface{}{"tokens": t, "cost": 0}
- }
- b, _ := json.Marshal(map[string]interface{}{"totalTokens": u.TotalTokens, "totalCost": 0, "totalRequests": u.TotalRequests, "perModel": per, "currency": "USD"})
- r.mu.Unlock()
- v, _ := vm.ToValue(string(b))
- return v
- })
- models := func() (string, []string) {
- m := r.req.Mocks.LLM
- def := m.Model
- if def == "" {
- def = "mock-model"
- }
- list := m.Models
- if len(list) == 0 {
- list = []string{def}
- }
- return def, list
- }
- vm.Set("_llm_models", func(call otto.FunctionCall) otto.Value {
- def, list := models()
- b, _ := json.Marshal(map[string]interface{}{"default": def, "models": list})
- r.call("llm", "models", "", string(b), "LLM window")
- v, _ := vm.ToValue(string(b))
- return v
- })
- vm.Set("_llm_listModels", func(call otto.FunctionCall) otto.Value {
- _, list := models()
- b, _ := json.Marshal(map[string]interface{}{"models": list})
- r.call("llm", "listModels", "", string(b), "LLM window")
- v, _ := vm.ToValue(string(b))
- return v
- })
- vm.Set("_llm_fileParts", func(call otto.FunctionCall) otto.Value {
- b, _ := json.Marshal(r.llmFileParts(vm, script, strList(call, 0)))
- v, _ := vm.ToValue(string(b))
- return v
- })
- vm.Run(`
- var llm = {};
- llm.chat = function(prompt, options){
- return _llm_chat(prompt, JSON.stringify(options || {}));
- };
- llm.chatWithFile = function(prompt, files, options){
- if (typeof files === "string"){ files = [files]; }
- return _llm_chatWithFile(prompt, JSON.stringify(files || []), JSON.stringify(options || {}));
- };
- llm.request = function(messages, options){
- return JSON.parse(_llm_request(JSON.stringify(messages || []), JSON.stringify(options || {})));
- };
- llm.streamRequest = function(messages, options, onDelta){
- return JSON.parse(_llm_streamRequest(JSON.stringify(messages || []), JSON.stringify(options || {}), onDelta || null));
- };
- llm.usage = function(){ return JSON.parse(_llm_usage()); };
- llm.models = function(){ return JSON.parse(_llm_models()); };
- llm.listModels = function(){ return JSON.parse(_llm_listModels()); };
- llm.fileParts = function(files){
- if (typeof files === "string"){ files = [files]; }
- return JSON.parse(_llm_fileParts(JSON.stringify(files || [])));
- };
- `)
- }
- // ---- cnn ----
- // CNNDefaults are the answers the CNN window starts from, shaped like the
- // CXNNAIO server's envelopes.
- var CNNDefaults = map[string]string{
- "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}]}`,
- "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}}]}`,
- "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]]}]}`,
- "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}]}]}`,
- "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}}]}`,
- "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]]}]}`,
- "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]]}]}`,
- "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]}]}`,
- "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}]}`,
- "faceCompare": `{"object":"face_compare","model":"arcface","similarity":0.72,"threshold":0.5,"same":true}`,
- "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]}]}`,
- "health": `{"status":"ok","version":"playground","models_loaded":3,"sessions":1,"uptime_s":3600}`,
- }
- // analyzeTasks maps cnn.analyze task names to the functions whose answers
- // they reuse.
- var analyzeTasks = map[string]string{
- "classify": "classify", "detect": "detect", "segment": "segment", "pose": "pose", "oriented": "oriented",
- "faces": "faceDetect", "landmarks": "faceLandmarks", "attributes": "faceAttributes",
- }
- func (r *run) cnnAnswer(fn string) (json.RawMessage, string) {
- if s := strings.TrimSpace(r.req.Mocks.CNN.Responses[fn]); s != "" && json.Valid([]byte(s)) {
- return json.RawMessage(s), "CNN window"
- }
- return json.RawMessage(CNNDefaults[fn]), "default"
- }
- func (r *run) injectCNN(vm *otto.Otto, script string) {
- file := func(call otto.FunctionCall, i int) string {
- p, _ := argString(call, i)
- p = r.relPath(script, p)
- if !r.canRead(p) {
- r.denied(vm, p)
- }
- if !r.fs.Exists(p) || r.fs.IsDir(p) {
- panic(vm.MakeCustomError("CNNError", fsErr("open", p, errNotExist).Error()))
- }
- return p
- }
- fail := func(fn, args string) {
- if e := r.req.Mocks.CNN.Error; e != "" {
- r.call("cnn", fn, args, "CNNError: "+e, "CNN window")
- panic(vm.MakeCustomError("CNNError", e))
- }
- }
- finish := func(fn, args string, body json.RawMessage, rule string, async bool) otto.Value {
- if async {
- id := "job_" + newUUID()[:12]
- job, _ := json.Marshal(map[string]interface{}{"id": id, "object": "job", "status": "succeeded", "created": time.Now().Unix(), "result": body, "error": nil})
- r.mu.Lock()
- r.state.Jobs[id] = job
- r.mu.Unlock()
- body = job
- }
- r.call("cnn", fn, args, clip(string(body), 400), rule)
- v, _ := vm.ToValue(string(body))
- return v
- }
- asyncOpt := func(call otto.FunctionCall, i int) bool {
- var o struct {
- Async bool `json:"async"`
- }
- s, _ := call.Argument(i).ToString()
- json.Unmarshal([]byte(s), &o)
- return o.Async
- }
- for _, fn := range []string{"classify", "detect", "segment", "pose", "oriented", "faceDetect", "faceLandmarks", "faceEmbedding", "faceAttributes"} {
- fn := fn
- vm.Set("_cnn_"+fn, func(call otto.FunctionCall) otto.Value {
- p := file(call, 0)
- fail(fn, p)
- body, rule := r.cnnAnswer(fn)
- return finish(fn, p, body, rule, asyncOpt(call, 1))
- })
- }
- vm.Set("_cnn_faceCompare", func(call otto.FunctionCall) otto.Value {
- a, b := file(call, 0), file(call, 1)
- fail("faceCompare", a+", "+b)
- body, rule := r.cnnAnswer("faceCompare")
- return finish("faceCompare", a+", "+b, body, rule, false)
- })
- vm.Set("_cnn_analyze", func(call otto.FunctionCall) otto.Value {
- p := file(call, 0)
- var tasks []string
- s, _ := call.Argument(1).ToString()
- json.Unmarshal([]byte(s), &tasks)
- fail("analyze", p)
- results := map[string]json.RawMessage{}
- for _, t := range tasks {
- if fn, ok := analyzeTasks[t]; ok {
- results[t], _ = r.cnnAnswer(fn)
- }
- }
- body, _ := json.Marshal(map[string]interface{}{"object": "analysis", "created": time.Now().Unix(), "tasks": tasks, "results": results})
- return finish("analyze", p+" "+s, body, "per-task answers", asyncOpt(call, 2))
- })
- vm.Set("_cnn_job", func(call otto.FunctionCall) otto.Value {
- id, _ := call.Argument(0).ToString()
- r.mu.Lock()
- job, ok := r.state.Jobs[id]
- r.mu.Unlock()
- if !ok {
- panic(vm.MakeCustomError("CNNError", "job not found: "+id))
- }
- v, _ := vm.ToValue(string(job))
- return v
- })
- for _, fn := range []string{"models", "health"} {
- fn := fn
- vm.Set("_cnn_"+fn, func(call otto.FunctionCall) otto.Value {
- fail(fn, "")
- body, rule := r.cnnAnswer(fn)
- return finish(fn, "", body, rule, false)
- })
- }
- vm.Run(`
- var cnn = {};
- ["classify","detect","segment","pose","oriented","faceDetect","faceLandmarks","faceEmbedding","faceAttributes"].forEach(function(n){
- var native = this["_cnn_" + n];
- cnn[n] = function(file, options){ return JSON.parse(native(file, JSON.stringify(options || {}))); };
- }, this);
- cnn.faceCompare = function(fileA, fileB, options){
- return JSON.parse(_cnn_faceCompare(fileA, fileB, JSON.stringify(options || {})));
- };
- cnn.analyze = function(file, tasks, options){
- return JSON.parse(_cnn_analyze(file, JSON.stringify(tasks || []), JSON.stringify(options || {})));
- };
- cnn.job = function(id){ return JSON.parse(_cnn_job(id)); };
- cnn.models = function(){ return JSON.parse(_cnn_models()); };
- cnn.health = function(){ return JSON.parse(_cnn_health()); };
- `)
- }
- // ---- sqlite ----
- var sqliteDefaults = map[string]string{
- "exec": `{"lastInsertId":0,"rowsAffected":0}`, "query": `[]`, "queryRow": `null`, "tables": `[]`, "schema": `[]`,
- }
- func (r *run) injectSQLite(vm *otto.Otto, script string) {
- answer := func(fn, sql, db string) string {
- for i, rule := range r.req.Mocks.SQLite {
- if rule.Fn != fn || !matchText(rule.Match, sql) {
- continue
- }
- if json.Valid([]byte(rule.Result)) {
- r.call("sqlite", fn, db+": "+sql, clip(rule.Result, 400), fmt.Sprintf("rule %d", i+1))
- return rule.Result
- }
- }
- r.call("sqlite", fn, db+": "+sql, sqliteDefaults[fn], "default")
- return sqliteDefaults[fn]
- }
- vm.Set("_sqlite_open", func(call otto.FunctionCall) otto.Value {
- p, _ := argString(call, 0)
- p = r.relPath(script, p)
- if !r.canWrite(p) {
- r.denied(vm, p)
- }
- if !r.fs.Exists(p) {
- if err := r.fs.WriteFile(p, []byte("SQLite format 3\x00")); err != nil {
- panic(vm.MakeCustomError("SQLiteError", fsErr("open", p, err).Error()))
- }
- }
- v, _ := vm.ToValue(p)
- return v
- })
- vm.Set("_sqlite_call", func(call otto.FunctionCall) otto.Value {
- fn, _ := call.Argument(0).ToString()
- db, _ := call.Argument(1).ToString()
- sql, _ := call.Argument(2).ToString()
- v, _ := vm.ToValue(answer(fn, sql, db))
- return v
- })
- vm.Run(`
- var sqlite = {};
- sqlite.open = function(vpath){
- var handle = _sqlite_open(vpath);
- var closed = false;
- function q(fn, sql){
- if (closed) throw new Error("database is closed");
- return JSON.parse(_sqlite_call(fn, handle, sql || ""));
- }
- var db = {
- exec: function(sql, params){ return q("exec", sql); },
- query: function(sql, params){ return q("query", sql); },
- queryRow: function(sql, params){ return q("queryRow", sql); },
- tables: function(){ return q("tables", ""); },
- schema: function(table){ return q("schema", table); },
- transaction: function(fn){ return fn(db); },
- close: function(){ closed = true; return true; }
- };
- return db;
- };
- `)
- }
- // ---- libraries the playground cannot run ----
- // injectGeneric builds a library from its api.json function names; every
- // function returns the JSON set for it in the Services window (null when
- // none) and is recorded.
- func (r *run) injectGeneric(vm *otto.Otto, lib string, fns []string) {
- vm.Set("_mock_call", func(call otto.FunctionCall) otto.Value {
- name, _ := call.Argument(0).ToString()
- args, _ := call.Argument(1).ToString()
- ans := strings.TrimSpace(r.req.Mocks.Generic[name])
- rule := "Services window"
- if ans == "" || !json.Valid([]byte(ans)) {
- ans, rule = "null", "not set (null)"
- }
- dot := strings.Index(name, ".")
- r.call(name[:dot], name[dot+1:], clip(args, 400), clip(ans, 400), rule)
- v, _ := vm.ToValue(ans)
- return v
- })
- sort.Strings(fns)
- var js strings.Builder
- fmt.Fprintf(&js, "var %s = {};\n", lib)
- made := map[string]bool{lib: true}
- for _, full := range fns {
- parts := strings.Split(full, ".")
- for i := 2; i < len(parts); i++ {
- obj := strings.Join(parts[:i], ".")
- if !made[obj] {
- made[obj] = true
- fmt.Fprintf(&js, "%s = %s || {};\n", obj, obj)
- }
- }
- b, _ := json.Marshal(full)
- fmt.Fprintf(&js, "%s = function(){ return JSON.parse(_mock_call(%s, JSON.stringify(Array.prototype.slice.call(arguments)))); };\n", full, b)
- }
- if _, err := vm.Run(js.String()); err != nil {
- r.log("agi", "error", "could not build the "+lib+" mock: "+err.Error())
- }
- r.log("agi", "warn", lib+" is mocked in the playground: its functions return what the Services window sets")
- }
|