@runappsai/agent 0.1.15 → 0.2.0

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/ui.cjs CHANGED
@@ -398,6 +398,20 @@ var VirtualList = class {
398
398
  this.win.replaceChildren();
399
399
  this.top.style.height = this.bottom.style.height = "0px";
400
400
  }
401
+ /**
402
+ * Puts row `i` at the top of the view and stops following the bottom. The
403
+ * rows above it are measured as they come into the window; the row stays
404
+ * where it is while they are (the layout anchors on the row at the top).
405
+ */
406
+ scrollToIndex(i) {
407
+ if (this.disposed || i < 0 || i >= this.rows.length) return;
408
+ this.pinned = null;
409
+ this.follow = false;
410
+ const total = this.computeOffsets();
411
+ this.bottom.style.height = `${total}px`;
412
+ this.setTop(this.offsets[i]);
413
+ this.layout();
414
+ }
401
415
  /** Jumps to the end and follows new output. */
402
416
  scrollToBottom() {
403
417
  this.pinned = null;
@@ -2148,7 +2162,7 @@ function debugPanel(opts) {
2148
2162
  ctx.textContent = "\u2014";
2149
2163
  });
2150
2164
  const sys = pre("\u2026", "tall");
2151
- void a.systemPrompt().then((p) => {
2165
+ void (a.systemPrompt?.() ?? Promise.resolve("(this agent does not expose its system prompt)")).then((p) => {
2152
2166
  sys.textContent = p;
2153
2167
  }).catch((err) => {
2154
2168
  sys.textContent = String(err);
@@ -2690,6 +2704,8 @@ var STRINGS = {
2690
2704
  delTurnMsg: "They are removed from the conversation; files stay as they are.",
2691
2705
  replyCost: "Cost: {cost}",
2692
2706
  replyUsage: "{in} in \xB7 {out} out \xB7 {calls} calls",
2707
+ older: "Load earlier messages",
2708
+ olderBusy: "Wait for the reply to finish, then load earlier messages.",
2693
2709
  rewindMsg: "The conversation after it is dropped and the message goes back into the composer.",
2694
2710
  rewindFiles: "Also restore the directory's files to that moment",
2695
2711
  rewindGone: "This message is no longer in the conversation.",
@@ -2790,6 +2806,7 @@ var STRINGS = {
2790
2806
  cmdsMore: "Templates (/name) and skills (/skill:name) are listed as you type.",
2791
2807
  autoCompact: "Auto-compaction",
2792
2808
  autoCompactAt: "when less than {n} tokens are left",
2809
+ autoCompactFull: "when the context is full",
2793
2810
  directory: "Directory",
2794
2811
  messagesLabel: "Messages",
2795
2812
  cmdArgs: { compact: "[focus]", model: "[name]", effort: "[level]" },
@@ -3003,6 +3020,8 @@ var STRINGS = {
3003
3020
  delTurnMsg: "\u8FD9\u6761\u63D0\u95EE\u548C\u5B83\u7684\u56DE\u7B54\u4F1A\u4ECE\u5BF9\u8BDD\u4E2D\u5220\u9664\uFF0C\u6587\u4EF6\u4E0D\u53D7\u5F71\u54CD\u3002",
3004
3021
  replyCost: "\u8D39\u7528\uFF1A{cost}",
3005
3022
  replyUsage: "\u8F93\u5165 {in} \xB7 \u8F93\u51FA {out} \xB7 {calls} \u6B21\u8C03\u7528",
3023
+ older: "\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F",
3024
+ olderBusy: "\u7B49\u8FD9\u6B21\u56DE\u590D\u7ED3\u675F\u540E\u518D\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F\u3002",
3006
3025
  rewindMsg: "\u5B83\u4E4B\u540E\u7684\u5BF9\u8BDD\u4F1A\u88AB\u5220\u9664\uFF0C\u6D88\u606F\u5185\u5BB9\u653E\u56DE\u8F93\u5165\u6846\u3002",
3007
3026
  rewindFiles: "\u540C\u65F6\u628A\u76EE\u5F55\u91CC\u7684\u6587\u4EF6\u6062\u590D\u5230\u90A3\u4E00\u523B",
3008
3027
  rewindGone: "\u8FD9\u6761\u6D88\u606F\u5DF2\u4E0D\u5728\u5BF9\u8BDD\u91CC\uFF08\u53EF\u80FD\u5DF2\u88AB\u538B\u7F29\uFF09\u3002",
@@ -3103,6 +3122,7 @@ var STRINGS = {
3103
3122
  cmdsMore: "\u6A21\u677F\uFF08/\u540D\u79F0\uFF09\u548C Skill\uFF08/skill:\u540D\u79F0\uFF09\u5728\u8F93\u5165\u65F6\u5217\u51FA\u3002",
3104
3123
  autoCompact: "\u81EA\u52A8\u538B\u7F29",
3105
3124
  autoCompactAt: "\u5269\u4F59\u4E0D\u8DB3 {n} tokens \u65F6",
3125
+ autoCompactFull: "\u4E0A\u4E0B\u6587\u7528\u6EE1\u65F6",
3106
3126
  directory: "\u76EE\u5F55",
3107
3127
  messagesLabel: "\u6D88\u606F",
3108
3128
  cmdArgs: { compact: "[\u91CD\u70B9]", model: "[\u540D\u79F0]", effort: "[\u6863\u4F4D]" },
@@ -3341,6 +3361,8 @@ var CSS = tokenCSS() + `
3341
3361
  @keyframes ra-shimmer{from{background-position:100% 0}to{background-position:0 0}}
3342
3362
  @media (prefers-reduced-motion:reduce){.ra-pending>span{animation:none;color:var(--ra-fg-muted);background:none}}
3343
3363
  .ra-time{text-align:center;font-size:12px;color:var(--ra-fg-muted);padding:14px 0 2px}
3364
+ .ra-olderrow{display:flex;justify-content:center;padding:6px 0 2px}
3365
+ .ra-chat .ra-older{font-size:12px;color:var(--ra-fg-muted)}
3344
3366
  .ra-work{border-bottom:1px solid var(--ra-border);padding-bottom:6px;margin-bottom:4px}
3345
3367
  .ra-work>summary{display:inline-flex;align-items:center;gap:4px;font-size:13px;color:var(--ra-fg-muted);cursor:pointer;list-style:none;user-select:none;padding:2px 0}
3346
3368
  .ra-work>summary::-webkit-details-marker{display:none}
@@ -3393,6 +3415,8 @@ var CSS = tokenCSS() + `
3393
3415
  .ra-tool>summary .ra-chev{color:var(--ra-fg-muted);transition:transform .15s}
3394
3416
  .ra-tool[open]>summary .ra-chev{transform:rotate(90deg)}
3395
3417
  .ra-tool .ra-ticon{width:20px;height:20px;border-radius:4px;background:var(--ra-accent-subtle);color:var(--ra-accent-fg);display:inline-flex;align-items:center;justify-content:center}
3418
+ .ra-tool .ra-ticon[data-tone="warning"]{background:var(--ra-warn-bg);color:var(--ra-warn-fg)}
3419
+ .ra-tool .ra-ticon[data-tone="danger"]{background:var(--ra-red-subtle);color:var(--ra-red)}
3396
3420
  .ra-tool.fail .ra-ticon{background:var(--ra-red-subtle);color:var(--ra-red)}
3397
3421
  .ra-tool .ra-tname{font-weight:600;white-space:nowrap}
3398
3422
  .ra-tool .ra-tname.own{font-weight:500;min-width:0;overflow:hidden;text-overflow:ellipsis}
@@ -3444,6 +3468,9 @@ var CSS = tokenCSS() + `
3444
3468
  .ra-q .ra-opt small{display:block;color:var(--ra-fg-muted);font-size:12px}
3445
3469
  .ra-q .ra-field{border:1px solid var(--ra-border);border-radius:6px;padding:6px 10px;background:var(--ra-bg);width:100%;font-size:14px}
3446
3470
  .ra-q .ra-field:focus{border-color:var(--ra-accent)}
3471
+ .ra-q .ra-field.bad{border-color:var(--ra-red)}
3472
+ .ra-q .ra-form{display:flex;flex-direction:column;gap:8px;margin:2px 0 4px}
3473
+ .ra-q .ra-ff{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--ra-fg-muted)}
3447
3474
  .ra-q textarea.ra-field{min-height:96px;max-height:200px;resize:vertical}
3448
3475
  .ra-btns{display:flex;justify-content:flex-end;gap:8px}
3449
3476
  .ra-cbody{margin:2px 0 10px;max-height:min(60vh,560px);overflow:auto;min-width:0}
@@ -3906,10 +3933,64 @@ function inlineUI(askArea, toasts, t, onChange) {
3906
3933
  }
3907
3934
  card.append(list);
3908
3935
  const row = h("div", "ra-btns");
3909
- row.append(btn(t.cancel, "ghost", () => done(null)), btn(t.ok, "solid", () => {
3910
- const picked = inputs.filter((i) => i.checked).map((i) => i.value === "__other__" ? other?.value.trim() ?? "" : i.value).filter(Boolean);
3911
- if (picked.length) done(picked);
3912
- }));
3936
+ const pickedNow = () => inputs.filter((i) => i.checked).map((i) => i.value === "__other__" ? other?.value.trim() ?? "" : i.value).filter(Boolean);
3937
+ const min = opts.multi ? opts.min ?? 1 : 1, max = opts.multi ? opts.max : void 0;
3938
+ const fits = (n) => n >= min && (max === void 0 || n <= max);
3939
+ const okBtn = btn(t.ok, "solid", () => {
3940
+ const picked = pickedNow();
3941
+ if (fits(picked.length)) done(picked);
3942
+ });
3943
+ if (opts.multi && (opts.min !== void 0 || opts.max !== void 0)) {
3944
+ const sync = () => {
3945
+ okBtn.disabled = !fits(pickedNow().length);
3946
+ };
3947
+ list.addEventListener("change", sync);
3948
+ list.addEventListener("input", sync);
3949
+ sync();
3950
+ }
3951
+ row.append(btn(t.cancel, "ghost", () => done(null)), okBtn);
3952
+ card.append(row);
3953
+ }, null, opts.signal),
3954
+ form: (title, fields, opts = {}) => open((card, done) => {
3955
+ head(card, title, opts.message);
3956
+ const box = h("div", "ra-form");
3957
+ const inputs = fields.map((f) => {
3958
+ const label = h("label", "ra-ff");
3959
+ label.append(h("span", "", (f.label ?? f.name) + (f.required ? " *" : "")));
3960
+ const input = h("input", "ra-field");
3961
+ input.type = f.type === "number" ? "number" : "text";
3962
+ input.name = f.name;
3963
+ if (f.type === "number") input.step = "any";
3964
+ if (f.placeholder) input.placeholder = f.placeholder;
3965
+ if (f.initial !== void 0) input.value = String(f.initial);
3966
+ label.append(input);
3967
+ box.append(label);
3968
+ return { f, input };
3969
+ });
3970
+ const submit = () => {
3971
+ const out = {};
3972
+ for (const { f, input } of inputs) {
3973
+ const raw = input.value.trim();
3974
+ const bad = !raw && f.required || !!raw && f.type === "number" && !Number.isFinite(Number(raw));
3975
+ input.classList.toggle("bad", bad);
3976
+ if (bad) {
3977
+ input.focus();
3978
+ return;
3979
+ }
3980
+ if (raw) out[f.name] = f.type === "number" ? Number(raw) : raw;
3981
+ }
3982
+ done(out);
3983
+ };
3984
+ box.addEventListener("keydown", (ev) => {
3985
+ const e = ev;
3986
+ if (e.key === "Enter" && !e.isComposing) {
3987
+ e.preventDefault();
3988
+ submit();
3989
+ }
3990
+ });
3991
+ card.append(box);
3992
+ const row = h("div", "ra-btns");
3993
+ row.append(btn(t.cancel, "ghost", () => done(null)), btn(opts.ok ?? t.submit, "solid", submit));
3913
3994
  card.append(row);
3914
3995
  }, null, opts.signal),
3915
3996
  input: (title, opts = {}) => open((card, done) => {
@@ -3984,7 +4065,8 @@ function renderChat(target, opts) {
3984
4065
  injectStyles();
3985
4066
  const lang = pickLocale(opts.locale);
3986
4067
  const t = STRINGS[lang];
3987
- 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, fileDialog: fileDialogOpt2, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, schedule: scheduleOpt, ...agentOpts } = opts;
4068
+ 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, fileDialog: fileDialogOpt2, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, webSearch: webSearchOpt, schedule: scheduleOpt, queue: queueOpt, replyActions, clearButton, commands: commandsOpt, uploadImage, headerStart, ...agentOpts } = opts;
4069
+ const canQueue = queueOpt !== false;
3988
4070
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
3989
4071
  setFileDialog(fileDialogOpt2);
3990
4072
  const provider = providerOpt ? (0, import_index2.toProvider)(providerOpt) : clientOpt ? (0, import_index2.toProvider)(clientOpt) : givenAgent?.provider ?? null;
@@ -4061,7 +4143,7 @@ function renderChat(target, opts) {
4061
4143
  clearBtn.style.display = "none";
4062
4144
  let oneChat = false;
4063
4145
  const syncClear = () => {
4064
- clearBtn.style.display = oneChat && agent?.messages.length ? "" : "none";
4146
+ clearBtn.style.display = clearButton !== false && oneChat && agent?.messages.length ? "" : "none";
4065
4147
  };
4066
4148
  const useBtn = h("button", "ra-btn ghost ra-usebtn");
4067
4149
  useBtn.type = "button";
@@ -4075,8 +4157,8 @@ function renderChat(target, opts) {
4075
4157
  btn.setAttribute("aria-label", label);
4076
4158
  if (!btn.title) btn.title = label;
4077
4159
  }
4078
- for (const el of [...headerActions ?? [], ...headerEnd ?? [], ...composerTop ? [composerTop] : [], ...emptyState instanceof HTMLElement ? [emptyState] : []]) el.classList.add("ra-host");
4079
- head.append(titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, schedBtn, histBtn, newBtn, clearBtn, ...headerActions ?? [], setBtn, ...headerEnd ?? []);
4160
+ for (const el of [...headerStart ?? [], ...headerActions ?? [], ...headerEnd ?? [], ...composerTop ? [composerTop] : [], ...emptyState instanceof HTMLElement ? [emptyState] : []]) el.classList.add("ra-host");
4161
+ head.append(...headerStart ?? [], titleEl, modelEl, h("span", "ra-sp"), useBtn, debugBtn, filesBtn, skillsBtn, schedBtn, histBtn, newBtn, clearBtn, ...headerActions ?? [], setBtn, ...headerEnd ?? []);
4080
4162
  if (title === false) head.style.display = "none";
4081
4163
  const log = h("div", "ra-log");
4082
4164
  const inner = h("div", "ra-col");
@@ -4338,7 +4420,7 @@ ${t.webHint}`;
4338
4420
  notify: (m, l) => ui.notify(m, l)
4339
4421
  });
4340
4422
  const restorable = (a) => !!a.workspace && typeof wsOpt === "function" && !a.workspace.root;
4341
- const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || a.queued.length > 0 || waiting.has(a.id)));
4423
+ const background = () => [...live.values()].filter((a) => a !== agent && (a.busy || (a.queued?.length ?? 0) > 0 || waiting.has(a.id)));
4342
4424
  const titleOfAgent = (a) => {
4343
4425
  const text = a.title ?? (0, import_index2.titleOf)({ v: 2, id: a.id, messages: a.messages, usage: a.usage, droppedTurns: 0, savedAt: 0 });
4344
4426
  return text === import_index2.UNTITLED ? t.untitled : text.length > 40 ? text.slice(0, 37) + "\u2026" : text;
@@ -4387,7 +4469,7 @@ ${t.webHint}`;
4387
4469
  ui.notify(`${titleOfAgent(a)} \xB7 ${t.finished}`);
4388
4470
  setTimeout(() => {
4389
4471
  if (!mounted) return;
4390
- if (agent !== a && !a.busy && !a.queued.length && !waiting.has(a.id)) {
4472
+ if (agent !== a && !a.busy && !a.queued?.length && !waiting.has(a.id)) {
4391
4473
  live.delete(a.id);
4392
4474
  unwatchBackground(a);
4393
4475
  release(a);
@@ -4573,7 +4655,7 @@ ${t.webHint}`;
4573
4655
  back.title = t.rewind;
4574
4656
  back.setAttribute("aria-label", t.rewind);
4575
4657
  back.addEventListener("click", () => void rewindTo(row));
4576
- foot.append(time, copy, back);
4658
+ foot.append(time, copy, ...replyActions?.rewind === false ? [] : [back]);
4577
4659
  el.addEventListener("mouseenter", () => row.update());
4578
4660
  row.update = () => {
4579
4661
  const ts = tsOf(row.msg);
@@ -4729,12 +4811,12 @@ ${t.webHint}`;
4729
4811
  ui.cancelAll();
4730
4812
  await a.abort();
4731
4813
  }
4732
- await a.remove(turn.start, turn.end);
4814
+ await a.remove?.(turn.start, turn.end);
4733
4815
  } catch (err) {
4734
4816
  ui.notify(err.message, "error");
4735
4817
  }
4736
4818
  })());
4737
- foot.append(copy, again, del);
4819
+ foot.append(copy, ...replyActions?.retry === false ? [] : [again], ...replyActions?.delete === false ? [] : [del]);
4738
4820
  const u = last.runUsage;
4739
4821
  if (u && u.calls) {
4740
4822
  const show = (currency) => {
@@ -4763,7 +4845,7 @@ ${t.webHint}`;
4763
4845
  const m = /^<file name="([^"]*)">\n([\s\S]*)\n<\/file>$/.exec(p.text);
4764
4846
  if (m) inline.set(m[1], m[2]);
4765
4847
  }
4766
- const images = parts.flatMap((p) => p.type === "image_url" && p.image_url.url.startsWith("data:") ? [p.image_url.url] : []);
4848
+ const images = imagesOf(parts);
4767
4849
  const files2 = [], paths = [], missing = [];
4768
4850
  for (const line of block.text.split("\n").slice(1)) {
4769
4851
  const a = parseAttachLine(line);
@@ -4993,6 +5075,7 @@ ${t.webHint}`;
4993
5075
  const d = displayOf(name), label = labelOf(name, args);
4994
5076
  const icon = h("span", "ra-ticon");
4995
5077
  icon.innerHTML = d?.icon ?? (TOOL_ICON[name] ?? I.wrench)();
5078
+ if (d?.tone) icon.dataset.tone = d.tone;
4996
5079
  const end = h("span", "ra-tend");
4997
5080
  end.innerHTML = '<span class="ra-spin"></span>';
4998
5081
  sum.innerHTML = `<span class="ra-chev">${I.chev()}</span>`;
@@ -5107,7 +5190,7 @@ ${t.webHint}`;
5107
5190
  list.schedule();
5108
5191
  return card;
5109
5192
  };
5110
- const imagesOf = (content) => Array.isArray(content) ? content.flatMap((p) => p.type === "image_url" && /^(data:image\/|https?:)/.test(p.image_url.url) ? [p.image_url.url] : []) : [];
5193
+ const imagesOf = (content) => Array.isArray(content) ? content.flatMap((p) => p.type === "image_url" && /^(data:image\/|https?:|\/(?!\/))/.test(p.image_url.url) ? [p.image_url.url] : []) : [];
5111
5194
  const offerFile = async (card) => {
5112
5195
  const ws = agent?.workspace;
5113
5196
  const d = displayOf(card.name), a = card.args;
@@ -5245,6 +5328,26 @@ ${t.webHint}`;
5245
5328
  active = null;
5246
5329
  let last = null;
5247
5330
  let lastUserTs;
5331
+ const src = agent;
5332
+ if (src?.hasOlder && src.loadOlder) {
5333
+ const b = h("button", "ra-btn ghost ra-older");
5334
+ b.type = "button";
5335
+ b.textContent = t.older;
5336
+ b.addEventListener("click", () => {
5337
+ if (src.busy) {
5338
+ ui.notify(t.olderBusy, "warning");
5339
+ return;
5340
+ }
5341
+ b.disabled = true;
5342
+ void src.loadOlder().catch((err) => {
5343
+ b.disabled = false;
5344
+ ui.notify(err.message, "error");
5345
+ });
5346
+ });
5347
+ const el = h("div", "ra-olderrow");
5348
+ el.append(b);
5349
+ addRow({ render: () => el, el });
5350
+ }
5248
5351
  const flush = (atEnd = false) => {
5249
5352
  if (!last) return;
5250
5353
  const m = last;
@@ -5361,15 +5464,18 @@ ${t.webHint}`;
5361
5464
  const schedTools = schedStore && schedCfg.tools !== false ? scheduleTools(schedStore, { ...schedCfg, onChange: () => refreshSched() }).map((x) => ({ ...x, display: { ...x.display, icon: I.clock(), label: schedLabels[x.name] } })) : [];
5362
5465
  const chatTools = [...agentOpts.tools ?? [], ...nextPrompt ? [nextPromptTool] : [], ...schedTools];
5363
5466
  const hiddenTools = new Set(chatTools.filter((x) => x.display?.hidden).map((x) => x.name));
5467
+ const hideToolsOf = (a) => {
5468
+ for (const x of a.tools ?? []) if (x.display?.hidden) hiddenTools.add(x.name);
5469
+ };
5364
5470
  const syncSend = () => {
5365
5471
  const busy = root.dataset.busy === "1", any = !!(ta.value.trim() || pendingFiles.length || pendingContext.length);
5366
5472
  sendBtn.style.display = !busy && any ? "" : "none";
5367
- steerBtn.style.display = fuBtn.style.display = busy && any ? "" : "none";
5473
+ steerBtn.style.display = fuBtn.style.display = canQueue && busy && any ? "" : "none";
5368
5474
  };
5369
5475
  const setBusy = (busy) => {
5370
5476
  root.dataset.busy = busy ? "1" : "";
5371
- ta.placeholder = busy ? fill(t.placeholderBusy) : nextSuggestion ?? placeholder ?? t.placeholder;
5372
- hint.textContent = fill(busy ? t.hintBusy : nextSuggestion ? t.hintNext : t.hintIdle);
5477
+ ta.placeholder = busy && canQueue ? fill(t.placeholderBusy) : nextSuggestion ?? placeholder ?? t.placeholder;
5478
+ hint.textContent = fill(busy && canQueue ? t.hintBusy : nextSuggestion ? t.hintNext : t.hintIdle);
5373
5479
  syncSend();
5374
5480
  stopBtn.style.display = busy ? "" : "none";
5375
5481
  renderQueue();
@@ -5400,18 +5506,18 @@ ${t.webHint}`;
5400
5506
  const actions = (item) => {
5401
5507
  const box2 = h("span", "ra-qa");
5402
5508
  if (item.kind !== "steer") box2.append(btn(I.enter(), t.sendNow, () => {
5403
- if (a.dequeue(item.message)) a.steer(item.message.content);
5509
+ if (a.dequeue?.(item.message)) a.steer?.(item.message.content);
5404
5510
  renderQueue();
5405
5511
  }));
5406
5512
  box2.append(btn(I.pen(), t.editQueued, () => {
5407
- if (!a.dequeue(item.message)) return;
5513
+ if (!a.dequeue?.(item.message)) return;
5408
5514
  ta.value = ta.value.trim() ? `${textOf(item.message)}
5409
5515
  ${ta.value}` : textOf(item.message);
5410
5516
  ta.focus();
5411
5517
  renderQueue();
5412
5518
  }));
5413
5519
  box2.append(btn(I.x(14), t.remove, () => {
5414
- a.dequeue(item.message);
5520
+ a.dequeue?.(item.message);
5415
5521
  renderQueue();
5416
5522
  }));
5417
5523
  return box2;
@@ -5659,6 +5765,14 @@ ${a.text}
5659
5765
  parts.push({ type: "video_url", video_url: { url: b64 } });
5660
5766
  }
5661
5767
  if (a.image && !blind && a.file.size <= MAX_IMAGE_PART) {
5768
+ if (uploadImage) {
5769
+ try {
5770
+ parts.push({ type: "image_url", image_url: { url: await uploadImage(a.file) } });
5771
+ } catch (err) {
5772
+ ui.notify(`${a.name}: ${err?.message || String(err)}`, "error");
5773
+ }
5774
+ continue;
5775
+ }
5662
5776
  const b64 = await new Promise((res) => {
5663
5777
  const r = new FileReader();
5664
5778
  r.onload = () => res(String(r.result));
@@ -5682,6 +5796,7 @@ ${lines.join("\n")}` });
5682
5796
  if (!text && !pendingFiles.length && !pendingContext.length || !agent || sending) return;
5683
5797
  clearNext();
5684
5798
  if (runBuiltin(text)) return;
5799
+ if (!canQueue && (agent.busy || compacting)) return;
5685
5800
  if (compacting) mode = "followUp";
5686
5801
  const a = agent;
5687
5802
  const taken = pendingFiles.splice(0);
@@ -5723,8 +5838,8 @@ ${c.text}` })));
5723
5838
  await a.prompt(content);
5724
5839
  return;
5725
5840
  }
5726
- if (mode === "steer") a.steer(content);
5727
- else void a.followUp(content).catch(() => void 0);
5841
+ if (mode === "steer") a.steer?.(content);
5842
+ else void a.followUp?.(content).catch(() => void 0);
5728
5843
  renderQueue();
5729
5844
  } catch (err) {
5730
5845
  awaitingRow = null;
@@ -6158,7 +6273,7 @@ ${c.text}` })));
6158
6273
  const b = h("button");
