@runappsai/agent 0.3.2 → 0.3.4

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.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // height composer that never resizes while typing, and a virtual
12
12
  // transcript (`VirtualList`) that keeps only the rows near the viewport
13
13
  // in the DOM, so a long history costs nothing to open.
14
+ import { STATE_MARK } from "./context.js";
14
15
  import { escapeHTML } from "./markdown.js";
15
16
  import { VirtualList } from "./vlist.js";
16
17
  import { chooseFiles, downloadBlob, h, I, modal, modalConfirm, renderMD, setFileDialog } from "./dom.js";
@@ -2023,7 +2024,7 @@ export function renderChat(target, opts) {
2023
2024
  const userRow = (content, msg) => {
2024
2025
  const parts = textPartsOf(content);
2025
2026
  // Expanded slash commands show what was typed; the expansion is for the model.
2026
- const own = parts.filter((p) => !p.startsWith(ATTACH_MARK) && !p.startsWith(CONTEXT_MARK) && !p.startsWith("<file name="));
2027
+ const own = parts.filter((p) => !p.startsWith(ATTACH_MARK) && !p.startsWith(CONTEXT_MARK) && !p.startsWith(STATE_MARK) && !p.startsWith("<file name="));
2027
2028
  const typed = typedOf(msg);
2028
2029
  const row = { msg, text: typed ?? own.join("\n"), update: () => undefined, render: () => userEl(content, row) };
2029
2030
  return row;
@@ -2272,13 +2273,18 @@ export function renderChat(target, opts) {
2272
2273
  * A finished reply: everything before its answer (thinking, tool calls, text written along the way)
2273
2274
  * folds into one "Worked for 6m 38s" line, the answer stays below it. A reply that is only an answer
2274
2275
  * has nothing to fold; one that ended without an answer (stopped, turn limit) folds whole.
2276
+ * A reply that stopped to ask the user something (an agent whose run ends on a question and goes on
2277
+ * with the answer) ends on that question's call, still waiting: it stays out with the text before it,
2278
+ * which is what the user is being asked about.
2275
2279
  */
2276
2280
  const foldReply = (body, ms) => {
2277
2281
  if (body.querySelector(":scope>.ra-work"))
2278
2282
  return;
2279
2283
  const kids = Array.from(body.children);
2280
- const last = kids.at(-1);
2281
- const process = last?.classList.contains("ra-md") ? kids.slice(0, -1) : kids;
2284
+ let end = kids.length;
2285
+ while (end > 0 && kids[end - 1].classList.contains("ra-tg") && kids[end - 1].querySelector(".ra-tgb>.ra-tool>summary .ra-tend .ra-spin"))
2286
+ end--;
2287
+ const process = end > 0 && kids[end - 1].classList.contains("ra-md") ? kids.slice(0, end - 1) : kids.slice(0, end);
2282
2288
  if (!process.length)
2283
2289
  return;
2284
2290
  const d = h("details", "ra-work");
package/dist/context.d.ts CHANGED
@@ -21,6 +21,11 @@ export interface SystemPromptInput {
21
21
  now?: Date;
22
22
  }
23
23
  export declare function buildSystemPrompt(input: SystemPromptInput): string;
24
+ /**
25
+ * Starts the part `messageContext` adds to a user message (the host's state when it was sent).
26
+ * The model reads it; the chat does not show it, and it is never a session title.
27
+ */
28
+ export declare const STATE_MARK = "[state] ";
24
29
  /** The gateway's own estimate: a token per 3 bytes, 1600 per image. */
25
30
  export declare function estimateTokens(messages: ChatMessage[], system?: string): number;
26
31
  export interface FitResult {
package/dist/context.js CHANGED
@@ -75,6 +75,11 @@ export function buildSystemPrompt(input) {
75
75
  /* Budget */
76
76
  /* ------------------------------------------------------------------ */
77
77
  const IMAGE_TOKENS = 1600;
78
+ /**
79
+ * Starts the part `messageContext` adds to a user message (the host's state when it was sent).
80
+ * The model reads it; the chat does not show it, and it is never a session title.
81
+ */
82
+ export const STATE_MARK = "[state] ";
78
83
  /** The gateway's own estimate: a token per 3 bytes, 1600 per image. */
79
84
  export function estimateTokens(messages, system) {
80
85
  let bytes = system ? utf8Length(system) : 0;
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ __export(src_exports, {
30
30
  MCPError: () => MCPError,
31
31
  PartialReadError: () => PartialReadError,
32
32
  ProviderError: () => ProviderError,
33
+ STATE_MARK: () => STATE_MARK,
33
34
  Scheduler: () => Scheduler,
34
35
  UNTITLED: () => UNTITLED,
35
36
  WEB_TOOL_NAMES: () => WEB_TOOL_NAMES,
@@ -353,6 +354,7 @@ Your notes from earlier conversations (${input.memoryPath ?? "/memory/notes.md"}
353
354
  return out.join("\n\n");
354
355
  }
355
356
  var IMAGE_TOKENS = 1600;
357
+ var STATE_MARK = "[state] ";
356
358
  function estimateTokens(messages, system) {
357
359
  let bytes = system ? utf8Length(system) : 0;
358
360
  let images = 0;
@@ -2475,7 +2477,7 @@ function titleOf(d) {
2475
2477
  return UNTITLED;
2476
2478
  }
2477
2479
  function isMachineTitle(title) {
2478
- return /^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(title);
2480
+ return /^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] |\[state\] )|\[attachments\]/.test(title);
2479
2481
  }
2480
2482
  function withLock(name, fn) {
2481
2483
  const locks2 = typeof navigator !== "undefined" ? navigator.locks : void 0;
@@ -4198,6 +4200,38 @@ var Agent = class {
4198
4200
  this.emit("queued", { kind, message });
4199
4201
  });
4200
4202
  }
4203
+ /**
4204
+ * A user message joining the conversation, with the host's state (`messageContext`) as it is now
4205
+ * as its last part. Done when it joins, not when it is typed: a queued message carries the state
4206
+ * it is answered in. State the conversation already ends on is not said again.
4207
+ */
4208
+ withState(m, last = this.lastState()) {
4209
+ let state;
4210
+ try {
4211
+ state = this.opts.messageContext?.();
4212
+ } catch {
4213
+ state = void 0;
4214
+ }
4215
+ if (!state || state === last) return m;
4216
+ const parts = typeof m.content === "string" ? [{ type: "text", text: m.content }] : [...m.content ?? []];
4217
+ parts.push({ type: "text", text: STATE_MARK + state });
4218
+ return { ...m, content: parts };
4219
+ }
4220
+ /**
4221
+ * The newest state still in the conversation. Read from the history itself, not remembered:
4222
+ * compaction, a rewind or a reload can take the message that carried it away.
4223
+ */
4224
+ lastState(messages = this.history) {
4225
+ for (let i = messages.length - 1; i >= 0; i--) {
4226
+ const m = messages[i];
4227
+ if (m.role !== "user" || !Array.isArray(m.content)) continue;
4228
+ for (let j = m.content.length - 1; j >= 0; j--) {
4229
+ const part = m.content[j];
4230
+ if (part.type === "text" && part.text.startsWith(STATE_MARK)) return part.text.slice(STATE_MARK.length);
4231
+ }
4232
+ }
4233
+ return void 0;
4234
+ }
4201
4235
  userMessage(content) {
4202
4236
  const parts = typeof content === "string" ? [{ type: "text", text: content }] : content.slice();
4203
4237
  return { role: "user", content: parts.length === 1 && parts[0].type === "text" ? parts[0].text : parts, ts: Date.now() };
@@ -4304,6 +4338,7 @@ var Agent = class {
4304
4338
  prefaced = message;
4305
4339
  prefaceError = err instanceof Error ? err : new Error(String(err));
4306
4340
  }
4341
+ prefaced = this.withState(prefaced);
4307
4342
  this.history.push(prefaced);
4308
4343
  }
4309
4344
  this._ended = null;
@@ -4467,7 +4502,8 @@ var Agent = class {
4467
4502
  }
4468
4503
  /** Moves queued steering into the history and says so (`steered`), so a UI draws each message once, when it lands. */
4469
4504
  applySteering(runId) {
4470
- const steer = this.queue.filter((q) => q.kind === "steer").map((q) => q.message);
4505
+ const steer = [];
4506
+ for (const q of this.queue) if (q.kind === "steer") steer.push(this.withState(q.message, this.lastState(steer) ?? this.lastState()));
4471
4507
  if (!steer.length) return;
4472
4508
  this.queue = this.queue.filter((q) => q.kind !== "steer");
4473
4509
  this.history.push(...steer);
package/dist/index.d.ts CHANGED
@@ -32,7 +32,7 @@ export { connectMCP, MCPError, type MCPConnection, type MCPOptions, type MCPTool
32
32
  export { sandboxTool, runInSandbox, type SandboxOptions, type SandboxResult, type SandboxToolBridge } from "./sandbox.js";
33
33
  export { parseSkill, parseFrontmatter } from "./skills.js";
34
34
  export { collectCompletion, type CollectedCompletion } from "./completion.js";
35
- export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns } from "./context.js";
35
+ export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns, STATE_MARK } from "./context.js";
36
36
  export { validateSchema } from "./json-schema.js";
37
37
  export { listZip, readZipEntry, buildZip, type ZipEntry, type Inflate } from "./zip.js";
38
38
  export { skillZipFS, skillFoldersOf, subFS } from "./skill-zips.js";
package/dist/index.js CHANGED
@@ -40,7 +40,7 @@ export { connectMCP, MCPError } from "./mcp.js";
40
40
  export { sandboxTool, runInSandbox } from "./sandbox.js";
41
41
  export { parseSkill, parseFrontmatter } from "./skills.js";
42
42
  export { collectCompletion } from "./completion.js";
43
- export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns } from "./context.js";
43
+ export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns, STATE_MARK } from "./context.js";
44
44
  export { validateSchema } from "./json-schema.js";
45
45
  export { listZip, readZipEntry, buildZip } from "./zip.js";
46
46
  export { skillZipFS, skillFoldersOf, subFS } from "./skill-zips.js";
package/dist/types.d.ts CHANGED
@@ -550,6 +550,14 @@ export interface AgentOptions {
550
550
  model?: string;
551
551
  /** The app's own system instructions (a function is re-read every turn). */
552
552
  instructions?: string | (() => string);
553
+ /**
554
+ * The app's state as it is now (what an editor holds, what is selected, ...), added to each user
555
+ * message when it joins the conversation and kept with it. Put what changes here rather than in
556
+ * `instructions`: a system prompt that changes from one request to the next keeps the provider's
557
+ * prompt cache from ever hitting, while this text, once sent, stays the same in every later request.
558
+ * State the conversation already ends on is not added again. Empty or a throw: nothing is added.
559
+ */
560
+ messageContext?: () => string | undefined;
553
561
  /** A short name for the app, used in the system prompt. */
554
562
  appName?: string;
555
563
  /** Private prompt reference(s) (RunApps: `{id, vars}`), forwarded on every request. */
package/dist/ui.cjs CHANGED
@@ -36,6 +36,9 @@ __export(ui_exports, {
36
36
  });
37
37
  module.exports = __toCommonJS(ui_exports);
38
38
 
39
+ // src/context.ts
40
+ var STATE_MARK = "[state] ";
41
+
39
42
  // src/markdown.ts
40
43
  var ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
41
44
  function escapeHTML(s) {
@@ -4944,7 +4947,7 @@ ${t.webHint}`;
4944
4947
  };
4945
4948
  const userRow = (content, msg) => {
4946
4949
  const parts = textPartsOf(content);
4947
- const own = parts.filter((p) => !p.startsWith(ATTACH_MARK) && !p.startsWith(CONTEXT_MARK) && !p.startsWith("<file name="));
4950
+ const own = parts.filter((p) => !p.startsWith(ATTACH_MARK) && !p.startsWith(CONTEXT_MARK) && !p.startsWith(STATE_MARK) && !p.startsWith("<file name="));
4948
4951
  const typed = typedOf(msg);
4949
4952
  const row = { msg, text: typed ?? own.join("\n"), update: () => void 0, render: () => userEl(content, row) };
4950
4953
  return row;
@@ -5165,8 +5168,9 @@ ${t.webHint}`;
5165
5168
  const foldReply = (body, ms) => {
5166
5169
  if (body.querySelector(":scope>.ra-work")) return;
5167
5170
  const kids = Array.from(body.children);
5168
- const last = kids.at(-1);
5169
- const process = last?.classList.contains("ra-md") ? kids.slice(0, -1) : kids;
5171
+ let end = kids.length;
5172
+ while (end > 0 && kids[end - 1].classList.contains("ra-tg") && kids[end - 1].querySelector(".ra-tgb>.ra-tool>summary .ra-tend .ra-spin")) end--;
5173
+ const process = end > 0 && kids[end - 1].classList.contains("ra-md") ? kids.slice(0, end - 1) : kids.slice(0, end);
5170
5174
  if (!process.length) return;
5171
5175
  const d = h("details", "ra-work");
5172
5176
  const sum = h("summary");
package/dist/workspace.js CHANGED
@@ -1162,7 +1162,7 @@ export function titleOf(d) {
1162
1162
  }
1163
1163
  /** A title that is not the user's words: a compaction summary, an expanded skill, an agent note, an attachment list, the host's context. */
1164
1164
  export function isMachineTitle(title) {
1165
- return /^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(title);
1165
+ return /^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] |\[state\] )|\[attachments\]/.test(title);
1166
1166
  }
1167
1167
  /** Runs fn holding the origin-wide Web Lock `name`; without Web Locks it just runs fn. */
1168
1168
  export function withLock(name, fn) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runappsai/agent",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
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",