File size: 20,764 Bytes
d72771b
7c91152
8ff66cf
 
 
d72771b
 
 
 
 
85e0fe1
8ff66cf
7c91152
d72771b
7c91152
d72771b
7c91152
8ff66cf
d72771b
 
8ff66cf
 
 
d72771b
 
8ff66cf
 
d72771b
8ff66cf
d72771b
 
 
 
 
 
8ff66cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
85e0fe1
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
 
 
85e0fe1
d72771b
 
 
 
 
e0daa77
8ff66cf
d72771b
 
 
 
 
8ff66cf
 
 
d72771b
8ff66cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72771b
 
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
85e0fe1
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
e0daa77
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
 
 
 
8ff66cf
 
 
 
 
 
 
 
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
d72771b
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
d72771b
 
 
 
 
 
 
 
 
 
8ff66cf
d72771b
 
 
8ff66cf
d72771b
8ff66cf
d72771b
 
8ff66cf
 
d72771b
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// Tools an LLM agent (or any script) can call to control XLeRobot in the simulation. Each tool has a
// JSON schema (OpenAI function-calling format, in specs.js) and an implementation here that runs a skill in
// the simulation loop and resolves with a short JSON-able result. locate finds objects in a camera's picture
// with Gemini (perception.js); pick, place, go_to and look_at take the point it gives (at) in place of a name,
// and with camera-only perception an agent has nothing else to go by.
//
// Positions given to and returned by the tools are in the robot frame: forward, left, up in metres from
// the robot's base. Angles are in degrees; positive turns are to the left.
import { approach, clearDrive, clearTurn, comfortable, drive, goNear, gripper, graspPlan, holding, homeArm, lookAt, objectInfo, pick, place, press, reach, restArm, turn, wait } from "../robots/skills.js";
import { policyPick } from "../policy/runner.js";
import { moveFixture, openTarget } from "../robots/fixtures.js";
import { annotate, castRay, geminiLocate, mapDetection, parseDetections } from "./perception.js";
import { TOOL_SPECS } from "./specs.js";

export { TOOL_SPECS };

const round = (v, d = 2) => Math.round(v * 10 ** d) / 10 ** d;
const CAMERA_ONLY = "objects are found with the camera here (camera-only perception): locate them, then give the point locate returns as at";

/**
 * Bind the tools to the running app: `app` provides {sim, robot, skills, objects(), loadPolicy(), snapshot(name),
 * envInfo(), cameras(), picture(camera, width), lastPicture(camera), perception()}. Returns {specs(vision),
 * call(name, args, {human})}: a call a person makes (the Skills tab) names objects even with camera-only perception.
 */