6159
6274
  b.type = "button";
6160
6275
  const bg = s ? live.get(s.id) : void 0;
6161
- const state = s && bg && bg !== cur ? waiting.has(s.id) ? ` \xB7 ${t.waitingAnswer}` : bg.busy || bg.queued.length ? ` \xB7 ${t.running}` : "" : "";
6276
+ const state = s && bg && bg !== cur ? waiting.has(s.id) ? ` \xB7 ${t.waitingAnswer}` : bg.busy || bg.queued?.length ? ` \xB7 ${t.running}` : "" : "";
6162
6277
  const name = h("span", "ra-mt");
6163
6278
  if (state && !waiting.has(s.id)) name.append(h("span", "ra-spin"));
6164
6279
  name.append(h("span", "ra-mtt", (s ? s.title : titleOfAgent(cur)) || t.untitled));
@@ -6381,14 +6496,14 @@ ${task.prompt}`;
6381
6496
  watchBackground(a);
6382
6497
  }
6383
6498
  }
6384
- if (!givenAgent && !oneChat) a.setTitle(`\u23F0 ${task.name}`);
6499
+ if (!givenAgent && !oneChat) a.setTitle?.(`\u23F0 ${task.name}`);
6385
6500
  ui.notify(t.schedStarted.replace("{name}", task.name));
6386
6501
  const r = a === agent ? await promptFromHost(text) : await a.prompt(text);
6387
6502
  refreshHistCount();
6388
6503
  if (r.reason === "error" || r.reason === "max_turns") ui.notify(t.schedFailed.replace("{name}", task.name).replace("{error}", r.error?.message ?? r.reason), "warning");
6389
6504
  return { status: r.reason === "done" ? "ok" : r.reason === "aborted" ? "stopped" : "error", ...r.error ? { note: r.error.message } : r.reason === "max_turns" ? { note: "turn limit" } : {}, ...r.usage?.total_cost ? { cost: r.usage.total_cost } : {} };
6390
6505
  };
6391
- const schedIdle = () => mounted && !switching && !!agent && asked === 0 && waiting.size === 0 && ![...live.values()].some((a) => a.busy || a.queued.length > 0) && !(document.activeElement === ta && ta.value.trim());
6506
+ const schedIdle = () => mounted && !switching && !!agent && asked === 0 && waiting.size === 0 && ![...live.values()].some((a) => a.busy || (a.queued?.length ?? 0) > 0) && !(document.activeElement === ta && ta.value.trim());
6392
6507
  const scheduler = schedStore ? new Scheduler({ store: schedStore, run: runScheduled, idle: schedIdle, lockPrefix: `__runapps_agent_chat:${project}:schedules`, onChange: () => refreshSched() }) : null;
6393
6508
  if (scheduler) {
6394
6509
  const again = () => setTimeout(() => void scheduler.tick(), 1500);
@@ -6731,7 +6846,7 @@ ${task.prompt}`;
6731
6846
  compacting = true;
