File size: 5,249 Bytes
7a35d14
8ff66cf
 
 
7a35d14
8ff66cf
7c91152
7a35d14
8ff66cf
 
 
 
 
 
 
 
 
7c91152
7a35d14
7c91152
7a35d14
 
 
 
 
8ff66cf
7a35d14
8ff66cf
 
7a35d14
d72771b
7a35d14
 
 
 
 
 
 
 
8ff66cf
 
7a35d14
 
 
 
 
 
 
 
 
 
 
 
 
8ff66cf
 
 
 
7a35d14
8ff66cf
7a35d14
8ff66cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a35d14
8ff66cf
7a35d14
 
 
 
 
8ff66cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a35d14
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
// The agent loop: the user's instruction, the model's tool calls run in the simulation, their results
// back to the model, until it answers without calling a tool (or the step limit). The model is one on an
// OpenAI-compatible endpoint (llm.js: Hugging Face's router, a local server), Gemini (gemini.js) or Claude
// (claude.js); each keeps the conversation in its own API's form.
import { complete } from "./llm.js";
import { geminiTurn } from "./gemini.js";
import { ROBOT_INTRO, TOOL_GUIDE } from "./specs.js";

/** Claude's models for the agent (claude.js talks to them, loaded when one is chosen). */
export const CLAUDE_MODELS = [
  { id: "claude-opus-5-5", label: "Claude Opus 5.5" },
  { id: "claude-sonnet-5-5", label: "Claude Sonnet 5.5" },
  { id: "claude-haiku-5-5", label: "Claude Haiku 5.5" },
  { id: "claude-fable-5-2", label: "Claude Fable 5.2" },
];
export const CLAUDE_DEFAULT = "claude-opus-5-5";

export const SYSTEM_PROMPT = `${ROBOT_INTRO}

${TOOL_GUIDE}
Keep replies short. Answer in the language the user writes in.`;

export class Agent {
  constructor(tools, settings) {
    this.tools = tools;
    this.settings = settings; // () => {provider, baseUrl, apiKey, model, vision, effort}
    this.messages = [{ role: "system", content: SYSTEM_PROMPT }];
    this.history = []; // Claude's or Gemini's conversation
    this.talkingTo = null; // provider and model of the conversation so far
    this.controller = null;
    this.maxSteps = 40; // a household task takes a few calls per object
  }

  get busy() {
    return this.controller !== null;
  }

  clear() {
    this.messages = [{ role: "system", content: SYSTEM_PROMPT }];
    this.history = [];
    this.talkingTo = null;
  }

  stop() {
    this.controller?.abort();
  }

  /**
   * Run one user turn. `on` receives events: {type: "assistant", text}, {type: "tool", name, args},
   * {type: "result", name, result}, {type: "error", message}, {type: "image", url}.
   */
  async send(text, on = () => {}) {
    if (this.busy) throw new Error("the agent is still working");
    const settings = this.settings();
    // A conversation belongs to its model (Claude's and Gemini's thinking is bound to it): another starts afresh.
    const who = `${settings.provider ?? "openai"} ${settings.model}`;
    if (this.talkingTo && this.talkingTo !== who) this.clear();
    this.talkingTo = who;
    this.controller = new AbortController();
    const signal = this.controller.signal;
    try {
      if (settings.provider === "claude" || settings.provider === "gemini") {
        const turn = settings.provider === "claude" ? (await import("./claude.js")).claudeTurn : geminiTurn;
        await turn({
          apiKey: settings.apiKey,
          model: settings.model,
          effort: settings.effort,
          thinking: settings.effort,
          system: SYSTEM_PROMPT,
          specs: this.tools.specs(true),
          history: this.history,
          text,
          call: (name, args) => this.tools.call(name, args),
          on,
          signal,
          maxSteps: this.maxSteps,
        });
      } else await this.#openaiTurn(text, settings, on, signal);
    } catch (error) {
      if (error.name === "AbortError" || signal.aborted) on({ type: "error", message: "stopped" });
      else on({ type: "error", message: error.message });
    } finally {
      this.controller = null;
    }
  }

  async #openaiTurn(text, settings, on, signal) {
    this.messages.push({ role: "user", content: text });
    for (let step = 0; step < this.maxSteps; step++) {
      const message = await complete({ ...settings, messages: this.messages, tools: this.tools.specs(settings.vision), signal });
      const calls = message.tool_calls ?? [];
      this.messages.push({ role: "assistant", content: message.content ?? "", ...(calls.length ? { tool_calls: calls } : {}) });
      const said = (message.content ?? "").replace(/<think>[\s\S]*?<\/think>/g, "").trim();
      if (said) on({ type: "assistant", text: said });
      if (!calls.length) return;
      const images = [];
      for (const call of calls) {
        if (signal.aborted) throw new DOMException("stopped", "AbortError");
        let args = {};
        try {
          args = call.function.arguments ? JSON.parse(call.function.arguments) : {};
        } catch {
          args = {};
        }
        on({ type: "tool", name: call.function.name, args });
        const result = await this.tools.call(call.function.name, args);
        const { image, ...rest } = result ?? {};
        if (image) {
          images.push(image);
          on({ type: "image", url: image });
        }
        on({ type: "result", name: call.function.name, result: rest });
        this.messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(rest) });
      }
      // Tool messages carry text only; pictures go to the model as a user message.
      if (images.length) {
        this.messages.push({ role: "user", content: [{ type: "text", text: images.length > 1 ? "Camera images, in the order of the calls:" : "Camera image:" }, ...images.map((url) => ({ type: "image_url", image_url: { url } }))] });
      }
    }
    on({ type: "assistant", text: `(stopped after ${this.maxSteps} steps)` });
  }
}