@runappsai/agent 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.d.ts CHANGED
@@ -104,6 +104,14 @@ export interface ChatOptions extends Omit<AgentOptions, "workspace"> {
104
104
  attachments?: boolean;
105
105
  /** Where attached files are saved in the directory (default `/uploads`). */
106
106
  uploadsDir?: string;
107
+ /**
108
+ * The globe in the composer's toolbar that turns the platform's web
109
+ * tools on and off (`webTools`; the user's choice is kept per app).
110
+ * Shown by default when the provider has them (the RunApps client,
111
+ * SDK 0.19+) and the host did not pass `webTools` as a function of its
112
+ * own; `false` hides it, `true` shows it anyway.
113
+ */
114
+ webSearch?: boolean;
107
115
  /**
108
116
  * Called when a link in the conversation (a reply, its thinking, a tool
109
117
  * card) is clicked, before the chat's own handling: return `true` when you
package/dist/chat.js CHANGED
@@ -38,7 +38,8 @@ const STRINGS = {
38
38
  delete: "Delete", deleteAll: "Delete all", confirmDelete: "Delete this conversation and its files?", confirmDeleteAll: "Delete every conversation, this one included, and their files?", untitled: "New conversation",
39
39
  attach: "Attach files", drop: "Drop files to attach", tooLarge: "is too large (max 20 MB)", remove: "Remove",
40
40
  toolsRunning: "Running", toolsDone: "Ran {n} tool calls", toolsDone1: "Ran 1 tool call", toolsFailed: "{n} failed",
41
- actRead: "read {n} file(s)", actList: "listed {n} folder(s)", actSearch: "searched {n} time(s)", actWrite: "wrote {n} file(s)", actEdit: "edited {n} file(s)", actDelete: "deleted {n} file(s)", actRun: "ran {n} snippet(s)", actAsk: "asked you {n} time(s)", actOther: "used {name}",
41
+ actRead: "read {n} file(s)", actList: "listed {n} folder(s)", actSearch: "searched {n} time(s)", actWrite: "wrote {n} file(s)", actEdit: "edited {n} file(s)", actDelete: "deleted {n} file(s)", actRun: "ran {n} snippet(s)", actAsk: "asked you {n} time(s)", actOther: "used {name}", actWeb: "searched the web {n} time(s)", actBrowse: "read {n} web page(s)", ingWeb: "Searching the web", ingBrowse: "Reading",
42
+ web: "Web", webOn: "Web search: on", webOff: "Web search: off", webHint: "When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed",
42
43
  runCode: "Run code", ingRead: "Reading", ingList: "Listing", ingSearch: "Searching", ingWrite: "Writing", ingEdit: "Editing", ingDelete: "Deleting", ingRun: "Running code", ingAsk: "Asking you", ingOther: "Running", current: "Current", jumpEnd: "Jump to the latest",
43
44
  sTabModel: "Model", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
44
45
  dNoCalls: "No tool calls yet.", dNoRequests: "No model requests yet. Each call to the model is listed here with what was sent and what came back.", dNoEvents: "No events yet.",
@@ -77,7 +78,8 @@ const STRINGS = {
77
78
  delete: "删除", deleteAll: "全部删除", confirmDelete: "删除这个对话和它的文件?", confirmDeleteAll: "删除所有对话(包括当前这个)和它们的文件?", untitled: "新对话",
78
79
  attach: "添加附件", drop: "松开即可添加附件", tooLarge: "太大了(最大 20 MB)", remove: "移除",
79
80
  toolsRunning: "正在执行", toolsDone: "执行了 {n} 个工具调用", toolsDone1: "执行了 1 个工具调用", toolsFailed: "{n} 个失败",
80
- actRead: "读取了 {n} 个文件", actList: "查看了 {n} 个目录", actSearch: "搜索了 {n} 次", actWrite: "写入了 {n} 个文件", actEdit: "修改了 {n} 个文件", actDelete: "删除了 {n} 个文件", actRun: "运行了 {n} 段代码", actAsk: "询问了你 {n} 次", actOther: "调用了 {name}",
81
+ actRead: "读取了 {n} 个文件", actList: "查看了 {n} 个目录", actSearch: "搜索了 {n} 次", actWrite: "写入了 {n} 个文件", actEdit: "修改了 {n} 个文件", actDelete: "删除了 {n} 个文件", actRun: "运行了 {n} 段代码", actAsk: "询问了你 {n} 次", actOther: "调用了 {name}", actWeb: "联网搜索了 {n} 次", actBrowse: "阅读了 {n} 个网页", ingWeb: "正在联网搜索", ingBrowse: "正在阅读",
82
+ web: "联网", webOn: "联网搜索:已开启", webOff: "联网搜索:已关闭", webHint: "开启后 AI 可以搜索和阅读网页,查资料和最新信息;每次搜索、每读一个网页按次计费",
81
83
  runCode: "运行代码", ingRead: "正在读取", ingList: "正在查看", ingSearch: "正在搜索", ingWrite: "正在写入", ingEdit: "正在修改", ingDelete: "正在删除", ingRun: "正在运行代码", ingAsk: "正在询问你", ingOther: "正在执行", current: "当前", jumpEnd: "回到最新",
82
84
  sTabModel: "模型", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
83
85
  dNoCalls: "还没有工具调用。", dNoRequests: "还没有模型请求。每次调用模型都会记在这里,包括发了什么、收到什么。", dNoEvents: "还没有事件。",
@@ -469,6 +471,7 @@ const CSS = tokenCSS() + `
469
471
  .ra-chat .ra-cbtn.icon{width:28px;padding:0;justify-content:center}
470
472
  .ra-chat .ra-cbtn:hover:not(:disabled){background:var(--ra-muted);color:var(--ra-fg)}
471
473
  .ra-chat .ra-cbtn svg{width:15px;height:15px}
474
+ .ra-chat .ra-cbtn.ra-web.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
472
475
  .ra-files{display:flex;flex-wrap:wrap;gap:6px;padding:0 0 6px}
473
476
  .ra-chip{display:inline-flex;align-items:center;gap:10px;max-width:min(100%,340px);height:44px;border:1px solid var(--ra-border);border-radius:12px;padding:0 12px 0 10px;font-size:14px;background:var(--ra-panel);white-space:nowrap}
474
477
  .ra-chip img{width:30px;height:30px;object-fit:cover;border-radius:6px;flex:none}
@@ -573,7 +576,7 @@ function injectStyles() {
573
576
  /* ------------------------------------------------------------------ */
574
577
  const TOOL_ICON = {
575
578
  read_file: I.fileText, write_file: I.filePlus, edit_file: I.filePen, delete_file: I.fileX, list_files: I.folderOpen,
576
- search_files: I.search, run_js: I.braces, ask_user: I.message,
579
+ search_files: I.search, run_js: I.braces, ask_user: I.message, web_search: I.search, web_fetch: I.globe,
577
580
  };
578
581
  /** Text of a message's content; images are listed as `<img>` elements by the caller. */
579
582
  function textOfContent(content) {
@@ -608,7 +611,7 @@ function summarizeArgs(name, args) {
608
611
  return first === undefined ? "" : (typeof first === "string" ? first : JSON.stringify(first)).slice(0, 80);
609
612
  }
610
613
  const TOOL_KIND = {
611
- read_file: "Read", list_files: "List", search_files: "Search", write_file: "Write", edit_file: "Edit", delete_file: "Delete", run_js: "Run", ask_user: "Ask",
614
+ read_file: "Read", list_files: "List", search_files: "Search", write_file: "Write", edit_file: "Edit", delete_file: "Delete", run_js: "Run", ask_user: "Ask", web_search: "Web", web_fetch: "Browse",
612
615
  };
613
616
  const pathArg = (args) => (args && typeof args === "object" && typeof args.path === "string" ? args.path : undefined);
614
617
  /** The status a saved tool result stands for, as the live card showed it. */
@@ -1008,7 +1011,7 @@ export function renderChat(target, opts) {
1008
1011
  injectStyles();
1009
1012
  const lang = pickLocale(opts.locale);
1010
1013
  const t = STRINGS[lang];
1011
- const { toolSettings, client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, ...agentOpts } = opts;
1014
+ const { toolSettings, client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, ...agentOpts } = opts;
1012
1015
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
1013
1016
  const provider = providerOpt ? toProvider(providerOpt) : clientOpt ? toProvider(clientOpt) : givenAgent?.provider ?? null;
1014
1017
  const project = provider?.name ?? agentOpts.appName ?? "app";
@@ -1198,7 +1201,42 @@ export function renderChat(target, opts) {
1198
1201
  actionBtns.set(a.id, { btn, a });
1199
1202
  return btn;
1200
1203
  });
1201
- left.append(attachBtn, ...hostActions, hint);
1204
+ // 联网: the platform's web tools for this app's chats, the choice kept per app.
1205
+ const WEB_KEY = `__runapps_agent_chat:${project}:web`;
1206
+ const webShown = !!provider?.platformTools && (webSearchOpt ?? typeof agentOpts.webTools !== "function");
1207
+ let webOn = (() => { try {
1208
+ const v = localStorage.getItem(WEB_KEY);
1209
+ if (v !== null)
1210
+ return v === "1";
1211
+ }
1212
+ catch { /* private mode */ } return agentOpts.webTools === true; })();
1213
+ const webBtn = h("button", "ra-cbtn ra-web");
1214
+ webBtn.type = "button";
1215
+ const drawWeb = () => {
1216
+ const label = webOn ? t.webOn : t.webOff;
1217
+ webBtn.innerHTML = I.globe(15) + (webOn ? `<span>${escapeHTML(t.web)}</span>` : "");
1218
+ webBtn.classList.toggle("on", webOn);
1219
+ webBtn.classList.toggle("icon", !webOn);
1220
+ webBtn.setAttribute("aria-pressed", String(webOn));
1221
+ webBtn.setAttribute("aria-label", label);
1222
+ webBtn.title = `${label}\n${t.webHint}`;
1223
+ };
1224
+ drawWeb();
1225
+ if (!webShown)
1226
+ webBtn.style.display = "none";
1227
+ const applyWeb = (a) => { if (webShown)
1228
+ a.configure({ webTools: webOn }); };
1229
+ webBtn.addEventListener("click", () => {
1230
+ webOn = !webOn;
1231
+ try {
1232
+ localStorage.setItem(WEB_KEY, webOn ? "1" : "0");
1233
+ }
1234
+ catch { /* private mode */ }
1235
+ drawWeb();
1236
+ for (const a of live.values())
1237
+ applyWeb(a);
1238
+ });
1239
+ left.append(attachBtn, webBtn, ...hostActions, hint);
1202
1240
  bar.append(left, acts);
1203
1241
  box.append(cmds, files, ta, bar, fileInput);
1204
1242
  const drop = h("div", "ra-drop", t.drop);
@@ -3892,6 +3930,7 @@ export function renderChat(target, opts) {
3892
3930
  clearNext();
3893
3931
  agent = a;
3894
3932
  live.set(a.id, a);
3933
+ applyWeb(a);
3895
3934
  unwatchBackground(a);
3896
3935
  ui.restore(parked.get(a.id) ?? []);
3897
3936
  parked.delete(a.id);
package/dist/dom.d.ts CHANGED
@@ -44,6 +44,7 @@ export declare const I: {
44
44
  filePlus: (s?: number) => string;
45
45
  filePen: (s?: number) => string;
46
46
  fileX: (s?: number) => string;
47
+ globe: (s?: number) => string;
47
48
  search: (s?: number) => string;
48
49
  braces: (s?: number) => string;
49
50
  message: (s?: number) => string;
package/dist/dom.js CHANGED
@@ -55,6 +55,7 @@ export const I = {
55
55
  filePlus: (s = 13) => svg(s, '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M9 15h6M12 18v-6"/>'),
56
56
  filePen: (s = 13) => svg(s, '<path d="M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M13.4 20.3a1 1 0 0 0 .5-.3l6.9-6.9a1.4 1.4 0 0 0-2-2l-6.9 6.9a1 1 0 0 0-.3.5l-.4 1.8z"/>'),
57
57
  fileX: (s = 13) => svg(s, '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="m14.5 12.5-5 5M9.5 12.5l5 5"/>'),
58
+ globe: (s = 14) => svg(s, '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'),
58
59
  search: (s = 13) => svg(s, '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),
59
60
  braces: (s = 13) => svg(s, '<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/>'),
60
61
  message: (s = 13) => svg(s, '<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>'),
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ __export(src_exports, {
30
30
  PartialReadError: () => PartialReadError,
31
31
  ProviderError: () => ProviderError,
32
32
  UNTITLED: () => UNTITLED,
33
+ WEB_TOOL_NAMES: () => WEB_TOOL_NAMES,
33
34
  Workspace: () => Workspace,
34
35
  applyEdits: () => applyEdits,
35
36
  askUserTool: () => askUserTool,
@@ -82,7 +83,8 @@ __export(src_exports, {
82
83
  summaryOf: () => summaryOf,
83
84
  titleOf: () => titleOf,
84
85
  toProvider: () => toProvider,
85
- validateSchema: () => validateSchema
86
+ validateSchema: () => validateSchema,
87
+ webTools: () => webTools
86
88
  });
87
89
  module.exports = __toCommonJS(src_exports);
88
90
 
@@ -158,6 +160,7 @@ function runappsProvider(client) {
158
160
  // Only what the client really has: a stand-in without create() or a catalogue is still a provider.
159
161
  complete: client.chat.create ? (p, init) => client.chat.create(p, init) : void 0,
160
162
  models: client.models?.list ? async (o) => await client.models.list(o) : void 0,
163
+ platformTools: client.tools,
161
164
  readFile: files ? async (path, o) => {
162
165
  const st = await files.stat(path);
163
166
  if (o?.etag && st.etag && o.etag === st.etag) return null;
@@ -3255,6 +3258,64 @@ ${r.logs}`);
3255
3258
  });
3256
3259
  }
3257
3260
 
3261
+ // src/web-tools.ts
3262
+ var WEB_TOOL_NAMES = ["web_search", "web_fetch"];
3263
+ var svg = (body) => `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
3264
+ var GLOBE_ICON = svg('<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>');
3265
+ var SEARCH_ICON = svg('<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>');
3266
+ var GUIDELINES = [
3267
+ "web_search finds pages and web_fetch reads one: use them for facts you can't know or that change (news, prices, releases, people, places, a work's details, a reference the user names), not for what the conversation or your own knowledge already answers.",
3268
+ "Read the most relevant results with web_fetch before relying on them; a snippet is not the page. Say where an answer came from, with the link.",
3269
+ "Each call costs the user a little: search with a precise query, and stop when you have enough."
3270
+ ];
3271
+ function hostOf(url) {
3272
+ if (typeof url !== "string") return "";
3273
+ try {
3274
+ const u = new URL(url.includes("://") ? url : `https://${url}`);
3275
+ const path = u.pathname === "/" ? "" : u.pathname;
3276
+ return u.host + (path.length > 32 ? path.slice(0, 31) + "\u2026" : path);
3277
+ } catch {
3278
+ return url.slice(0, 48);
3279
+ }
3280
+ }
3281
+ async function webTools(platform, opts = {}) {
3282
+ const list = await platform.list(opts.signal ? { signal: opts.signal } : void 0);
3283
+ const out = [];
3284
+ for (const name of WEB_TOOL_NAMES) {
3285
+ const info = list.find((t) => t.name === name);
3286
+ if (!info) continue;
3287
+ const isSearch = name === "web_search";
3288
+ out.push({
3289
+ name,
3290
+ description: info.description,
3291
+ parameters: info.parameters ?? { type: "object", properties: {} },
3292
+ readOnly: true,
3293
+ // A page may be long; web_fetch cuts it at its own max_chars (40 000 by default).
3294
+ maxResultChars: isSearch ? 16e3 : 42e3,
3295
+ ...isSearch ? { guidelines: GUIDELINES } : {},
3296
+ display: {
3297
+ icon: isSearch ? SEARCH_ICON : GLOBE_ICON,
3298
+ outcome: ({ details }) => {
3299
+ if (isSearch) {
3300
+ const n = details?.results?.length;
3301
+ return typeof n === "number" ? String(n) : void 0;
3302
+ }
3303
+ const title = details?.title;
3304
+ return title ? title.slice(0, 40) : void 0;
3305
+ }
3306
+ },
3307
+ async execute(args, ctx) {
3308
+ if (!isSearch && typeof args.url === "string") ctx.update(hostOf(args.url));
3309
+ const r = await platform.call(name, args, { signal: ctx.signal });
3310
+ const cost = r.usage?.total_cost;
3311
+ if (typeof cost === "number" && cost > 0) opts.onCost?.(cost);
3312
+ return { content: r.content, details: r.data };
3313
+ }
3314
+ });
3315
+ }
3316
+ return out;
3317
+ }
3318
+
3258
3319
  // src/dialogs.ts
3259
3320
  function isZh() {
3260
3321
  if (typeof document === "undefined") return false;
@@ -3610,6 +3671,10 @@ var Agent = class {
3610
3671
  __publicField(this, "workspace");
3611
3672
  __publicField(this, "tools");
3612
3673
  __publicField(this, "opts");
3674
+ /** `webTools` as configured (a function is read every turn). */
3675
+ __publicField(this, "web");
3676
+ /** The platform's web tools, loaded the first time they are offered. */
3677
+ __publicField(this, "webCache", null);
3613
3678
  __publicField(this, "history", []);
3614
3679
  __publicField(this, "committed", 0);
3615
3680
  __publicField(this, "droppedTurns", 0);
@@ -3656,6 +3721,7 @@ var Agent = class {
3656
3721
  seen.add(t.name);
3657
3722
  }
3658
3723
  this.tools = tools;
3724
+ this.web = opts.webTools ?? false;
3659
3725
  if (opts.serverTools?.length && (opts.tools?.length || this.workspace || opts.sandbox !== false || opts.askUser !== false)) {
3660
3726
  throw new Error("serverTools work only for an agent with no tools of its own (tools: [], workspace: null, sandbox: false, askUser: false) \u2014 the gateway runs that loop");
3661
3727
  }
@@ -3765,6 +3831,7 @@ var Agent = class {
3765
3831
  /** Changes settings for the runs that follow (a run in progress keeps its own). `undefined` leaves a field alone; `reasoningEffort: null` takes the model's default. */
3766
3832
  configure(patch) {
3767
3833
  if ("model" in patch) this.model = patch.model || void 0;
3834
+ if (typeof patch.webTools === "boolean") this.web = patch.webTools;
3768
3835
  if ("reasoningEffort" in patch) {
3769
3836
  const extra = { ...this.opts.extra ?? {} };
3770
3837
  if (patch.reasoningEffort) extra.reasoning_effort = patch.reasoningEffort;
@@ -4159,11 +4226,39 @@ var Agent = class {
4159
4226
  const [image, video, audio] = await Promise.all([this.accepts("image"), this.accepts("video"), this.accepts("audio")]);
4160
4227
  return { image, video, audio };
4161
4228
  }
4162
- /** The tools offered this turn: `vision` tools only while the model is known to take pictures. */
4229
+ /** Whether the platform's web tools are offered now (`webTools`, `configure({ webTools })`). */
4230
+ get webTools() {
4231
+ return this.webToolsAvailable && (typeof this.web === "function" ? !!this.web() : this.web);
4232
+ }
4233
+ /** The provider's platform has web tools (the RunApps client, SDK 0.19+). */
4234
+ get webToolsAvailable() {
4235
+ return !!this.provider.platformTools;
4236
+ }
4237
+ /** The tools offered this turn: `vision` tools only while the model is known to take pictures, the web tools while they are on. */
4163
4238
  async activeTools() {
4164
- if (!this.tools.some((t) => t.vision)) return this.tools;
4165
- const sees = await this.accepts("image");
4166
- return this.tools.filter((t) => !t.vision || sees === true);
4239
+ let tools = this.tools;
4240
+ if (tools.some((t) => t.vision)) {
4241
+ const sees = await this.accepts("image");
4242
+ tools = tools.filter((t) => !t.vision || sees === true);
4243
+ }
4244
+ if (this.webTools) {
4245
+ const web = await this.loadWeb();
4246
+ const own = new Set(tools.map((t) => t.name));
4247
+ const extra = web.filter((t) => !own.has(t.name));
4248
+ if (extra.length) tools = [...tools, ...extra];
4249
+ }
4250
+ return tools;
4251
+ }
4252
+ /** The web tools, asked of the platform once (a failure is asked again next turn). */
4253
+ loadWeb() {
4254
+ const platform = this.provider.platformTools;
4255
+ if (!platform) return Promise.resolve([]);
4256
+ this.webCache ?? (this.webCache = webTools(platform, { onCost: (usd) => this.addToolCost(usd) }).catch((err) => {
4257
+ this.webCache = null;
4258
+ console.warn("[agent] could not load the web tools:", err);
4259
+ return [];
4260
+ }));
4261
+ return this.webCache;
4167
4262
  }
4168
4263
  /** The system prompt for the next request (what the model is told). */
4169
4264
  async systemPrompt() {
@@ -4613,6 +4708,10 @@ Fix the call and try again.`);
4613
4708
  return;
4614
4709
  }
4615
4710
  }
4711
+ /** A platform tool's charge: added to the cost, not counted as a model call. */
4712
+ addToolCost(usd) {
4713
+ this._usage.total_cost = round(this._usage.total_cost + usd);
4714
+ }
4616
4715
  addUsage(u) {
4617
4716
  this._usage.total_cost = round(this._usage.total_cost + (u.total_cost ?? 0));
4618
4717
  this._usage.prompt_tokens += u.prompt_tokens ?? 0;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { Agent, type PromptContent } from "./agent.js";
2
- export { openAIProvider, runappsProvider, toProvider, ProviderError, ContextOverflowError, isContextOverflow, sseData, modelAccepts, type ContextOverflow, type OverflowCause, type ModelProvider, type ModelInfo, type ModelPrice, type InputKind, type OpenAIProviderOptions, type RunAppsClientLike } from "./provider.js";
2
+ export { openAIProvider, runappsProvider, toProvider, ProviderError, ContextOverflowError, isContextOverflow, sseData, modelAccepts, type ContextOverflow, type OverflowCause, type ModelProvider, type ModelInfo, type ModelPrice, type InputKind, type OpenAIProviderOptions, type RunAppsClientLike, type PlatformTools } from "./provider.js";
3
+ export { webTools, WEB_TOOL_NAMES } from "./web-tools.js";
3
4
  export type { ChatMessage, ContentPart, ChatTool, ChatToolCall, ChatCompletionParams, ChatCompletionChunk, ChatCompletion, Usage } from "./llm.js";
4
5
  import { Agent } from "./agent.js";
5
6
  import type { AgentOptions } from "./types.js";
package/dist/index.js CHANGED
@@ -5,6 +5,7 @@
5
5
  // `@runappsai/agent/node`.
6
6
  export { Agent } from "./agent.js";
7
7
  export { openAIProvider, runappsProvider, toProvider, ProviderError, ContextOverflowError, isContextOverflow, sseData, modelAccepts } from "./provider.js";
8
+ export { webTools, WEB_TOOL_NAMES } from "./web-tools.js";
8
9
  import { Agent } from "./agent.js";
9
10
  import { Workspace } from "./workspace.js";
10
11
  import { toProvider } from "./provider.js";
@@ -72,6 +72,32 @@ export interface ModelProvider {
72
72
  } | null>;
73
73
  /** Names the app's local storage (IndexedDB) when the host gives no `project`. */
74
74
  name?: string;
75
+ /**
76
+ * Tools the provider's platform runs (web search, reading pages), which
77
+ * the agent offers as its own with `webTools`. The RunApps client has
78
+ * them (`client.tools`); another provider leaves this out.
79
+ */
80
+ platformTools?: PlatformTools;
81
+ }
82
+ /** A platform's own tools: the list (with JSON Schema and price) and one call. */
83
+ export interface PlatformTools {
84
+ list(opts?: {
85
+ signal?: AbortSignal;
86
+ }): Promise<Array<{
87
+ name: string;
88
+ description: string;
89
+ parameters: Record<string, unknown>;
90
+ price?: number;
91
+ }>>;
92
+ call(name: string, args: Record<string, unknown>, init?: {
93
+ signal?: AbortSignal;
94
+ }): Promise<{
95
+ content: string;
96
+ data?: unknown;
97
+ usage?: {
98
+ total_cost?: number;
99
+ };
100
+ }>;
75
101
  }
76
102
  /** A failed model call. `status` is the HTTP status (0: no answer at all). */
77
103
  export declare class ProviderError extends Error {
@@ -131,6 +157,8 @@ export interface RunAppsClientLike {
131
157
  }>;
132
158
  get(path: string): Promise<Blob>;
133
159
  };
160
+ /** SDK 0.19+: the platform's tools (`webTools`). */
161
+ tools?: PlatformTools;
134
162
  projectName?: string;
135
163
  }
136
164
  /** The RunApps SDK client as a provider: the gateway's models and catalogue, the user's RunApps storage for `files:` skills. */
package/dist/provider.js CHANGED
@@ -96,6 +96,7 @@ export function runappsProvider(client) {
96
96
  // Only what the client really has: a stand-in without create() or a catalogue is still a provider.
97
97
  complete: client.chat.create ? (p, init) => client.chat.create(p, init) : undefined,
98
98
  models: client.models?.list ? async (o) => (await client.models.list(o)) : undefined,
99
+ platformTools: client.tools,
99
100
  readFile: files
100
101
  ? async (path, o) => {
101
102
  const st = await files.stat(path);
package/dist/types.d.ts CHANGED
@@ -290,7 +290,7 @@ export interface Skill {
290
290
  }
291
291
  export type RunEndReason = "done" | "aborted" | "max_turns" | "error";
292
292
  export interface AgentUsage {
293
- /** Sum of every model call's `total_cost` (the gateway's figure, before platform markup and creator fee). */
293
+ /** Sum of every model call's `total_cost` (the gateway's figure, before platform markup and creator fee), plus what the web tools charged. */
294
294
  total_cost: number;
295
295
  prompt_tokens: number;
296
296
  completion_tokens: number;
@@ -569,7 +569,18 @@ export interface AgentOptions {
569
569
  block: boolean;
570
570
  reason?: string;
571
571
  }>;
572
- /** Offer the gateway's server tools when the agent has no tools of its own. */
572
+ /**
573
+ * The platform's web tools — `web_search` and `web_fetch` — offered to
574
+ * the model beside the agent's own tools, run and billed by the platform
575
+ * per call (needs the RunApps client, SDK 0.19+; `agent.webToolsAvailable`).
576
+ * A function is read every turn; `agent.configure({ webTools })` switches
577
+ * it; the chat's globe button does that for the user.
578
+ */
579
+ webTools?: boolean | (() => boolean);
580
+ /**
581
+ * @deprecated Use `webTools`. The gateway's server tools, run inside the
582
+ * chat call, for an agent with no tools of its own.
583
+ */
573
584
  serverTools?: Array<"web_search" | "web_fetch" | "twitter_search">;
574
585
  /**
575
586
  * The `run_js` sandbox tool (default on): the model computes and runs
package/dist/ui.cjs CHANGED
@@ -504,21 +504,25 @@ var VirtualList = class {
504
504
  const anchorDelta = this.offsets[anchor] - scrollTop;
505
505
  const first = this.indexAt(Math.max(0, scrollTop - this.overscan));
506
506
  const last = Math.min(n - 1, this.indexAt(Math.min(total - 1, scrollTop + view + this.overscan)));
507
+ this.top.style.height = `${this.offsets[first]}px`;
508
+ this.bottom.style.height = `${total - this.offsets[last + 1]}px`;
507
509
  if (first !== this.first || last !== this.last || this.win.childElementCount !== last - first + 1) {
508
510
  const keep = new Set(this.rows.slice(first, last + 1));
509
- for (const [row, w] of this.wrappers) if (!keep.has(row)) {
511
+ const leaving = [...this.wrappers].filter(([row]) => !keep.has(row));
512
+ let prev = null;
513
+ for (let i = first; i <= last; i++) {
514
+ const w = this.wrapper(this.rows[i]);
515
+ if (w.parentNode !== this.win) this.win.insertBefore(w, prev ? prev.nextSibling : this.win.firstChild);
516
+ prev = w;
517
+ }
518
+ for (const [row, w] of leaving) {
510
519
  this.ro?.unobserve(w);
511
520
  w.remove();
512
521
  this.wrappers.delete(row);
513
522
  }
514
- const kids = [];
515
- for (let i = first; i <= last; i++) kids.push(this.wrapper(this.rows[i]));
516
- this.win.replaceChildren(...kids);
517
523
  this.first = first;
518
524
  this.last = last;
519
525
  }
520
- this.top.style.height = `${this.offsets[first]}px`;
521
- this.bottom.style.height = `${total - this.offsets[last + 1]}px`;
522
526
  let changed = false;
523
527
  for (let i = first; i <= last; i++) {
524
528
  const row = this.rows[i];
@@ -591,6 +595,7 @@ var I = {
591
595
  filePlus: (s = 13) => svg(s, '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M9 15h6M12 18v-6"/>'),
592
596
  filePen: (s = 13) => svg(s, '<path d="M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M13.4 20.3a1 1 0 0 0 .5-.3l6.9-6.9a1.4 1.4 0 0 0-2-2l-6.9 6.9a1 1 0 0 0-.3.5l-.4 1.8z"/>'),
593
597
  fileX: (s = 13) => svg(s, '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="m14.5 12.5-5 5M9.5 12.5l5 5"/>'),
598
+ globe: (s = 14) => svg(s, '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>'),
594
599
  search: (s = 13) => svg(s, '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/>'),
595
600
  braces: (s = 13) => svg(s, '<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/>'),
596
601
  message: (s = 13) => svg(s, '<path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/>'),
@@ -2077,6 +2082,14 @@ var STRINGS = {
2077
2082
  actRun: "ran {n} snippet(s)",
2078
2083
  actAsk: "asked you {n} time(s)",
2079
2084
  actOther: "used {name}",
2085
+ actWeb: "searched the web {n} time(s)",
2086
+ actBrowse: "read {n} web page(s)",
2087
+ ingWeb: "Searching the web",
2088
+ ingBrowse: "Reading",
2089
+ web: "Web",
2090
+ webOn: "Web search: on",
2091
+ webOff: "Web search: off",
2092
+ webHint: "When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed",
2080
2093
  runCode: "Run code",
2081
2094
  ingRead: "Reading",
2082
2095
  ingList: "Listing",
@@ -2327,6 +2340,14 @@ var STRINGS = {
2327
2340
  actRun: "\u8FD0\u884C\u4E86 {n} \u6BB5\u4EE3\u7801",
2328
2341
  actAsk: "\u8BE2\u95EE\u4E86\u4F60 {n} \u6B21",
2329
2342
  actOther: "\u8C03\u7528\u4E86 {name}",
2343
+ actWeb: "\u8054\u7F51\u641C\u7D22\u4E86 {n} \u6B21",
2344
+ actBrowse: "\u9605\u8BFB\u4E86 {n} \u4E2A\u7F51\u9875",
2345
+ ingWeb: "\u6B63\u5728\u8054\u7F51\u641C\u7D22",
2346
+ ingBrowse: "\u6B63\u5728\u9605\u8BFB",
2347
+ web: "\u8054\u7F51",
2348
+ webOn: "\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5F00\u542F",
2349
+ webOff: "\u8054\u7F51\u641C\u7D22\uFF1A\u5DF2\u5173\u95ED",
2350
+ webHint: "\u5F00\u542F\u540E AI \u53EF\u4EE5\u641C\u7D22\u548C\u9605\u8BFB\u7F51\u9875\uFF0C\u67E5\u8D44\u6599\u548C\u6700\u65B0\u4FE1\u606F\uFF1B\u6BCF\u6B21\u641C\u7D22\u3001\u6BCF\u8BFB\u4E00\u4E2A\u7F51\u9875\u6309\u6B21\u8BA1\u8D39",
2330
2351
  runCode: "\u8FD0\u884C\u4EE3\u7801",
2331
2352
  ingRead: "\u6B63\u5728\u8BFB\u53D6",
2332
2353
  ingList: "\u6B63\u5728\u67E5\u770B",
@@ -2842,6 +2863,7 @@ var CSS = tokenCSS() + `
2842
2863
  .ra-chat .ra-cbtn.icon{width:28px;padding:0;justify-content:center}
2843
2864
  .ra-chat .ra-cbtn:hover:not(:disabled){background:var(--ra-muted);color:var(--ra-fg)}
2844
2865
  .ra-chat .ra-cbtn svg{width:15px;height:15px}
2866
+ .ra-chat .ra-cbtn.ra-web.on{background:var(--ra-accent-subtle);color:var(--ra-accent-fg)}
2845
2867
  .ra-files{display:flex;flex-wrap:wrap;gap:6px;padding:0 0 6px}
2846
2868
  .ra-chip{display:inline-flex;align-items:center;gap:10px;max-width:min(100%,340px);height:44px;border:1px solid var(--ra-border);border-radius:12px;padding:0 12px 0 10px;font-size:14px;background:var(--ra-panel);white-space:nowrap}
2847
2869
  .ra-chip img{width:30px;height:30px;object-fit:cover;border-radius:6px;flex:none}
@@ -2948,7 +2970,9 @@ var TOOL_ICON = {
2948
2970
  list_files: I.folderOpen,
2949
2971
  search_files: I.search,
2950
2972
  run_js: I.braces,
2951
- ask_user: I.message
2973
+ ask_user: I.message,
2974
+ web_search: I.search,
2975
+ web_fetch: I.globe
2952
2976
  };
2953
2977
  function textOfContent(content) {
2954
2978
  if (typeof content === "string") return content;
@@ -2977,7 +3001,9 @@ var TOOL_KIND = {
2977
3001
  edit_file: "Edit",
2978
3002
  delete_file: "Delete",
2979
3003
  run_js: "Run",
2980
- ask_user: "Ask"
3004
+ ask_user: "Ask",
3005
+ web_search: "Web",
3006
+ web_fetch: "Browse"
2981
3007
  };
2982
3008
  var pathArg = (args) => args && typeof args === "object" && typeof args.path === "string" ? args.path : void 0;
2983
3009
  function statusOfResult(text) {
@@ -3323,7 +3349,7 @@ function renderChat(target, opts) {
3323
3349
  injectStyles();
3324
3350
  const lang = pickLocale(opts.locale);
3325
3351
  const t = STRINGS[lang];
3326
- const { toolSettings, client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, ...agentOpts } = opts;
3352
+ const { toolSettings, client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, ...agentOpts } = opts;
3327
3353
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
3328
3354
  const provider = providerOpt ? (0, import_index2.toProvider)(providerOpt) : clientOpt ? (0, import_index2.toProvider)(clientOpt) : givenAgent?.provider ?? null;
3329
3355
  const project = provider?.name ?? agentOpts.appName ?? "app";
@@ -3494,7 +3520,43 @@ function renderChat(target, opts) {
3494
3520
  if (a.id) actionBtns.set(a.id, { btn, a });
3495
3521
  return btn;
3496
3522
  });
3497
- left.append(attachBtn, ...hostActions, hint);
3523
+ const WEB_KEY = `__runapps_agent_chat:${project}:web`;
3524
+ const webShown = !!provider?.platformTools && (webSearchOpt ?? typeof agentOpts.webTools !== "function");
3525
+ let webOn = (() => {
3526
+ try {
3527
+ const v = localStorage.getItem(WEB_KEY);
3528
+ if (v !== null) return v === "1";
3529
+ } catch {
3530
+ }
3531
+ return agentOpts.webTools === true;
3532
+ })();
3533
+ const webBtn = h("button", "ra-cbtn ra-web");
3534
+ webBtn.type = "button";
3535
+ const drawWeb = () => {
3536
+ const label = webOn ? t.webOn : t.webOff;
3537
+ webBtn.innerHTML = I.globe(15) + (webOn ? `<span>${escapeHTML(t.web)}</span>` : "");
3538
+ webBtn.classList.toggle("on", webOn);
3539
+ webBtn.classList.toggle("icon", !webOn);
3540
+ webBtn.setAttribute("aria-pressed", String(webOn));
3541
+ webBtn.setAttribute("aria-label", label);
3542
+ webBtn.title = `${label}
3543
+ ${t.webHint}`;
3544
+ };
3545
+ drawWeb();
3546
+ if (!webShown) webBtn.style.display = "none";
3547
+ const applyWeb = (a) => {
3548
+ if (webShown) a.configure({ webTools: webOn });
3549
+ };
3550
+ webBtn.addEventListener("click", () => {
3551
+ webOn = !webOn;
3552
+ try {
3553
+ localStorage.setItem(WEB_KEY, webOn ? "1" : "0");
3554
+ } catch {
3555
+ }
3556
+ drawWeb();
3557
+ for (const a of live.values()) applyWeb(a);
3558
+ });
3559
+ left.append(attachBtn, webBtn, ...hostActions, hint);
3498
3560
  bar.append(left, acts);
3499
3561
  box.append(cmds, files, ta, bar, fileInput);
3500
3562
  const drop = h("div", "ra-drop", t.drop);
@@ -5990,6 +6052,7 @@ ${c.text}` })));
5990
6052
  if (agent !== a) clearNext();
5991
6053
  agent = a;
5992
6054
  live.set(a.id, a);
6055
+ applyWeb(a);
5993
6056
  unwatchBackground(a);
5994
6057
  ui.restore(parked.get(a.id) ?? []);
5995
6058
  parked.delete(a.id);
package/dist/vlist.js CHANGED
@@ -240,24 +240,30 @@ export class VirtualList {
240
240
  const anchorDelta = this.offsets[anchor] - scrollTop;
241
241
  const first = this.indexAt(Math.max(0, scrollTop - this.overscan));
242
242
  const last = Math.min(n - 1, this.indexAt(Math.min(total - 1, scrollTop + view + this.overscan)));
243
- // Reconcile the window.
243
+ // The spacers first: a row that holds the focus forces a layout the moment it leaves (the browser clears
244
+ // the focus), and a scroller that is short then pulls scrollTop back to its new end.
245
+ this.top.style.height = `${this.offsets[first]}px`;
246
+ this.bottom.style.height = `${total - this.offsets[last + 1]}px`;
247
+ // Reconcile the window. Only the rows entering and leaving are touched: taking one out and putting it
248
+ // back would lose its focus, its selection and the scroll position of every code block inside it.
244
249
  if (first !== this.first || last !== this.last || this.win.childElementCount !== last - first + 1) {
245
250
  const keep = new Set(this.rows.slice(first, last + 1));
246
- for (const [row, w] of this.wrappers)
247
- if (!keep.has(row)) {
248
- this.ro?.unobserve(w);
249
- w.remove();
250
- this.wrappers.delete(row);
251
- }
252
- const kids = [];
253
- for (let i = first; i <= last; i++)
254
- kids.push(this.wrapper(this.rows[i]));
255
- this.win.replaceChildren(...kids);
251
+ const leaving = [...this.wrappers].filter(([row]) => !keep.has(row));
252
+ let prev = null;
253
+ for (let i = first; i <= last; i++) {
254
+ const w = this.wrapper(this.rows[i]);
255
+ if (w.parentNode !== this.win)
256
+ this.win.insertBefore(w, prev ? prev.nextSibling : this.win.firstChild);
257
+ prev = w;
258
+ }
259
+ for (const [row, w] of leaving) {
260
+ this.ro?.unobserve(w);
261
+ w.remove();
262
+ this.wrappers.delete(row);
263
+ }
256
264
  this.first = first;
257
265
  this.last = last;
258
266
  }
259
- this.top.style.height = `${this.offsets[first]}px`;
260
- this.bottom.style.height = `${total - this.offsets[last + 1]}px`;
261
267
  // Measure what is shown; a change means another pass with the new sizes.
262
268
  let changed = false;
263
269
  for (let i = first; i <= last; i++) {
@@ -0,0 +1,15 @@
1
+ import type { PlatformTools } from "./provider.js";
2
+ import type { Tool } from "./types.js";
3
+ /** The platform tools `webTools` offers. */
4
+ export declare const WEB_TOOL_NAMES: readonly ["web_search", "web_fetch"];
5
+ /** lucide "globe". */
6
+ export declare const GLOBE_ICON: string;
7
+ /**
8
+ * The tools as the agent holds them. `onCost` gets what each call charged
9
+ * (USD, the creator's fee included); a call that fails throws, and costs
10
+ * nothing.
11
+ */
12
+ export declare function webTools(platform: PlatformTools, opts?: {
13
+ signal?: AbortSignal;
14
+ onCost?: (usd: number) => void;
15
+ }): Promise<Tool[]>;