6732
6847
  let summary = null;
6733
6848
  try {
6734
- summary = await a.summarize(asked2?.msg);
6849
+ summary = await a.summarize?.(asked2?.msg) ?? null;
6735
6850
  } finally {
6736
6851
  compacting = false;
6737
6852
  closeActive();
@@ -6740,7 +6855,7 @@ ${task.prompt}`;
6740
6855
  await (oneChat ? clearConversation() : newSession().then(() => void 0));
6741
6856
  const b = agent;
6742
6857
  if (summary) {
6743
- await b.seed(summary);
6858
+ await b.seed?.(summary);
6744
6859
  renderHistory(b.messages);
6745
6860
  showUsage_(b);
6746
6861
  } else if (a.messages.length > 1) ui.notify(t.ovNoSummary, "warning");
@@ -6927,7 +7042,7 @@ ${task.prompt}`;
6927
7042
  else ui.notify(t.debugOff);
6928
7043
  } }
6929
7044
  ];
6930
- const builtinCommands = () => builtins.filter((b) => (b.name !== "files" || !!agent?.workspace && filesOpt !== false) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || !givenAgent && !!agent?.workspace && !oneChat)).map((b) => ({ name: b.name, description: b.name === "new" && oneChat ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
7045
+ const builtinCommands = () => builtins.filter((b) => (!commandsOpt || commandsOpt.includes(b.name)) && (b.name !== "files" || !!agent?.workspace && filesOpt !== false) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || !givenAgent && !!agent?.workspace && !oneChat)).map((b) => ({ name: b.name, description: b.name === "new" && oneChat ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
6931
7046
  const runBuiltin = (text) => {
6932
7047
  const m = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text);
6933
7048
  if (!m) return false;
@@ -6976,7 +7091,7 @@ ${task.prompt}`;
6976
7091
  const cap2 = (x) => x.charAt(0).toUpperCase() + x.slice(1);
6977
7092
  const compactLine = (a, window2) => {
6978
7093
  const c = a.compactionFor(window2);
6979
- return `${c.summarize ? t.autoCompact : t.autoTrim}: ${t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens))}`;
7094
+ return `${c.summarize ? t.autoCompact : t.autoTrim}: ${c.reserveTokens > 0 ? t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens)) : t.autoCompactFull}`;
6980
7095
  };
6981
7096
  const pctOf = (used, window2) => {
6982
7097
  const p = used / window2;
@@ -7045,6 +7160,7 @@ ${task.prompt}`;
7045
7160
  const attach = async (a) => {
7046
7161
  for (const u of unsub) u();
7047
7162
  unsub = [];
7163
+ hideToolsOf(a);
7048
7164
  if (a.workspace) {
7049
7165
  const ws = a.workspace;
7050
7166
  unsub.push(ws.onChange((c) => {
@@ -7122,6 +7238,19 @@ ${task.prompt}`;
7122
7238
  showUsage_(a);
7123
7239
  }
7124
7240
  });
7241
+ on("history", (ev) => {
7242
+ if (agent !== a) return;
7243
+ const before = list.length, hadOlder = before > 0 && list.rows[0]?.el?.classList.contains("ra-olderrow") === true;
7244
+ const following = list.follow, top = log.scrollTop;
7245
+ renderHistory(a.messages);
7246
+ if (ev.reason === "older") list.scrollToIndex(Math.max(0, list.length - (before - (hadOlder ? 1 : 0))));
7247
+ else if (ev.reason === "newer" && !following) {
7248
+ list.follow = false;
7249
+ log.scrollTop = top;
7250
+ list.layout();
7251
+ }
7252
+ showUsage_(a);
7253
+ });
7125
7254
  on("text_delta", (ev) => {
7126
7255
  const act = ensureActive();
7127
7256
  clearPending(act);
@@ -7211,7 +7340,7 @@ ${task.prompt}`;
7211
7340
  if (!ev.summary && ev.runId && trimNoted === ev.runId) return;
7212
7341
  if (!ev.summary) trimNoted = ev.runId ?? null;
7213
7342
  const first = a.messages[0];
7214
- const s = first && typeof first.content === "string" ? (0, import_index2.summaryOf)(first) : null;
7343
+ const s = ev.summaryText ?? (first && typeof first.content === "string" ? (0, import_index2.summaryOf)(first) : null);
7215
7344
  addNote(ev.summary ? t.compacted : t.trimmed, ev.summary && s ? s : void 0);
7216
7345
  });
7217
7346
  on("run_end", (r) => {
@@ -7274,7 +7403,7 @@ ${task.prompt}`;
7274
7403
  if (id && id === agent?.id) return agent;
7275
7404
  const prev = agent;
7276
7405
  if (prev) {
7277
- if (prev.busy || prev.queued.length > 0) {
7406
+ if (prev.busy || (prev.queued?.length ?? 0) > 0) {
7278
7407
  if (background().length >= MAX_BACKGROUND) {
7279
7408
  ui.notify(t.bgLimit.replace("{n}", String(background().length)), "warning");
7280
7409
  return prev;
@@ -7300,7 +7429,7 @@ ${task.prompt}`;
7300
7429
  await ready;
7301
7430
  const a = agent ?? givenAgent;
7302
7431
  ui.cancelAll();
7303
- await a.clear();
7432
+ await a.clear?.();
7304
7433
  if (agent === a || givenAgent === a) {
7305
7434
  renderHistory(a.messages);
7306
7435
  showUsage_(a);
@@ -7384,6 +7513,9 @@ ${task.prompt}`;
7384
7513
  debugOn = on;
7385
7514
  applyDebug();
7386
7515
  },
7516
+ setTitle(text) {
7517
+ titleEl.textContent = text;
7518
+ },
7387
7519
  updateComposerAction(id, patch) {
7388
7520
  const e = actionBtns.get(id);
7389
7521
  if (!e) return;
package/dist/ui.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { renderChat, enhanceSelect, type ChatOptions, type ChatHandle, type ComposerAction, type SettingsField, type SettingsTab } from "./chat.js";
2
2
  export type { FileDialog } from "./dom.js";
3
+ export type { ChatAgent, FormField } from "./index.js";
3
4
  export { selectBox, type SelectBox, type SelectOption as SelectBoxOption } from "./select.js";
4
5
  export { VirtualList, type VRow, type VListOptions } from "./vlist.js";
5
6
  export { CHAT_PALETTES, CHAT_COLOR_TOKENS, CHAT_SHARED_TOKENS, type ChatPalette, type ChatVars, type ChatToken, type ChatColorToken } from "./chat-theme.js";
package/dist/vlist.d.ts CHANGED
@@ -57,6 +57,12 @@ export declare class VirtualList {
57
57
  /** Removes a row (its element is dropped from the DOM if shown). */
58
58
  remove(row: VRow): void;
59
59
  clear(): void;
60
+ /**
61
+ * Puts row `i` at the top of the view and stops following the bottom. The
62
+ * rows above it are measured as they come into the window; the row stays
63
+ * where it is while they are (the layout anchors on the row at the top).
64
+ */
65
+ scrollToIndex(i: number): void;
60
66
  /** Jumps to the end and follows new output. */
61
67
  scrollToBottom(): void;
62
68
  /**
package/dist/vlist.js CHANGED
@@ -121,6 +121,22 @@ export class VirtualList {
121
121
  this.win.replaceChildren();
122
122
  this.top.style.height = this.bottom.style.height = "0px";
123
123
  }
124
+ /**
125
+ * Puts row `i` at the top of the view and stops following the bottom. The
126
+ * rows above it are measured as they come into the window; the row stays
127
+ * where it is while they are (the layout anchors on the row at the top).
128
+ */
129
+ scrollToIndex(i) {
130
+ if (this.disposed || i < 0 || i >= this.rows.length)
131
+ return;
132
+ this.pinned = null;
133
+ this.follow = false;
134
+ const total = this.computeOffsets();
135
+ // Room to scroll that far before the window is rebuilt there: the spacers are what gives the list its height.
136
+ this.bottom.style.height = `${total}px`;
137
+ this.setTop(this.offsets[i]);
138
+ this.layout();
139
+ }
124
140
  /** Jumps to the end and follows new output. */
125
141
  scrollToBottom() {
126
142
  this.pinned = null;
package/docs/chat-ui.md CHANGED
@@ -115,6 +115,12 @@ Typing `/` lists the built-in commands, then the directory's prompt templates an
115
115
  | `permissionsSetting` | on | *Always allow (this app)* on permission questions and the *Tool permissions* choice in the settings; `false` for an app that decides when to ask itself. Not shown when `permissions` is a function or `agent` is given. |
116
116
  | `rewindState` | | `{ label, take(), restore(value) }`: your app's own state (an editor's text, a form) snapshotted as each message is sent; rewinding offers `label` as a checkbox and calls `restore` with that snapshot. Needs a workspace. |
117
117
  | `onSession(agent)` | | Called with each conversation's agent as it opens. |
118
+ | `headerStart` | | Elements of your own before the header's title (a button that opens your list of conversations). |
119
+ | `queue` | on | Steering and queueing while a run is going. `false`: the composer offers only *Stop* then, Enter sends nothing and what is typed stays in the box — for an agent that takes one message at a time. |
120
+ | `replyActions` | all on | `{ rewind, retry, delete }`: the actions under a message, each off when `false` — *Rewind* on a user message, *Answer again* and *Delete* under a reply. |
121
+ | `clearButton` | on | The header's *Clear* button of a one-conversation chat; `false` when your app clears or deletes conversations itself. |
122
+ | `commands` | all that apply | The built-in slash commands to keep, by name: `["help", "compact", "model", "context", "export"]`. |
123
+ | `uploadImage(file)` | | Uploads an attached picture and returns its address; the message then carries the address instead of the picture as a data URL. A site-relative address (`/uploads/a.png`) is shown in the conversation like any other. |
118
124
 
119
125
  ## The empty conversation: a greeting and starter prompts
120
126
 
@@ -168,6 +174,7 @@ await chat.deleteSession(id);
168
174
  await chat.clear(); // start the open conversation over (the Clear button)
169
175
  await chat.refresh(); // re-read skills and templates for the / menu
170
176
  chat.setDebug(true);
177
+ chat.setTitle("Daily report"); // the header's title
171
178
  chat.setAppearance({ theme: "dark", palette: "slate" });
172
179
  chat.ui; // the inline dialogs — your own tools can use them
173
180
  chat.unmount(); // remove it; agents the chat made are stopped
@@ -296,6 +303,48 @@ renderChat(el, { agent });
296
303
 
297
304
  The chat shows that agent; it does not make new ones (no conversation list or *New chat*; *Clear* starts it over).
298
305
 
306
+ ### An agent that is not an `Agent`
307
+
308
+ `agent` only has to be a `ChatAgent`: the members of `Agent` the chat uses. So the conversation can live somewhere
309
+ else — a loop that runs on your server, with the browser sending messages and receiving a stream:
310
+
311
+ ```ts
312
+ import type { ChatAgent } from "@runappsai/agent";
313
+
314
+ class RemoteAgent implements ChatAgent {
315
+ // state the chat reads
316
+ id; provider; workspace = null; tools; messages; usage; lastEnd; busy; model; settings; title;
317
+ // what it calls
318
+ on(name, handler) {…} // run_start, text_delta, reasoning_delta, tool_start, tool_end, message_end, run_end, …
319
+ ready() {…} // resolves once `messages` holds the conversation
320
+ prompt(content) {…} // send to the server; emit the events as its stream arrives; resolve at the end
321
+ abort() {…} rewind(index) {…} continue() {…} compact() {…}
322
+ context() {…} limits() {…} modelInfo() {…} accepts(kind) {…} compactionFor(window) {…} configure(patch) {…}
323
+ }
324
+ renderChat(el, { agent: new RemoteAgent(…), queue: false, replyActions: { delete: false }, clearButton: false });
325
+ ```
326
+
327
+ What the chat relies on:
328
+
329
+ - **Messages keep their identity.** The message a `run_start` event carried is the very object later found in `messages`
330
+ (rewinding looks it up there).
331
+ - **`busy`** is true from `run_start` until after `run_end`.
332
+ - **`tools`** is only read for each tool's `display` (label, icon, `tone`, `hidden`); nothing is executed.
333
+ - **Features it has no members for are switched off**: `queue: false` without `steer` / `followUp` / `dequeue`,
334
+ `replyActions.delete: false` without `remove`, `clearButton: false` (and no `/new` in `commands`) without `clear`.
335
+ - **Dialogs**: the host's agent asks through its own `ui`; pass it `chat.ui` to ask in the cards above the composer.
336
+ Besides `confirm`, `select` (now with `min` / `max` for several choices) and `input`, the built-in UIs have
337
+ `form(title, fields)` for several fields at once.
338
+
339
+ Two things exist for an agent whose messages change outside its own runs:
340
+
341
+ - `hasOlder` / `loadOlder()`: when `hasOlder` is true the conversation starts with a *Load earlier messages* row;
342
+ `loadOlder()` puts older messages in front and emits `history`.
343
+ - the `history` event, `{ reason: "older" | "newer" | "replace" }`: the transcript is drawn again from `messages` —
344
+ staying on what it showed (`older`), following the end if it was there (`newer`), or from its end (`replace`).
345
+
346
+ A `compaction` event may carry `summaryText` when the summary is not the first message (the older messages are kept).
347
+
299
348
  ## Theming
300
349
 
301
350
  Every colour and font is a CSS custom property on the chat's root: `--ra-bg`, `--ra-panel`, `--ra-subtle`, `--ra-muted`, `--ra-fg`, `--ra-fg-muted`, `--ra-border`, `--ra-accent`, `--ra-accent-fg`, `--ra-accent-subtle`, `--ra-accent-muted`, `--ra-user-bg`, `--ra-link`, `--ra-ok`, `--ra-red`, `--ra-red-subtle`, `--ra-warn-fg`, `--ra-warn-bg`, `--ra-warn-border`, `--ra-shadow`, `--ra-shadow-md`, `--ra-font`, `--ra-mono`.
package/docs/tools.md CHANGED
@@ -144,6 +144,7 @@ defineTool({
144
144
  icon: "<svg …>", // the card's icon
145
145
  render: ({ args, status, result, details }) => chipsFor(args, result), // your element under the title, visible while folded
146
146
  outcome: ({ result }) => summaryOf(result), // beside the status mark ("Added", "$0.12")
147
+ tone: "danger", // marks the icon: "warning" (it spends or acts), "danger" (it deletes or publishes)
147
148
  file: ({ path }) => path, // the workspace file it is about: the card offers to open it
148
149
  },
149
150
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runappsai/agent",
3
- "version": "0.1.15",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Agent harness: the model ↔ tool loop with a workspace, skills, sessions, compaction, a sandbox and a chat UI. Bring any OpenAI-compatible model provider (RunApps included); no runtime dependencies.",
6
6
  "license": "MIT",