export function createTools(app) {
  let human = false; // the call running is a person's (calls run one at a time)
  const cameraOnly = () => !human && Boolean(app.perception?.().cameraOnly);
  const byName = (name) => {
    if (cameraOnly()) throw new Error(CAMERA_ONLY);
    const list = app.objects();
    const want = String(name ?? "").trim().toLowerCase().replace(/^the\s+/, "");
    const found = list.find((o) => o.name.toLowerCase() === want) ?? list.find((o) => o.name.toLowerCase().includes(want));
    if (!found) throw new Error(`no object named "${name}"; objects: ${list.map((o) => o.name).join(", ")}`);
    return found;
  };
  const pointOf = (at) => {
    const p = Array.isArray(at) ? at.slice(0, 3).map(Number) : null;
    if (!p || p.length < 3 || p.some((v) => !Number.isFinite(v))) throw new Error("at is a point [forward, left, up] in metres, as locate gives it");
    return p;
  };
  // The object nearest a point (robot frame) within `radius` metres, but for those a gripper holds.
  const objectAt = (at, { radius = 0.08 } = {}) => {
    const world = app.robot.toWorld(pointOf(at));
    let best = null;
    for (const o of app.objects()) {
      if (["left", "right"].some((s) => holding(app.robot, s, o.id))) continue;
      const c = objectInfo(app.sim, o.id).center;
      const d = Math.hypot(c[0] - world[0], c[1] - world[1], c[2] - world[2]);
      if (!best || d < best.d) best = { o, d };
    }
    if (!best || best.d > radius) throw new Error(`nothing within ${Math.round(radius * 100)} cm of [${pointOf(at).map((v) => round(v)).join(", ")}]${best ? `: the nearest object is ${Math.round(best.d * 100)} cm away; locate it again from nearer` : ""}`);
    return best.o;
  };
  const run = (label, generator) => app.skills.start(label, generator);
  // open or close a fixture by its pull
  const moveTool = async (object, open) => {
    const f = fixtureNamed(object);
    const opens = (app.household?.fixtures() ?? []).filter((e) => e.fixture && e.reach !== false);
    if (!f?.fixture) return { ok: false, message: `no drawer or door named "${object}"; these open: ${opens.map((e) => e.label).join(", ") || "none"}` };
    if (f.reach === false) return { ok: false, message: `the ${f.label} is beyond the arms' reach` };
    return run(`${open ? "open" : "close"} the ${f.label}`, moveFixture(app.robot, f.fixture, open ? openTarget(f.fixture) : 0, { what: `the ${f.label}` }));
  };
  const heldBy = (side) => app.objects().find((o) => holding(app.robot, side, o.id))?.name ?? null;
  // a fixture (surface, container, switch) of the scene's household, when no object has that name
  const fixtureNamed = (name) => {
    const want = String(name ?? "").trim().toLowerCase().replace(/^the\s+/, "");
    if (app.objects().some((o) => o.name.toLowerCase() === want)) return null;
    const e = app.household?.find(want);
    return e && ["surface", "container", "switch"].includes(e.kind) ? e : null;
  };

  const impl = {
    observe() {
      const { robot, sim } = app;
      const [x, y, yaw] = robot.pose();
      const objects = cameraOnly() ? null : app.objects().map((o) => {
        const info = objectInfo(sim, o.id);
        const p = robot.toRobot(info.center);
        const check = comfortable(robot, o.id);
        const plan = check.plan;
        return {
          name: o.name,
          forward_m: round(p[0]),
          left_m: round(p[1]),
          up_m: round(p[2]),
          distance_m: round(Math.hypot(p[0], p[1])),
          size_cm: [round(info.width * 100, 0), round(info.height * 100, 0)],
          graspable_now: !plan.reason,
          arm: plan.reason ? null : plan.side,
          note: plan.reason ?? (check.ok ? "in reach" : "at the edge of reach"),
        };
      });
      objects?.sort((a, b) => a.distance_m - b.distance_m);
      const h = app.household;
      const fixtures = h?.fixtures().map((e) => {
        const near = h.nearPoint(e, robot.pose());
        const p = near ? robot.toRobot(near.world) : [0, 0, 0];
        const out = { name: e.label, kind: e.kind === "switch" ? `switch (${e.on ? "on" : "off"})` : e.kind, forward_m: round(p[0]), left_m: round(p[1]), distance_m: round(Math.hypot(p[0], p[1])) };
        if (e.fixture) out.open = h.holds("open", [e.name]);
        return e.reach === false ? { ...out, note: "beyond the arms' reach" } : out;
      });
      return {
        scene: app.envInfo(),
        robot: { x_m: round(x), y_m: round(y), heading_deg: round((yaw * 180) / Math.PI, 0) },
        grippers: Object.fromEntries(["left", "right"].map((s) => { const held = heldBy(s); return [s, { open: !held && robot.gripperOpening(s) > 0.5, holding: held }]; })),
        ...(objects ? { objects } : { objects_hidden: `camera-only perception: ${CAMERA_ONLY}` }),
        ...(fixtures ? { fixtures } : {}),
        ...(app.episode ? { task: app.episode.report() } : {}),
      };
    },
    async look() {
      const shot = await app.picture("head");
      if (!shot) return { ok: false, message: "this robot has no head camera" };
      return { ok: true, message: "head camera image attached", image: shot.image };
    },
    /**
     * Objects in a camera's picture, found by Gemini (or the caller's own points in the last picture), each with
     * its position from the camera's depth or from the plane it stands on.
     */
    async locate({ query, points, camera = "head", method }) {
      const hide = cameraOnly(); // before any await: calls of a person and of an agent can overlap
      const cams = app.cameras?.() ?? [];
      const name = String(camera || "head").trim().toLowerCase().replace(/[\s-]+/g, "_");
      if (!cams.includes(name)) return { ok: false, message: `no camera "${camera}"; cameras: ${cams.join(", ") || "none"}` };
      // the head camera can be XLeRobot's RealSense (RGB-D); the wrist cameras see colour only
      const how = method ?? (name === "head" ? "depth" : "plane");
      if (!["depth", "plane"].includes(how)) return { ok: false, message: 'method is "depth" or "plane"' };
      const settings = app.perception?.() ?? {};
      let shot;
      let detections;
      let by;
      if (points !== undefined && points !== null) {
        shot = app.lastPicture?.(name);
        if (!shot) return { ok: false, message: `take a picture with the ${name} camera first (camera, or look for the head), then give points in it` };
        detections = parseDetections(points);
        if (!detections.length) return { ok: false, message: 'points: [{"label", "point": [y, x], "box_2d": [ymin, xmin, ymax, xmax]}] on the 0-1000 grid of the last picture' };
        by = "the points given";
      } else {
        if (!String(query ?? "").trim()) return { ok: false, message: "say what to find (query), or give points you see in the last picture" };
        if (!settings.key) return { ok: false, message: "no Gemini API key: one goes in the Agent tab (Perception) or, for Claude Code, in GEMINI_API_KEY for the MCP server. Without one, look at a camera picture yourself and give locate the points you see." };
        shot = await app.picture(name, 640);
        if (!shot) return { ok: false, message: `the ${name} camera took no picture` };
        const answer = await geminiLocate({ apiKey: settings.key, image: shot.image, query: String(query), model: settings.model, thinking: settings.thinking });
        detections = answer.detections;
        by = answer.model;
      }
      const cast = (origin, dir, options) => castRay(app.sim, app.robot.root, origin, dir, options);
      const found = detections.map((d, k) => {
        const out = { n: k + 1, label: d.label, point: d.point.map((v) => Math.round(v)), ...(d.box ? { box_2d: d.box.map((v) => Math.round(v)) } : {}) };
        const m = mapDetection(shot.frame, d, how, cast);
        if (!m.world) return { ...out, at: null, note: m.reason };
        const p = app.robot.toRobot(m.world);
        out.at = p.map((v) => round(v));
        out.distance_m = round(Math.hypot(p[0], p[1]));
        if (m.surface) out.on = m.surface.replace(/_/g, " ");
        if (m.height_m) out.size_cm = [Math.round(m.width_m * 100), Math.round(m.height_m * 100)];
        if (!hide) {
          // how far off the simulation's own record of the nearest object is
          let best = null;
          for (const o of app.objects()) {
            const c = objectInfo(app.sim, o.id).center;
            const dist = Math.hypot(c[0] - m.world[0], c[1] - m.world[1], c[2] - m.world[2]);
            if (!best || dist < best.dist) best = { name: o.name, dist };
          }
          if (best) out.nearest_object = { name: best.name, off_cm: Math.round(best.dist * 100) };
        }
        return out;
      });
      const image = await annotate(shot.image, detections);
      const what = query ? `"${query}"` : "the points";
      return {
        ok: true,
        camera: name,
        method: how,
        by,
        found,
        message: found.length ? `${found.length} found for ${what} (${by}, ${how})` : `nothing matching ${what} in the ${name} camera's picture`,
        image,
      };
    },
    async go_to({ object, at }) {
      if (!object && !at) return { ok: false, message: "give object (a name) or at (a point from locate)" };
      const f = at ? null : fixtureNamed(object);
      if (f) {
        const near = app.household.nearPoint(f, app.robot.pose());
        return run(`go to the ${f.label}`, goNear(app.robot, near.world, { slack: near.slack, what: `the ${f.label}` }));
      }
      const o = at ? objectAt(at) : byName(object);
      return run(`go to ${o.name}`, approach(app.robot, o.id));
    },
    async press({ object }) {
      const f = fixtureNamed(object);
      if (!f || f.kind !== "switch") return { ok: false, message: `no switch named "${object}"; switches: ${(app.household?.switches() ?? []).map((e) => e.label).join(", ") || "none"}` };
      const was = f.on;
      const result = await run(`press the ${f.label}`, press(app.robot, app.household.buttonTop(f)));
      if (!result.ok) return result;
      return { ok: f.on !== was, message: f.on !== was ? `the ${f.label} is ${f.on ? "on" : "off"} now` : `pressed, but the ${f.label} stayed ${f.on ? "on" : "off"}` };
    },
    async open({ object }) {
      return moveTool(object, true);
    },
    async close({ object }) {
      return moveTool(object, false);
    },
    task() {
      if (!app.episode) return { ok: false, message: "no household task is running (one is started from the Tasks tab)", tasks: (app.household?.tasks ?? []).map((t) => t.title) };
      return { ok: true, ...app.episode.report() };
    },
    async drive({ distance_m }) {
      const asked = Math.max(-3, Math.min(3, Number(distance_m)));
      const clear = clearDrive(app.robot, asked);
      if (Math.abs(clear.distance) < 0.01) return { ok: false, message: `cannot drive ${asked > 0 ? "forward" : "backward"}: the ${clear.blockedBy} is in the way` };
      const result = await run(`drive ${round(clear.distance)} m`, drive(app.robot, clear.distance));
      return clear.blockedBy ? { ...result, message: `${result.message}, stopping short of the ${clear.blockedBy}` } : result;
    },
    async turn({ degrees }) {
      const asked = (Math.max(-360, Math.min(360, Number(degrees))) * Math.PI) / 180;
      const clear = clearTurn(app.robot, asked);
      if (Math.abs(clear.angle) < 0.02) return { ok: false, message: `cannot turn ${asked > 0 ? "left" : "right"}: the robot would swing into the ${clear.blockedBy}` };
      const result = await run(`turn ${round((clear.angle * 180) / Math.PI, 0)}°`, turn(app.robot, clear.angle));
      return clear.blockedBy ? { ...result, message: `${result.message}, stopping short of the ${clear.blockedBy}` } : result;
    },
    async pick({ object, at, arm, method = "script" }) {
      if (!object && !at) return { ok: false, message: "give object (a name) or at (a point from locate)" };
      const o = at ? objectAt(at) : byName(object);
      // with one hand full, the other one (the full one would let go of what it holds)
      const full = ["left", "right"].filter((s) => heldBy(s));
      if (full.length === 2) return { ok: false, message: `both grippers hold something (${heldBy("left")}, ${heldBy("right")}); place one first` };
      if (arm && full.includes(arm)) return { ok: false, message: `the ${arm} gripper holds the ${heldBy(arm)}; use the other arm or place it first` };
      if (!arm && full.length === 1) arm = full[0] === "left" ? "right" : "left";
      const plan = graspPlan(app.robot, o.id, arm);
      const tooWide = plan.reason && plan.info && plan.info.width > 0.065;
      if (plan.reason && (method === "policy" || tooWide)) return { ok: false, message: `cannot grasp ${o.name}: ${plan.reason}${tooWide ? "" : ". Try go_to first."}` };
      if (plan.reason) {
        // Out of reach from here: drive there and grasp, the arm reaching out as the base arrives.
        const robot = app.robot;
        return run(`pick ${o.name}`, (function* () {
          const went = yield* approach(robot, o.id, { side: arm });
          if (!went.ok) return { ok: false, message: `could not get to the ${o.name}: ${went.message}` };
          return yield* pick(robot, o.id, { side: arm ?? went.side });
        })());
      }
      if (method === "policy") {
        const runner = await app.loadPolicy();
        const side = arm ?? plan.side;
        const robot = app.robot;
        // The policy learned to pick starting with the arm at rest.
        return run(`policy pick ${o.name}`, (function* () {
          yield* restArm(robot, side);
          return yield* policyPick(robot, runner, o.id, side);
        })());
      }
      return run(`pick ${o.name}`, pick(app.robot, o.id, { side: arm }));
    },
    async place({ arm, on, at, forward_m, left_m }) {
      const { robot, sim } = app;
      const heldName = heldBy(arm);
      const held = heldName ? app.objects().find((o) => o.name === heldName) : null;
      let point;
      let target = null;
      let slack = 0;
      if (at && !on) {
        // a point from locate: the object there (a bowl, a plate), or else that spot on the surface below it
        try {
          target = objectAt(at, { radius: 0.1 });
        } catch {
          [forward_m, left_m] = pointOf(at);
        }
      }
      const fixture = on && !target ? fixtureNamed(on) : null;
      if (fixture) {
        // on a surface or into a container of the household
        if (!held) return { ok: false, message: `the ${arm} gripper holds nothing` };
        if (fixture.kind === "switch") return { ok: false, message: `the ${fixture.label} is a switch; press it instead` };
        const h = app.household;
        const name = h.entityOf(held.id);
        const pred = fixture.kind === "container" ? "inside" : "ontop";
        const spot = h.placeTarget(name, pred, fixture.name, { from: robot.pose() });
        if (!spot) return { ok: false, message: `no free spot ${pred === "inside" ? "in" : "on"} the ${fixture.label}` };
        const result = await run(`place`, place(robot, arm, robot.toRobot(spot.world), held.id, { slack: spot.slack, drop: Boolean(spot.drop) }));
        await run("settle", wait(robot, 0.5)); // let it come to rest in the container
        const there = h.holds(pred, [name, fixture.name]);
        const word = pred === "inside" ? "in" : "on";
        return { ...result, ok: there, message: there ? `put the ${held.name} ${word} the ${fixture.label}` : `the ${held.name} is not ${word} the ${fixture.label} (${result.message})` };
      }
      if (on || target) {
        target ??= byName(on);
        const info = objectInfo(sim, target.id);
        const c = robot.toRobot(info.center);
        point = [c[0], c[1], robot.toRobot([0, 0, info.bottom])[2] + 0.012];
        // Anywhere near the middle of a wide container will do: the arm aims at the nearer part of it.
        // (the held object's width at rest: in the fingers it can lie tilted and measure wider)
        const heldWidth = held ? (app.household?.restWidth(held.id) ?? objectInfo(sim, held.id).width) : 0.05;
        slack = Math.max(0, info.width / 2 - heldWidth / 2 - 0.02);
      } else if (forward_m !== undefined && left_m !== undefined) {
        // On the furniture under that spot (the floor if none).
        point = [Number(forward_m), Number(left_m), 0];
        const below = app.surfaceBelow?.(robot.toWorld([point[0], point[1], 2]));
        point[2] = robot.toRobot([0, 0, below ?? 0])[2];
      } else return { ok: false, message: "give 'on', 'at' (a point from locate), or forward_m and left_m" };
      const result = await run(`place`, place(robot, arm, point, held?.id, { slack }));
      if (target && held) {
        // In or on a container counts when the object ends within its footprint.
        const t = objectInfo(sim, target.id);
        const a = robot.toRobot(t.center);
        const b = robot.toRobot(sim.bodyPos(held.id));
        const inside = Math.hypot(a[0] - b[0], a[1] - b[1]) < Math.max(0.03, t.width / 2 - 0.005);
        return { ...result, ok: inside, message: inside ? `put the ${held.name} in/on the ${target.name}` : `the ${held.name} missed the ${target.name} (${result.message})` };
      }
      return result;
    },
    async gripper({ arm, open }) {
      return run(`${open ? "open" : "close"} ${arm} gripper`, gripper(app.robot, arm, Boolean(open)));
    },
    async move_arm({ arm, forward_m, left_m, up_m, pitch_deg = 90 }) {
      return run(`move ${arm} arm`, reach(app.robot, arm, [Number(forward_m), Number(left_m), Number(up_m)], { pitch: (Number(pitch_deg) * Math.PI) / 180, duration: 1.4 }));
    },
    async home_arms() {
      const robot = app.robot;
      return run("home arms", (function* () {
        yield* homeArm(robot, "left");
        yield* homeArm(robot, "right");
        return { ok: true, message: "arms at rest" };
      })());
    },
    async look_at({ object, at }) {
      if (at) return run("look", lookAt(app.robot, app.robot.toWorld(pointOf(at))));
      if (!object) return { ok: false, message: "give object (a name) or at (a point [forward, left, up])" };
      const o = byName(object);
      return run(`look at ${o.name}`, lookAt(app.robot, app.sim.bodyPos(o.id)));
    },
    async wait({ seconds }) {
      return run(`wait`, wait(app.robot, Math.max(0, Math.min(20, Number(seconds)))));
    },
  };

  return {
    specs: (vision = true) => TOOL_SPECS.filter((t) => vision || !t.vision),
    async call(name, args = {}, options = {}) {
      const fn = impl[name];
      if (!fn) return { ok: false, message: `unknown tool ${name}` };
      if (!app.robot?.arms) return { ok: false, message: "these tools drive XLeRobot, and another robot is loaded (XLeRobot can be chosen under Scene, Robot)" };
      human = Boolean(options.human);
      try {
        return await fn(args ?? {});
      } catch (error) {
        return { ok: false, message: error.message };
      } finally {
        human = false;
      }
    },
  };
}