paseo-plugin-genui 0.2.1 → 0.2.2

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/OVERVIEW.md CHANGED
@@ -13,6 +13,7 @@ When automatic instructions are enabled, new agents receive the Generative UI co
13
13
  - **86 components in 10 groups**: Layout, Content, Data, Media, Inputs, Widgets, Project, Dev, Manage, and Evidence.
14
14
  - **Confined file reading**: `Load(path)`, `Snippet(path, from, to)`, and `Image(path)` read JSON, CSV, TSV, logs, test reports (Vitest, Jest, JUnit), coverage (`lcov`, Istanbul, `coverage.py`, Go), lint and typecheck findings (ESLint, SARIF, `tsc`, Ruff), HAR traces, and benchmarks. Reads are strictly confined to the agent's workspace directory, its per-agent thread storage directory (`/tmp/opencode/genui-storage/<agentId>`), `/tmp`, and any extra folders added in settings.
15
15
  - **Live workspace and git state**: `Changes()`, `Commits()`, `PullRequest()`, `Threads()`, and `Environments()` read the workspace's git diff, commits, pull request status, subagents, and worktrees on the daemon host.
16
+ - **Repair of broken blocks**: When an agent's turn ends, the daemon checks each `ui` block in its reply. If a block fails to compile, load a file, or render, the plugin sends the agent one follow-up message that starts with `[genui]` and lists the errors, and the agent replies with corrected blocks. It sends at most one such message per user message and skips subagents. The follow-up shows in the chat as a user message. Turning off automatic agent instructions in settings also turns this off.
16
17
  - **Sandboxed mini-apps**: `app` blocks run self-contained HTML and JavaScript inside a sandboxed iframe (`sandbox="allow-scripts"`) with a network-blocking Content Security Policy on desktop and web clients.
17
18
  - **Settings and web lookups**: Under **Settings -> Plugins -> Generative UI**, you can toggle automatic agent instructions for new sessions and toggle server-side web lookups, and add extra folders (for example `~/dev/scratch`) that file reads may use. When web lookups are on, the daemon fetches photo searches from Wikimedia Commons (`commons.wikimedia.org` / `upload.wikimedia.org`), geocoding from Photon (`photon.komoot.io`), map tiles from OpenStreetMap (`tile.openstreetmap.org`), and HTTPS images through an address-checked proxy that rejects loopback, private, and link-local IP addresses. No cookies, credentials, or conversation text beyond the specific search query or place name are sent. Turning web lookups off disables all external network requests.
18
19
 
package/index.server.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { mkdir } from "node:fs/promises";
2
2
  import type { PluginServerContext } from "@getpaseo/plugin/server";
3
- import { checkSpec, renderReplyMarkdown } from "./shared/fallback";
3
+ import { checkSpec, renderReplyMarkdown, repairRequest, REPAIR_MARKER } from "./shared/fallback";
4
4
  import { buildFullInstructions, GENUI_MARKER } from "./shared/instructions";
5
5
  import {
6
6
  appendDemoRpc,
@@ -109,6 +109,26 @@ export default function contribute(server: PluginServerContext) {
109
109
  };
110
110
  });
111
111
 
