Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(computer): carry a script's read tokens into the next script

jeffreyea549954ddba
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md
index e4147743..0a7d3b22 100644
--- a/apps/computer/local-daemon/README.md
+++ b/apps/computer/local-daemon/README.md
@@ -383,6 +383,8 @@ settles, since the browser shows such a tab a moment later. Reading the tab
strip replaces Cua's snapshot of the window, so the Daemon remembers the rows
of recent reads and moves an Agent's element token, in an input or written
into a script, to the current snapshot when its row reads the same there.
+A script's reads after its last input count too: the script guard returns
+them beside the script's value, and the Daemon takes them out of the result.
Only the window
the task opened with `launch_app` is held. A script that names no window in
its `args` is taken to drive that window; a script to another app is neither
diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua.go b/apps/computer/local-daemon/internal/linger/localtools/cua.go
index afc52b4a..7147f9ec 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/cua.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/cua.go
@@ -542,8 +542,17 @@ func (c *cuaSession) call(ctx context.Context, name string, args json.RawMessage
}
driverStarted := time.Now()
result, err := c.sendInput(ctx, name, arguments, appKeys, agentChrome)
+ var scriptReads []windowRead
+ if err == nil && name == "run_script" {
+ result, scriptReads = scriptResultReads(result)
+ }
if c.snapshots != nil {
c.snapshots.sent(name)
+ // The script's reads after its last input come after the fence, so
+ // their tokens carry over the Computer's reads before the next call.
+ for _, read := range scriptReads {
+ c.snapshots.record(read)
+ }
}
driverMs = time.Since(driverStarted).Milliseconds()
if err == nil {
diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script.go
index d115f460..5efeb152 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script.go
@@ -1,6 +1,7 @@
package localtools
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
@@ -67,7 +68,9 @@ var scriptForbidden = []string{"delivery_mode", "foreground", "screenshot_out_fi
// script, in Unix milliseconds, so it can refuse an input whose result it
// could not verify in time. A script reads text, so getState takes no
// screenshot unless the script asks for one: Cua's default captures one per
-// read, which took seconds on a busy page. A positive inputLimit paces the script for the
+// read, which took seconds on a busy page. The guard returns the window reads
+// made after the script's last input beside its value, under scriptReadsKey,
+// for scriptResultReads to take out. A positive inputLimit paces the script for the
// Computer's own browser: the guard waits a person's pause before each input,
// throws once the script tries to send more than inputLimit inputs, and
// refuses to open an app or URL, whose site checks run only in the Daemon's
@@ -85,10 +88,12 @@ func guardedScript(args, body string, deadline int64, inputLimit int, chrome int
source, _ := json.Marshal(`"use strict"; ` + body + "\n")
return strings.ReplaceAll(`const args = Object.freeze(`+args+`), DEADLINE = `+strconv.FormatInt(deadline, 10)+`; const __guarded = (() => {
const keys = Object.keys, names = Object.getOwnPropertyNames, proto = Object.getPrototypeOf, define = Object.defineProperty, freeze = Object.freeze;
-const apply = Reflect.apply, stringify = JSON.stringify, parse = JSON.parse, test = RegExp.prototype.test, then = Promise.prototype.then;
+const apply = Reflect.apply, stringify = JSON.stringify, parse = JSON.parse, test = RegExp.prototype.test, then = Promise.prototype.then, slice = Array.prototype.slice;
const plainProtos = [Object.prototype, Array.prototype, null], real = globalThis.cua;
const bad = /`+strings.Join(pattern, "|")+`/;
-const limit = `+strconv.Itoa(inputLimit)+`, chrome = `+strconv.Itoa(chrome)+`, rest = real.sleep, random = Math.random, floor = Math.floor; let sent = 0;
+const limit = `+strconv.Itoa(inputLimit)+`, chrome = `+strconv.Itoa(chrome)+`, rest = real.sleep, random = Math.random, floor = Math.floor; let sent = 0, reads = [], readChars = 0;
+const reading = (k, c) => k === "getState" || k === "call" && c[0] === "get_window_state";
+const keep = r => { if (r === null || typeof r !== "object" || typeof r.snapshot_id !== "string" || typeof r.pid !== "number" || typeof r.window_id !== "number") return; const read = {snapshot_id: r.snapshot_id, pid: r.pid, window_id: r.window_id}; for (const f of ["tree_markdown", "tree_diff", "since", "since_status"]) if (typeof r[f] === "string") read[f] = r[f]; const size = (read.tree_markdown || "").length + (read.tree_diff || "").length; reads[reads.length] = read; readChars += size; while (reads.length > `+strconv.Itoa(scriptReadsKept)+` || readChars > `+strconv.Itoa(scriptReadCharacters)+` && reads.length > 0) { const first = reads[0]; readChars -= (first.tree_markdown || "").length + (first.tree_diff || "").length; reads = apply(slice, reads, [1]); } };
const keyOps = {__proto__: null, hotkey: true, type_text: true, press_key: true}, keyMethods = {__proto__: null, hotkey: true, typeText: true, pressKey: true};
const routes = v => v !== null && typeof v === "object" && (v.pid !== undefined || v.app !== undefined || v.target !== undefined || v.window_id !== undefined || v.windowId !== undefined);
const rerouted = c => { for (let i = 0; i < c.length; i++) if (routes(c[i])) return true; return false; };
@@ -109,22 +114,23 @@ define(w, k, {enumerable: true, get() { const v = o[k]; if (typeof v !== "functi
if (limit > 0 && k === "typeText") { const given = c.length > 2 && c[2] !== null && typeof c[2] === "object" ? c[2] : {}; const t = {length: 3}; define(t, 0, {value: c[0]}); define(t, 1, {value: c[1]}); define(t, 2, {value: {delay_ms: `+strconv.Itoa(agentChromeTypeDelay)+`, ...given}}); c = t; }
if (k === "getState" && (c.length === 0 || c[0] === undefined || c[0] !== null && typeof c[0] === "object" && c[0].include_screenshot === undefined)) { const t = {length: 1}; define(t, 0, {value: {include_screenshot: false, ...(c.length > 0 && c[0] !== undefined ? c[0] : {})}}); c = t; }
if (limit > 0 && k === "sleep" && o === real && typeof c[0] === "number" && c[0] > `+strconv.Itoa(scriptSleepLimit)+`) { const t = {length: 1}; define(t, 0, {value: `+strconv.Itoa(scriptSleepLimit)+`}); c = t; }
-const run = () => { const r = apply(v, o, c); return r !== null && typeof r === "object" && typeof r.then === "function" ? apply(then, r, [out]) : out(r); };
+const run = () => { const r = apply(v, o, c); const seen = x => { if (reading(k, c)) keep(x); return out(x); }; return r !== null && typeof r === "object" && typeof r.then === "function" ? apply(then, r, [seen]) : seen(r); };
if (launches(k, c)) throw new Error("COMPUTER_SCRIPT_REFUSED: a script opens no app or URL, so the site checks of launch_app hold and the key rule knows every app the script reaches; call launch_app as its own tool");
if (keyed(k, c, o)) throw new Error(`+strconv.Quote(everydayChromeKeysRefused)+`);
+if (input(k, c)) { reads = []; readChars = 0; }
if (limit <= 0 || !input(k, c)) return run();
if (++sent > limit) throw new Error("COMPUTER_SCRIPT_INPUT_LIMIT: a script sends at most " + limit + " inputs to the Computer's own browser; return what you have, look at the window, then continue in a new script");
return apply(then, apply(rest, real, [`+strconv.Itoa(scriptInputPauseMin)+` + floor(random() * `+strconv.Itoa(scriptInputPauseSpan)+`)]), [run]); }; }}); } }
return freeze(w); };
-return wrap(real); })();
+return {api: wrap(real), done: v => reads.length === 0 ? v : v === undefined ? {`+scriptReadsKey+`: reads} : {`+scriptReadsKey+`: reads, value: v}}; })();
try { new ((async function () {}).constructor)(`+string(source)+`); } catch (e) { throw new Error("COMPUTER_SCRIPT_REFUSED: the script is not one complete function body: " + e.message); }
for (const f of [function () {}, async function () {}, function* () {}, async function* () {}]) Object.defineProperty(Object.getPrototypeOf(f), "constructor", {value: undefined, writable: false, configurable: false});
for (const b of [Object, Object.prototype, Array, Array.prototype, Function.prototype, Promise, Promise.prototype, JSON, Reflect, RegExp, RegExp.prototype, String.prototype, Symbol]) Object.freeze(b);
-return await (function (cua, globalThis, eval, Function) { return (async function () { "use strict"; `, "\n", " ") + body + scriptEpilogue
+return __guarded.done(await (function (cua, globalThis, eval, Function) { return (async function () { "use strict"; `, "\n", " ") + body + scriptEpilogue
}
// scriptEpilogue closes what guardedScript opened.
-const scriptEpilogue = "\n}).call(undefined); })(__guarded, undefined, undefined, undefined);"
+const scriptEpilogue = "\n}).call(undefined); })(__guarded.api, undefined, undefined, undefined));"
// forbiddenKey reports whether value holds an object key that names word.
func forbiddenKey(value any, word string) bool {
@@ -213,6 +219,93 @@ func scriptArguments(ctx context.Context, arguments map[string]any, reviewScope
return nil
}
+// scriptReadsKey names the reads the guard adds to a script's return value.
+// The guard keeps at most scriptReadsKept of them and scriptReadCharacters of
+// tree text, the latest first kept: an Agent acts on its latest read, and a
+// whole busy page is a few hundred thousand characters.
+const (
+ scriptReadsKey = "__computer_reads"
+ scriptReadsKept = 4
+ scriptReadCharacters = 2000000
+)
+
+// scriptValueCharacters is where Cua cuts a return value in a script's text.
+const scriptValueCharacters = 8000
+
+// scriptResultReads takes the window reads the guard added to a script's
+// return value out of the result, and puts the value the script returned
+// back into the text Cua wrote for it. They are the script's reads after its
+// last input, so the Computer's own reads before the next call can carry the
+// tokens of those rows over, as they do for the Agent's own reads. A result
+// without them is returned as it is.
+func scriptResultReads(result json.RawMessage) (json.RawMessage, []windowRead) {
+ var reply map[string]json.RawMessage
+ var structured map[string]json.RawMessage
+ var value map[string]json.RawMessage
+ if json.Unmarshal(result, &reply) != nil || json.Unmarshal(reply["structuredContent"], &structured) != nil ||
+ json.Unmarshal(structured["value"], &value) != nil {
+ return result, nil
+ }
+ _, inner := value["value"]
+ if _, ok := value[scriptReadsKey]; !ok || len(value) > 2 || len(value) == 2 && !inner {
+ return result, nil
+ }
+ var reads []windowRead
+ if json.Unmarshal(value[scriptReadsKey], &reads) != nil {
+ return result, nil
+ }
+ returned := json.RawMessage("null")
+ if inner {
+ var compact bytes.Buffer
+ if json.Compact(&compact, value["value"]) != nil {
+ return result, nil
+ }
+ returned = compact.Bytes()
+ }
+ structured["value"] = returned
+ text := string(returned)
+ if runes := []rune(text); len(runes) > scriptValueCharacters {
+ text = string(runes[:scriptValueCharacters]) + "…"
+ }
+ var content []map[string]any
+ if json.Unmarshal(reply["content"], &content) == nil {
+ for _, item := range content {
+ if body, ok := item["text"].(string); ok {
+ item["text"] = withReturnValue(body, text)
+ }
+ }
+ }
+ encodedContent, contentErr := json.Marshal(content)
+ encodedStructured, structuredErr := json.Marshal(structured)
+ if contentErr != nil || structuredErr != nil {
+ return result, nil
+ }
+ reply["content"], reply["structuredContent"] = encodedContent, encodedStructured
+ unwrapped, err := json.Marshal(reply)
+ if err != nil {
+ return result, nil
+ }
+ return unwrapped, reads
+}
+
+// withReturnValue replaces the return value line of a script's text, which
+// runs to the console or call log section after it.
+func withReturnValue(text, value string) string {
+ const label = "\nreturn value: "
+ start := strings.Index(text, label)
+ if start < 0 {
+ return text
+ }
+ start += len(label)
+ end := len(text)
+ for _, next := range []string{"\nconsole (", "\ncalls:\n"} {
+ if at := strings.Index(text[start:], next); at >= 0 && start+at < end {
+ end = start + at
+ }
+ }
+ return text[:start] + value + text[end:]
+}
+
// compactScriptResult keeps a script's result small in the model's context:
// the driver call log keeps its first and last lines, the text is cut at a
// fixed length, and the screenshots of the reads the script made are dropped.
diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.go b/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.go
index 1e5ac204..caff3f53 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_script_guard_test.go
@@ -14,7 +14,7 @@ import (
// the same prelude's semantics.
const guardHarness = `import fs from "fs";
const log = [];
-class App { constructor(n, pid, windowId) { this.n = n; this.pid = pid; this.windowId = windowId; } hotkey(keys, on, options) { log.push("hotkey:" + keys.join("+") + ":" + JSON.stringify({pid: this.pid, ...on, ...options})); return "hotkeyed"; } click(a) { log.push("raw:" + JSON.stringify(a)); return "clicked"; } typeText(text, on, options) { log.push("type:" + JSON.stringify(options)); return "typed"; } pressKey(key, on) { log.push("key:" + key); return "pressed"; } getState(options) { log.push("state:" + JSON.stringify(options)); return {tree_markdown: ""}; } }
+class App { constructor(n, pid, windowId) { this.n = n; this.pid = pid; this.windowId = windowId; } hotkey(keys, on, options) { log.push("hotkey:" + keys.join("+") + ":" + JSON.stringify({pid: this.pid, ...on, ...options})); return "hotkeyed"; } click(a) { log.push("raw:" + JSON.stringify(a)); return "clicked"; } typeText(text, on, options) { log.push("type:" + JSON.stringify(options)); return "typed"; } pressKey(key, on) { log.push("key:" + key); return "pressed"; } getState(options) { log.push("state:" + JSON.stringify(options)); return options.query === "rows" ? {snapshot_id: "s0000000a", pid: this.pid, window_id: 9, tree_markdown: "- [3] AXButton \"OK\"", elements: 1} : {tree_markdown: ""}; } }
const fake = { call(t, a) { log.push("call:" + t + ":" + JSON.stringify(a)); return Promise.resolve({ok: true}); },
launch(name) { log.push("launched:" + name); return Promise.resolve(new App("l", 7, 1)); },
getApp(target) { return Promise.resolve(new App("a", target && target.pid, target && target.windowId)); },
@@ -48,10 +48,13 @@ func TestScriptGuardRefusesForbiddenInputInAJSEngine(t *testing.T) {
{"handle in an object", `const b = await cua.box(); return b.inner.app.click({out_file: "/tmp/x"});`, "threw:COMPUTER_SCRIPT_REFUSED", "raw:"},
{"no global object", `return [typeof globalThis, typeof eval, typeof Function, typeof this].join(",");`, "undefined,undefined,undefined,undefined", ""},
{"no function constructor", `return typeof (async function () {}).constructor;`, "undefined", ""},
- {"closing the wrapper", "return 1; }).call(undefined); })(globalThis.cua, globalThis, eval, Function); (function () { return (async function () {", "threw:COMPUTER_SCRIPT_REFUSED: the script is not one complete function body", "call:"},
+ {"closing the wrapper", "return 1; }).call(undefined); })(globalThis.cua, globalThis, eval, Function)); Object(await (function () { return (async function () {", "threw:COMPUTER_SCRIPT_REFUSED: the script is not one complete function body", "call:"},
{"closing the wrapper to call", `}); await globalThis.cua.call("click", {["deliv" + "ery_mode"]: "foreground"}); (async function () {`, "threw:", "call:"},
{"inputs", `return [args.n, DEADLINE].join(",");`, `"1,42"`, ""},
{"read without a screenshot", `const app = await cua.getApp({pid: 1}); await app.getState(); await app.getState({query: "Search"}); await app.getState({include_screenshot: true}); return "read";`, `"state:{\"include_screenshot\":false}","state:{\"include_screenshot\":false,\"query\":\"Search\"}","state:{\"include_screenshot\":true}"`, ""},
+ {"reads after the last input", `const app = await cua.getApp({pid: 4}); await app.click(1); await app.getState({query: "rows"}); return "done";`, `"result":{"__computer_reads":[{"snapshot_id":"s0000000a","pid":4,"window_id":9,"tree_markdown":"- [3] AXButton \"OK\""}],"value":"done"}`, ""},
+ {"a read before an input", `const app = await cua.getApp({pid: 4}); await app.getState({query: "rows"}); await app.click(1); return "done";`, `"result":"done"`, ""},
+ {"no return value", `const app = await cua.getApp({pid: 4}); await app.getState({query: "rows"});`, `"result":{"__computer_reads":[{"snapshot_id":"s0000000a","pid":4,"window_id":9,"tree_markdown":"- [3] AXButton \"OK\""}]}`, ""},
{"frozen builtins", `try { JSON.parse = () => ({delivery_mode: 1}); } catch (e) { return "refused"; } return "changed";`, "refused", ""},
}
for _, tc := range cases {
diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.go b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.go
index 379acd3a..e0ea73d3 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots.go
@@ -46,7 +46,8 @@ func newSnapshotRows() *snapshotRows {
}
// observe records the rows of a read, or forgets the current snapshots after
-// a script, whose reads run inside the driver.
+// a script, whose reads run inside the driver: the reads it made after its
+// last input are recorded from its result once the fence for it is set.
func (s *snapshotRows) observe(params any, result json.RawMessage) {
call, _ := params.(map[string]any)
name, _ := call["name"].(string)
@@ -60,20 +61,29 @@ func (s *snapshotRows) observe(params any, result json.RawMessage) {
return
}
var reply struct {
- Structured struct {
- Snapshot string `json:"snapshot_id"`
- PID float64 `json:"pid"`
- Window float64 `json:"window_id"`
- Tree string `json:"tree_markdown"`
- Diff string `json:"tree_diff"`
- Since string `json:"since"`
- Status string `json:"since_status"`
- } `json:"structuredContent"`
- }
- if json.Unmarshal(result, &reply) != nil || reply.Structured.Snapshot == "" {
+ Structured windowRead `json:"structuredContent"`
+ }
+ if json.Unmarshal(result, &reply) == nil {
+ s.record(reply.Structured)
+ }
+}
+
+// windowRead is the part of a get_window_state result that names its rows.
+type windowRead struct {
+ Snapshot string `json:"snapshot_id"`
+ PID float64 `json:"pid"`
+ Window float64 `json:"window_id"`
+ Tree string `json:"tree_markdown"`
+ Diff string `json:"tree_diff"`
+ Since string `json:"since"`
+ Status string `json:"since_status"`
+}
+
+// record keeps the rows of read as its window's current snapshot.
+func (s *snapshotRows) record(read windowRead) {
+ if read.Snapshot == "" {
return
}
- read := reply.Structured
window := fmt.Sprintf("%g:%g", read.PID, read.Window)
rows := map[string]string{}
s.mu.Lock()
diff --git a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.go b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.go
index 7cf14f81..955beff3 100644
--- a/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.go
+++ b/apps/computer/local-daemon/internal/linger/localtools/cua_snapshots_test.go
@@ -2,6 +2,7 @@ package localtools
import (
"encoding/json"
+ "strings"
"testing"
)
@@ -94,3 +95,65 @@ func TestSnapshotRowsCarriesTokensOverTheComputersOwnReads(t *testing.T) {
t.Fatalf("after a script = %v, want the token unchanged", after["element_token"])
}
}
+
+// A script's reads after its last input come back in its result, so a token
+// it returned carries over the Computer's own reads into the next script.
+func TestSnapshotRowsCarriesAScriptsTokensIntoTheNextScript(t *testing.T) {
+ tree := "- [0] AXWindow \"Shop\"\n - [4] AXLink \"Kettle\" [actions=[press]]"
+ value := map[string]any{scriptReadsKey: []any{map[string]any{"snapshot_id": "s00000011", "pid": 7, "window_id": 9, "tree_markdown": tree}}, "value": map[string]any{"z": 1, "a": "s00000011:4"}}
+ encodedValue, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := "run_script: ok in 5 ms, 2 driver call(s)\nreturn value: " + string(encodedValue)[:40] + "…\nconsole (1 line(s)):\n hi\ncalls:\n 1. line 1 get_window_state ok (3 ms): window_id=9"
+ result, err := json.Marshal(map[string]any{"content": []any{map[string]any{"type": "text", "text": text}},
+ "structuredContent": map[string]any{"ok": true, "value": json.RawMessage(`{"__computer_reads":` + string(mustJSON(t, value[scriptReadsKey])) + `,"value":{"z":1,"a":"s00000011:4"}}`)}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ unwrapped, reads := scriptResultReads(result)
+ var reply struct {
+ Content []struct{ Text string } `json:"content"`
+ Structured struct {
+ Value json.RawMessage `json:"value"`
+ } `json:"structuredContent"`
+ }
+ if err := json.Unmarshal(unwrapped, &reply); err != nil || len(reads) != 1 {
+ t.Fatalf("reply = %s, reads = %v, error = %v", unwrapped, reads, err)
+ }
+ if want := "return value: {\"z\":1,\"a\":\"s00000011:4\"}\nconsole (1 line(s)):\n hi\ncalls:\n"; !strings.Contains(reply.Content[0].Text, want) {
+ t.Fatalf("text = %q, want it to hold %q", reply.Content[0].Text, want)
+ }
+ if string(reply.Structured.Value) != `{"z":1,"a":"s00000011:4"}` {
+ t.Fatalf("structured value = %s", reply.Structured.Value)
+ }
+
+ s := newSnapshotRows()
+ s.observe(map[string]any{"name": "run_script"}, unwrapped)
+ s.sent("run_script")
+ for _, read := range reads {
+ s.record(read)
+ }
+ // The Computer counts the tabs after the script and checks the tab
+ // before the next one; each read replaces the script's snapshot.
+ s.observe(readCall(nil), readResult(t, map[string]any{"snapshot_id": "s00000012", "pid": 7, "window_id": 9, "tree_markdown": tree}))
+ next := map[string]any{"script": `await app.click("s00000011:4")`}
+ s.remap(next)
+ if want := `await app.click("s00000012:4")`; next["script"] != want {
+ t.Fatalf("next script = %v, want %s", next["script"], want)
+ }
+
+ plain := json.RawMessage(`{"content":[{"type":"text","text":"run_script: ok\nreturn value: 1"}],"structuredContent":{"value":1}}`)
+ if same, reads := scriptResultReads(plain); string(same) != string(plain) || reads != nil {
+ t.Fatalf("a result without reads = %s, %v; want it unchanged", same, reads)
+ }
+}
+
+func mustJSON(t *testing.T, value any) []byte {
+ t.Helper()
+ encoded, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return encoded
+}