112
+ // A ```ui block that fails shows the user an error box. Send the errors back so the
113
+ // agent rewrites the block; one attempt per user message, so a failed fix cannot loop.
114
+ server.on("agent.turn_ended", async (event, { paseo }) => {
115
+ if (event.outcome.kind !== "completed" || event.agent.parentAgentId) return;
116
+ const current = await settings.read();
117
+ if (current.status === "ready" && !current.values.autoInstructions) return;
118
+ const agent = paseo.agents.ref(event.agent.id);
119
+ const page = await agent.timeline.refetch({ direction: "tail", limit: 40 });
120
+ if (page.error) return;
121
+ const items = page.entries.map((entry) => entry.item);
122
+ const lastUser = items.findLastIndex((item) => item.type === "user_message");
123
+ if (lastUser >= 0 && items[lastUser].type === "user_message" && items[lastUser].text.startsWith(REPAIR_MARKER)) return;
124
+ const reply = items
125
+ .slice(lastUser + 1)
126
+ .flatMap((item) => (item.type === "assistant_message" ? [item.text] : []))
127
+ .join("\n\n");
128
+ const request = await repairRequest(reply, (req) => loadAgentFile(paseo, event.agent.id, req.path, req));
129
+ if (request !== null) await agent.send(request);
130
+ });
131
+
112
132
  server.before("agent.session_open", async ({ request }) => {
113
133
  const storageDir = agentStorageDir(request.agentId);
114
134
  await mkdir(storageDir, { recursive: true }).catch(() => undefined);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-plugin-genui",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Paseo plugin: agents answer with charts, diagrams, maps, plans and forms rendered inline in the chat.",
5
5
  "keywords": [
6
6
  "paseo",
@@ -10,6 +10,7 @@ import {
10
10
  DESCRIPTIONS,
11
11
  EXPECTED,
12
12
  functionArg,
13
+ isUnknownComponentName,
13
14
  LAMBDA_METHODS,
14
15
  stateMismatch,
15
16
  type Kind,
@@ -305,6 +306,12 @@ const Interpreter = defineClass(
305
306
  if (action !== undefined) return this.action(expr, action, scope);
306
307
  const own = this.program.named.get(expr.name)?.value;
307
308
  if (own?.type === "arrow") return this.callOwn(expr, own, scope);
309
+ if (own === undefined && isUnknownComponentName(expr.name)) {
310
+ const key = `${expr.pos.line}:${expr.pos.column}${this.suffix}`;
311
+ const message = `\`${expr.name}\` is not a component`;
312
+ this.diagnostics.report(expr.pos, message);
313
+ return this.node("Error", key, { message }, expr.pos);
314
+ }
308
315
  return this.callFunction(expr, scope);
309
316
  }
310
317
  case "method":
@@ -66,6 +66,11 @@ const FUNCTION_ARITY: ReadonlyMap<string, Arity> = new Map(
66
66
  } satisfies Record<FunctionName, Arity>),
67
67
  );
68
68
 
69
+ /** A capitalized call the catalog lacks, as in `Link(url)`: it renders as an Error node instead of failing the block. */
70
+ export function isUnknownComponentName(name: string): boolean {
71
+ return /^[A-Z][A-Za-z0-9]*$/.test(name) && !COMPONENT_SPECS.has(name) && !ACTION_SPECS.has(name) && !FUNCTION_ARITY.has(name);
72
+ }
73
+
69
74
  const ACTION_LIST = [...ACTION_SPECS].map(([name, spec]) => signature(name, spec)).join(", ");
70
75
  const ARROW_ONLY =
71
76
  "arrow functions can only be declared as a named function (`share = p => ...`) or passed to a list method such as map, filter, reduce or sort";
@@ -581,7 +586,9 @@ const Validator = defineClass(
581
586
  } else {
582
587
  const arity = FUNCTION_ARITY.get(expr.name);
583
588
  if (arity === undefined) {
584
- this.diagnostics.report(expr.pos, this.unknownCallee(expr.name, params));
589
+ // An unknown component renders as an inline Error node, so the rest of the block still shows.
590
+ const component = this.unknownComponent(expr.name, params);
591
+ this.diagnostics.report(expr.pos, this.unknownCallee(expr.name, params), component ? "warning" : "error");
585
592
  } else {
586
593
  if (expr.named.length > 0) {
587
594
  this.diagnostics.report(expr.named[0].pos, `\`${expr.name}\` takes positional arguments only`);
@@ -597,6 +604,10 @@ const Validator = defineClass(
597
604
  for (const arg of expr.named) this.check(arg.value, params, refs);
598
605
  },
599
606
 
607
+ unknownComponent(name: string, params: readonly string[]): boolean {
608
+ return isUnknownComponentName(name) && !this.named.has(name) && !params.includes(name) && !this.states.has(name);
609
+ },
610
+
600
611
  unknownCallee(name: string, params: readonly string[]): string {
601
612
  if (this.named.has(name) || params.includes(name) || this.states.has(name)) {
602
613
  return `\`${name}\` is a value and cannot be called; only components, actions and functions can`;
@@ -95,15 +95,11 @@ export async function renderReplyMarkdown(text: string, load: Loader, find?: Ima
95
95
  return output.join("\n");
96
96
  }
97
97
 
98
- export async function checkSpec(
99
- spec: string,
100
- load: Loader,
101
- find?: ImageFinder,
102
- project?: ProjectReader,
103
- ): Promise<{ readonly ok: boolean; readonly report: string }> {
98
+ /** What is wrong with a spec: compile errors, files that failed to load, and evaluation errors. Empty when it renders cleanly. */
99
+ async function specProblems(spec: string, load: Loader): Promise<{ problems: string[]; roots: UiNode[] | null }> {
104
100
  const compiled = compile(spec);
105
101
  if (compiled.program === null) {
106
- return { ok: false, report: `The block does not compile:\n${formatDiagnostics(compiled.diagnostics)}` };
102
+ return { problems: [`The block does not compile:\n${formatDiagnostics(compiled.diagnostics)}`], roots: null };
107
103
  }
108
104
  const requests = collectLoads(compiled.program);
109
105
  const loaded = await Promise.all(requests.map(async (request) => [request, await load(request)] as const));
@@ -113,8 +109,37 @@ export async function checkSpec(
113
109
  ...loaded.flatMap(([request, result]) => (result.ok ? [] : [`${request.path}: ${result.error}`])),
114
110
  ...(diagnostics.length > 0 ? [formatDiagnostics(diagnostics)] : []),
115
111
  ];
112
+ return { problems, roots };
113
+ }
114
+
115
+ export async function checkSpec(
116
+ spec: string,
117
+ load: Loader,
118
+ find?: ImageFinder,
119
+ project?: ProjectReader,
120
+ ): Promise<{ readonly ok: boolean; readonly report: string }> {
121
+ const { problems, roots } = await specProblems(spec, load);
122
+ if (roots === null) return { ok: false, report: problems[0] };
116
123
  const preview = `Text version of what the user will see:\n\n${await rootsMarkdown(roots, find, project)}`;
117
124
  return problems.length === 0
118
125
  ? { ok: true, report: `No errors. ${preview}` }
119
126
  : { ok: false, report: `Fix before replying:\n${problems.join("\n")}\n\n${preview}` };
120
127
  }
128
+
129
+ export const REPAIR_MARKER = "[genui]";
130
+
131
+ /** The follow-up that asks the agent to rewrite the ```ui blocks of `reply` that fail, or null when they all render. */
132
+ export async function repairRequest(reply: string, load: Loader): Promise<string | null> {
133
+ const fences = findFences(reply.split("\n")).filter((fence) => fence.language === "ui" && fence.closed);
134
+ const failures: string[] = [];
135
+ for (const [index, fence] of fences.entries()) {
136
+ const { problems } = await specProblems(fence.body, load);
137
+ if (problems.length > 0) failures.push(`Block ${index + 1}:\n${problems.join("\n")}`);
138
+ }
139
+ if (failures.length === 0) return null;
140
+ return [
141
+ `${REPAIR_MARKER} Your last reply has \`\`\`ui blocks the user sees as errors:`,
142
+ ...failures,
143
+ "Send the corrected blocks only, using components from the Inline UI reference. Do not explain the fix.",
144
+ ].join("\n\n");
145
+ }
@@ -33,7 +33,7 @@ Games, simulations, custom visuals: write \`\`\`app, a self-contained HTML page
33
33
 
34
34
  export const UI_REFERENCE_MORE = `# Inline UI reference, continued
35
35
  ${componentLines(REFERENCE_MORE_GROUPS)}
36
- Icon names: Check X Plus Minus Edit Copy Trash2 Download ExternalLink Play Pause RotateCcw Search Settings GitBranch GitMerge GitPullRequest Bug Code Terminal FileText Folder Clock Calendar Mail Sent Lock Star Pin Link Eye AlertTriangle Info Globe Smartphone Laptop Cloud Layers Puzzle.`;
36
+ Icon names (strings, as in icon: "git-branch"): check x plus minus edit copy trash-2 download external-link play pause rotate-ccw search settings git-branch git-merge git-pull-request bug code terminal file-text folder clock calendar mail sent lock star pin link eye alert-triangle info globe smartphone laptop cloud layers puzzle.`;
37
37
 
38
38
  const MAP_EXAMPLE = `\`\`\`ui
39
39
  Card("Day 1", [Map([{name: "Belém Tower, Lisbon", note: "Opens 9:30"}, {name: "Pena Palace, Sintra"}], route: true)])
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { compile, evaluate, initialState } from "./core";
3
+ import { repairRequest } from "./fallback";
4
+
5
+ const noFiles = async () => ({ ok: false as const, error: "no files in this test" });
6
+
7
+ const LINK_SPEC = `Card("Mergeable PRs", [
8
+ Text("Four can merge"),
9
+ Link("https://github.com/acme/api/pull/1", "PR 1")
10
+ ])`;
11
+
12
+ describe("unknown components", () => {
13
+ it("render as an Error node and keep the rest of the block", () => {
14
+ const { program, diagnostics } = compile(LINK_SPEC);
15
+ expect(program).not.toBeNull();
16
+ expect(diagnostics.map((d) => d.severity)).toEqual(["warning"]);
17
+ const { roots, diagnostics: runtime } = evaluate(program!, initialState(program!));
18
+ const card = roots[0];
19
+ expect(card.type).toBe("Card");
20
+ const children = (card.props.children as { type: string }[]).map((child) => child.type);
21
+ expect(children).toEqual(["Text", "Error"]);
22
+ expect(runtime[0].message).toContain("`Link` is not a component");
23
+ });
24
+
25
+ it("stay errors when the name is a function call that needs a value", () => {
26
+ expect(compile(`x = 1\nCard("a", [Text(x())])`).program).toBeNull();
27
+ });
28
+ });
29
+
30
+ describe("repairRequest", () => {
31
+ it("lists each failing ```ui block for the agent", async () => {
32
+ const reply = `Answer.\n\n\`\`\`ui\nCard("ok", [Text("fine")])\n\`\`\`\n\n\`\`\`ui\n${LINK_SPEC}\n\`\`\``;
33
+ const request = await repairRequest(reply, noFiles);
34
+ expect(request).toMatch(/^\[genui\]/);
35
+ expect(request).toContain("Block 2:");
36
+ expect(request).not.toContain("Block 1:");
37
+ expect(request).toContain("`Link` is not a component");
38
+ });
39
+
40
+ it("is null when every block renders", async () => {
41
+ expect(await repairRequest('```ui\nCard("ok", [Text("fine")])\n```', noFiles)).toBeNull();
42
+ expect(await repairRequest("No UI here.", noFiles)).toBeNull();
43
+ });
44
+ });