@agent-native/core 0.101.11 → 0.101.12

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.
@@ -1,5 +1,11 @@
1
1
  # @agent-native/core
2
2
 
3
+ ## 0.101.12
4
+
5
+ ### Patch Changes
6
+
7
+ - 2ff004e: Fix workspace-file resolution and run-code paging/routing edge cases. `contentFromWorkspaceFile` now resolves the same file the run-code `workspaceRead`/`workspaceWrite` bridge sees (bridge scope first, then Resources), and fails closed on a bridge read error instead of silently falling back to a possibly-different same-path Resources body. `workspaceRead` returns null instead of a silently truncated prefix when a later page fails, and the run-code bridge now returns a distinct "not registered" (404) error for unknown tools instead of a misleading read-only access error.
8
+
3
9
  ## 0.101.11
4
10
 
5
11
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.101.11",
3
+ "version": "0.101.12",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/BuilderIO/agent-native#readme",
6
6
  "bugs": {
@@ -740,8 +740,18 @@ function handleBridgeRequest(
740
740
 
741
741
  // Enforce allowlist.
742
742
  const entry = actions[toolName];
743
+ // Unknown/mistyped tool: report "not registered" (404) before the
744
+ // access-control branch below. Otherwise an undefined `entry` falls into the
745
+ // allowlist 403 and returns a misleading access error for a tool that simply
746
+ // does not exist. (Bridge-allowlisted tools always have an entry, so this
747
+ // cannot mask a legitimate allowlisted call.)
748
+ if (!entry) {
749
+ res.writeHead(404, { "Content-Type": "application/json" });
750
+ res.end(JSON.stringify({ error: `Tool "${toolName}" is not registered.` }));
751
+ return;
752
+ }
743
753
  const isReadOnlyAction =
744
- entry?.readOnly === true &&
754
+ entry.readOnly === true &&
745
755
  entry.agentTool !== false &&
746
756
  entry.toolCallable !== false;
747
757
  if (
@@ -749,21 +759,24 @@ function handleBridgeRequest(
749
759
  !extraTools.has(toolName) &&
750
760
  !isReadOnlyAction
751
761
  ) {
762
+ // A registered, agent-exposed action that isn't read-only is a mutation.
763
+ // (Unknown tools already returned 404 above, so `entry` is defined here.)
764
+ // Point the caller at the native tool path instead of leaving them to guess
765
+ // (the common trap: retrying create-extension/update-extension through
766
+ // appAction, which cannot work).
767
+ const isMutatingAction =
768
+ entry.agentTool !== false && entry.readOnly !== true;
752
769
  res.writeHead(403, { "Content-Type": "application/json" });
753
770
  res.end(
754
771
  JSON.stringify({
755
- error: `Tool "${toolName}" is not an agent-exposed read-only action or sandbox bridge allowlisted tool.`,
772
+ error: isMutatingAction
773
+ ? `Tool "${toolName}" is a mutating action and cannot be called from run-code (appAction only exposes read-only actions). Call "${toolName}" directly as a native tool. For large content bodies, stage the content and pass "contentFromAttachment" instead of an inline string rather than routing it through run-code.`
774
+ : `Tool "${toolName}" is not an agent-exposed read-only action or sandbox bridge allowlisted tool.`,
756
775
  }),
757
776
  );
758
777
  return;
759
778
  }
760
779
 
761
- if (!entry) {
762
- res.writeHead(404, { "Content-Type": "application/json" });
763
- res.end(JSON.stringify({ error: `Tool "${toolName}" is not registered.` }));
764
- return;
765
- }
766
-
767
780
  const toolArgs = parsed.args ?? {};
768
781
  usedTools.add(toolName);
769
782
  // Run the tool with the parent request context so auth/org/owner resolution
@@ -1534,12 +1547,52 @@ async function webRead(url, init = {}) {
1534
1547
  /**
1535
1548
  * Read a Resources-backed workspace file by path. Returns the file content as
1536
1549
  * a string, or null if not found.
1537
- * Supports optional offset and maxChars for paging large files.
1550
+ *
1551
+ * By default this returns the WHOLE file: the underlying store caps a single
1552
+ * read at 100k chars, so this auto-pages across chunks and concatenates them,
1553
+ * so callers never get a silently truncated body. Pass an explicit \`offset\`
1554
+ * or \`maxChars\` to take manual control of a single page instead.
1538
1555
  */
1539
1556
  async function workspaceRead(path, opts = {}) {
1540
- const parsed = await workspaceReadMeta(path, opts);
1541
- if (parsed && parsed.ok === false) return null;
1542
- return parsed && typeof parsed.content === "string" ? parsed.content : null;
1557
+ // Explicit paging requested → single read, caller owns the window.
1558
+ if (opts.offset !== undefined || opts.maxChars !== undefined) {
1559
+ const parsed = await workspaceReadMeta(path, opts);
1560
+ if (parsed && parsed.ok === false) return null;
1561
+ return parsed && typeof parsed.content === "string" ? parsed.content : null;
1562
+ }
1563
+ // Default → assemble the full file by paging until the store reports no more.
1564
+ let offset = 0;
1565
+ let out = "";
1566
+ let found = false;
1567
+ let complete = false;
1568
+ // Bounded loop (files cap at 2 MB / 100k-char reads) so a misbehaving store
1569
+ // can never spin forever.
1570
+ for (let i = 0; i < 512; i++) {
1571
+ const parsed = await workspaceReadMeta(path, { offset, maxChars: 100000 });
1572
+ // A failed/missing page aborts. If it failed before the first page we never
1573
+ // found the file (return null below); if it failed part-way through a
1574
+ // truncated read, complete stays false and we return null rather than a
1575
+ // silently truncated body.
1576
+ if (!parsed || parsed.ok === false) break;
1577
+ found = true;
1578
+ const chunk = typeof parsed.content === "string" ? parsed.content : "";
1579
+ out += chunk;
1580
+ if (!parsed.truncated) {
1581
+ complete = true;
1582
+ break;
1583
+ }
1584
+ const next =
1585
+ typeof parsed.nextOffset === "number"
1586
+ ? parsed.nextOffset
1587
+ : offset + chunk.length;
1588
+ if (next <= offset) break; // no forward progress; stop rather than loop
1589
+ offset = next;
1590
+ }
1591
+ if (!found) return null;
1592
+ // Only hand back a body we know is whole. A truncated read followed by a
1593
+ // failed/stalled page would otherwise corrupt a large clone with a partial
1594
+ // prefix and no error signal.
1595
+ return complete ? out : null;
1543
1596
  }
1544
1597
 
1545
1598
  /**
@@ -3,8 +3,17 @@ import type { ActionRunContext } from "../action.js";
3
3
  import type { ActionEntry } from "../agent/production-agent.js";
4
4
  import type { AgentChatAttachment } from "../agent/types.js";
5
5
  import { writeAppState } from "../application-state/script-helpers.js";
6
- import { getRequestRunContext } from "../server/request-context.js";
6
+ import { readResource } from "../resources/script-helpers.js";
7
+ import {
8
+ getRequestOrgId,
9
+ getRequestRunContext,
10
+ getRequestUserEmail,
11
+ } from "../server/request-context.js";
7
12
  import { resolveAccess } from "../sharing/access.js";
13
+ import {
14
+ readWorkspaceFile,
15
+ type WorkspaceFilesScope,
16
+ } from "../workspace-files/store.js";
8
17
  import type {
9
18
  ExtensionContentEdit,
10
19
  ExtensionLegacyPatch,
@@ -483,7 +492,7 @@ export function createExtensionActionEntries(): Record<string, ActionEntry> {
483
492
  "create-extension": {
484
493
  tool: {
485
494
  description:
486
- 'Create a persisted sandboxed Alpine.js mini-app extension and render it inline in the chat. Use this when the user wants generated UI that should be saved, reusable, or visible in the Extensions view: extensions, widgets, dashboards, calculators, mini-apps, and reusable interactive utilities. For one-time chat-only UI, use render-inline-extension instead. The content must be a self-contained Alpine.js HTML body snippet that can use appAction(), appFetch(), dbQuery(), extensionFetch(), extensionData, agentNative.ui.output(value, opts?), and agentNative.chat.send()/sendToAgentChat(). Use appAction() for app data writes and extensionData for extension-owned persisted UI state; dbQuery() is for read-only inspection of known app SQL tables. Use agentNative.ui.output for passive current values from knobs, sliders, and selections; it writes application state at inline-ui:<extension id>:output, which the agent can read later with readAppState when the user says to use that value. Use agentNative.chat.send for visible submit/apply actions. Persist reusable user-edited state with extensionData: if the extension has checkboxes, todos, notes, filters, preferences, or any control whose value should survive reload/reopen, load that state on init and save changes with extensionData, usually at user scope, instead of keeping it only in Alpine state. IMPORTANT — hosting a pasted file: if the user pasted a large HTML/Alpine file (it appears in your context as an <attachment name="pasted-text-…"> block) and asked you to host it as-is, do NOT copy that file into `content`. Instead leave `content` empty and pass `contentFromAttachment` set to that attachment\'s name (or the literal "latest" for the most recent pasted block) — the server reads the file verbatim. Re-emitting a large pasted file as `content` regularly gets cut off mid-stream and stalls the turn. Prefer appAction(name, params) for app data and actions, including read actions mounted as GET; do not call template /api/* routes from appFetch because the extension bridge only allows framework /_agent-native/* paths. Parse JSON string action results before aggregating; use dbQuery() only for known existing SQL tables and never for writes. Keep the initial create-extension payload compact and working; for complex extensions, create a useful v1 first, then use focused update-extension edits for refinements rather than assembling one enormous initial tool input. For any non-trivial component (more than a couple of state fields, any methods, any string formatting, any branching) put the component in a <script> block via Alpine.data(\'name\', () => ({...})) and reference it with x-data="name" — do NOT cram methods, template literals, or branching logic into an inline x-data="{...}" attribute (HTML parser pitfalls cause ReferenceError failures). Define every variable referenced from x-text/x-show/x-if/x-for on the data object\'s initial state. If the extension\'s value depends on an LLM call, require a real key via \\${keys.OPENAI_API_KEY}/\\${keys.ANTHROPIC_API_KEY} (and tell the user to add it in the Dispatch Vault, or in app Settings → API Keys & Connections for standalone apps, if missing) or route the AI work to the agent chat — never ship a stubbed analysis step that renders a placeholder/boolean as the result.',
495
+ 'Create a persisted sandboxed Alpine.js mini-app extension and render it inline in the chat. Use this when the user wants generated UI that should be saved, reusable, or visible in the Extensions view: extensions, widgets, dashboards, calculators, mini-apps, and reusable interactive utilities. For one-time chat-only UI, use render-inline-extension instead. The content must be a self-contained Alpine.js HTML body snippet that can use appAction(), appFetch(), dbQuery(), extensionFetch(), extensionData, agentNative.ui.output(value, opts?), and agentNative.chat.send()/sendToAgentChat(). Use appAction() for app data writes and extensionData for extension-owned persisted UI state; dbQuery() is for read-only inspection of known app SQL tables. Use agentNative.ui.output for passive current values from knobs, sliders, and selections; it writes application state at inline-ui:<extension id>:output, which the agent can read later with readAppState when the user says to use that value. Use agentNative.chat.send for visible submit/apply actions. Persist reusable user-edited state with extensionData: if the extension has checkboxes, todos, notes, filters, preferences, or any control whose value should survive reload/reopen, load that state on init and save changes with extensionData, usually at user scope, instead of keeping it only in Alpine state. IMPORTANT — hosting a pasted file: if the user pasted a large HTML/Alpine file (it appears in your context as an <attachment name="pasted-text-…"> block) and asked you to host it as-is, do NOT copy that file into `content`. Instead leave `content` empty and pass `contentFromAttachment` set to that attachment\'s name (or the literal "latest" for the most recent pasted block) — the server reads the file verbatim. Re-emitting a large pasted file as `content` regularly gets cut off mid-stream and stalls the turn. IMPORTANT — cloning a large extension that lives as a workspace resource (not a chat attachment): leave `content` empty and pass `contentFromWorkspaceFile` set to the resource path (e.g. "intuit-analytics-extension.html"); the server reads the full file. Do NOT try to reconstruct the body with run-code or route create-extension through run-code (mutating actions are not callable there). Prefer appAction(name, params) for app data and actions, including read actions mounted as GET; do not call template /api/* routes from appFetch because the extension bridge only allows framework /_agent-native/* paths. Parse JSON string action results before aggregating; use dbQuery() only for known existing SQL tables and never for writes. Keep the initial create-extension payload compact and working; for complex extensions, create a useful v1 first, then use focused update-extension edits for refinements rather than assembling one enormous initial tool input. For any non-trivial component (more than a couple of state fields, any methods, any string formatting, any branching) put the component in a <script> block via Alpine.data(\'name\', () => ({...})) and reference it with x-data="name" — do NOT cram methods, template literals, or branching logic into an inline x-data="{...}" attribute (HTML parser pitfalls cause ReferenceError failures). Define every variable referenced from x-text/x-show/x-if/x-for on the data object\'s initial state. If the extension\'s value depends on an LLM call, require a real key via \\${keys.OPENAI_API_KEY}/\\${keys.ANTHROPIC_API_KEY} (and tell the user to add it in the Dispatch Vault, or in app Settings → API Keys & Connections for standalone apps, if missing) or route the AI work to the agent chat — never ship a stubbed analysis step that renders a placeholder/boolean as the result.',
487
496
  parameters: {
488
497
  type: "object",
489
498
  properties: {
@@ -506,6 +515,11 @@ export function createExtensionActionEntries(): Record<string, ActionEntry> {
506
515
  description:
507
516
  'Host a pasted/attached file verbatim WITHOUT re-typing it. Set this to the name of an attachment on the current turn (e.g. "pasted-text-1718000000000-ab12cd.txt") or the literal "latest" for the most recent pasted block; the server resolves it into the extension content. Use this instead of `content` whenever the user pasted a large file to host — it avoids re-emitting thousands of tokens. When set, leave `content` empty.',
508
517
  },
518
+ contentFromWorkspaceFile: {
519
+ type: "string",
520
+ description:
521
+ 'Host a workspace/shared resource file verbatim WITHOUT re-typing it. Set this to the resource path (e.g. "intuit-analytics-extension.html"); the server reads the full file and uses it as the extension content. Use this — NOT run-code or contentFromAttachment — when cloning a large extension body that already exists as a workspace resource. When set, leave `content` empty.',
522
+ },
509
523
  icon: {
510
524
  type: "string",
511
525
  description: "Optional icon name or short label.",
@@ -521,7 +535,7 @@ export function createExtensionActionEntries(): Record<string, ActionEntry> {
521
535
  run: async (args, ctx) => {
522
536
  const name = String(args?.name ?? "").trim();
523
537
  if (!name) return "Error: name is required.";
524
- const resolved = resolveExtensionContent(args, ctx);
538
+ const resolved = await resolveExtensionContentAsync(args, ctx);
525
539
  if ("error" in resolved) return resolved.error;
526
540
  const content = resolved.content.trim();
527
541
  if (!content) return "Error: content is required.";
@@ -553,9 +567,12 @@ export function createExtensionActionEntries(): Record<string, ActionEntry> {
553
567
  } catch {
554
568
  // Non-fatal — agent can still mention the path in its reply.
555
569
  }
570
+ const hiddenIds = await getHiddenExtensionIdsForCurrentUser();
556
571
  return {
557
572
  ok: true,
558
- extension: { ...existing, path: existingPath },
573
+ // Compact summary (contentLength + contentHash, no full body). Echoing
574
+ // the whole HTML back is pure token waste — the agent just supplied it.
575
+ extension: await summarizeExtension(existing, hiddenIds, false),
559
576
  path: existingPath,
560
577
  next: `Extension was already created in this session (recovered from a connection retry). The user is being navigated to it — no further navigation tool calls needed.`,
561
578
  };
@@ -585,9 +602,12 @@ export function createExtensionActionEntries(): Record<string, ActionEntry> {
585
602
  // Non-fatal — agent can still mention the path in its reply.
586
603
  }
587
604
 
605
+ const hiddenIds = await getHiddenExtensionIdsForCurrentUser();
588
606
  return {
589
607
  ok: true,
590
- extension: { ...extension, path },
608
+ // Compact summary (contentLength + contentHash, no full body). Echoing
609
+ // the whole HTML back is pure token waste — the agent just supplied it.
610
+ extension: await summarizeExtension(extension, hiddenIds, false),
591
611
  path,
592
612
  next: `Created. The user is being navigated to the new extension automatically — no further navigation tool calls needed.`,
593
613
  };
@@ -624,6 +644,11 @@ export function createExtensionActionEntries(): Record<string, ActionEntry> {
624
644
  description:
625
645
  'Optional full replacement sourced from a pasted/attached file on the current turn, by attachment name (or the literal "latest" for the most recent pasted block). Use instead of `content` when replacing the whole body with a large pasted file so you do not have to re-type it. Ignored when `content` is provided.',
626
646
  },
647
+ contentFromWorkspaceFile: {
648
+ type: "string",
649
+ description:
650
+ 'Optional full replacement sourced from a workspace/shared resource file, by resource path (e.g. "intuit-analytics-extension.html"). The server reads the full file and uses it as the replacement body. Use instead of `content` when replacing the whole body with a large file that exists as a workspace resource. Ignored when `content` is provided.',
651
+ },
627
652
  patches: {
628
653
  type: "string",
629
654
  description:
@@ -670,9 +695,10 @@ export function createExtensionActionEntries(): Record<string, ActionEntry> {
670
695
  : undefined;
671
696
  if (
672
697
  replacementContent === undefined &&
673
- args?.contentFromAttachment !== undefined
698
+ (args?.contentFromAttachment !== undefined ||
699
+ args?.contentFromWorkspaceFile !== undefined)
674
700
  ) {
675
- const resolved = resolveExtensionContent(args, ctx);
701
+ const resolved = await resolveExtensionContentAsync(args, ctx);
676
702
  if ("error" in resolved) return resolved.error;
677
703
  replacementContent = resolved.content;
678
704
  }
@@ -1320,6 +1346,114 @@ function resolveExtensionContent(
1320
1346
  return { content: resolved };
1321
1347
  }
1322
1348
 
1349
+ /**
1350
+ * Resolve the workspace-files bridge scope exactly the way run-code's
1351
+ * workspaceRead/workspaceWrite do: org-preferred (org → shared owner) with the
1352
+ * requesting user's email as the solo fallback. Kept in lockstep with
1353
+ * `resolveScope` in `workspace-files/tool.ts`.
1354
+ */
1355
+ function workspaceFilesBridgeScope(): WorkspaceFilesScope | null {
1356
+ const orgId = getRequestOrgId();
1357
+ if (orgId) return { scope: "org", scopeId: orgId };
1358
+ const email = getRequestUserEmail();
1359
+ if (email) return { scope: "user", scopeId: email };
1360
+ return null;
1361
+ }
1362
+
1363
+ /**
1364
+ * Read a workspace/shared/personal resource file's FULL content by path.
1365
+ *
1366
+ * Precedence (single, documented rule so this never silently resolves a
1367
+ * different file than the agent inspected):
1368
+ * 1. The run-code `workspace-files` bridge scope (org → shared owner, else the
1369
+ * user's email). This is the SAME owner/scope `workspaceRead` /
1370
+ * `workspaceWrite` use, so a body the agent staged via `workspaceWrite` is
1371
+ * resolved here verbatim — the two paths cannot diverge.
1372
+ * 2. User-managed Resources (personal override → org/shared → workspace
1373
+ * default) as a fallback, for pre-built resources that were created in the
1374
+ * Resources panel rather than staged through the bridge.
1375
+ *
1376
+ * Unlike attachments, resource content is not capped/truncated on the way in, so
1377
+ * this is the correct path for cloning a large extension body that already
1378
+ * exists as a workspace resource (e.g. a per-customer dashboard).
1379
+ */
1380
+ async function readWorkspaceFileContent(path: string): Promise<string | null> {
1381
+ const trimmed = path.trim();
1382
+ if (!trimmed) return null;
1383
+ // 1) Bridge parity — resolve exactly the file workspaceRead/workspaceWrite see.
1384
+ const bridgeScope = workspaceFilesBridgeScope();
1385
+ if (bridgeScope) {
1386
+ let bridgeFile: Awaited<ReturnType<typeof readWorkspaceFile>>;
1387
+ try {
1388
+ bridgeFile = await readWorkspaceFile(bridgeScope, trimmed);
1389
+ } catch {
1390
+ // A THROW here is a transient store error or invalid path — NOT a
1391
+ // definitive "not found". Fail closed rather than silently hosting a
1392
+ // possibly-different same-path Resources body than workspaceRead
1393
+ // inspected. A retry re-runs this read cleanly.
1394
+ return null;
1395
+ }
1396
+ // A null result means the file genuinely does not exist in the bridge scope;
1397
+ // fall through to user-managed Resources for pre-built resource-panel files.
1398
+ if (bridgeFile && typeof bridgeFile.content === "string") {
1399
+ return bridgeFile.content;
1400
+ }
1401
+ }
1402
+ // 2) Fallback — user-managed Resources by scope precedence.
1403
+ for (const scope of ["personal", "shared", "workspace"] as const) {
1404
+ try {
1405
+ const content = await readResource(trimmed, { scope });
1406
+ if (typeof content === "string") return content;
1407
+ } catch {
1408
+ // A given scope can throw (e.g. `personal` when no user identity is
1409
+ // resolvable in this context). Don't let one scope abort the lookup —
1410
+ // fall through and try the next one.
1411
+ }
1412
+ }
1413
+ return null;
1414
+ }
1415
+
1416
+ /**
1417
+ * Resolve the extension HTML body from (in priority order) inline `content`, a
1418
+ * `contentFromWorkspaceFile` resource path, or a `contentFromAttachment` handle.
1419
+ *
1420
+ * The workspace-file path exists because a large extension body frequently lives
1421
+ * as a workspace resource (not a chat attachment). Without it the model has no
1422
+ * viable route — inline is too large to shuttle reliably, contentFromAttachment
1423
+ * only sees chat attachments, and mutating actions cannot run from run-code — so
1424
+ * it loops and the run aborts with no_progress.
1425
+ */
1426
+ async function resolveExtensionContentAsync(
1427
+ args: Record<string, string> | undefined,
1428
+ ctx: ActionRunContext | undefined,
1429
+ ): Promise<{ content: string } | { error: string }> {
1430
+ const inline = args?.content !== undefined ? String(args.content) : undefined;
1431
+ if (inline !== undefined && inline.trim().length > 0) {
1432
+ return { content: inline };
1433
+ }
1434
+
1435
+ const wsRef =
1436
+ args?.contentFromWorkspaceFile !== undefined
1437
+ ? String(args.contentFromWorkspaceFile).trim()
1438
+ : "";
1439
+ if (wsRef) {
1440
+ const content = await readWorkspaceFileContent(wsRef);
1441
+ if (content === null) {
1442
+ return {
1443
+ error: `Error: contentFromWorkspaceFile="${wsRef}" did not match any readable workspace/shared/personal resource file. Check the exact path (e.g. "intuit-analytics-extension.html"), or pass the HTML inline via content.`,
1444
+ };
1445
+ }
1446
+ if (content.trim().length === 0) {
1447
+ return {
1448
+ error: `Error: workspace file "${wsRef}" is empty. Pass non-empty HTML inline via content, or point contentFromWorkspaceFile at a file with content.`,
1449
+ };
1450
+ }
1451
+ return { content };
1452
+ }
1453
+
1454
+ return resolveExtensionContent(args, ctx);
1455
+ }
1456
+
1323
1457
  function coerceBoolean(value: unknown): boolean {
1324
1458
  return value === true || value === "true";
1325
1459
  }
@@ -143,6 +143,65 @@ Notes:
143
143
  "extension unavailable" message instead of the content. Share the extension to
144
144
  the same audience as the dashboard so all viewers can see it.
145
145
 
146
+ ## Cloning An Extension-Backed Dashboard (e.g. per-customer copies)
147
+
148
+ When the user asks for a copy of an existing extension-backed dashboard for a
149
+ different customer/org (for example "make an Intuit version of the Roku usage
150
+ dashboard"), follow this playbook. Extension bodies are frequently tens of
151
+ thousands of characters. The reliable path is to read+transform+write the body
152
+ INSIDE `run-code` (where `workspaceRead` returns the full file) and then create
153
+ from that written file — never by pulling the body into chat context first or
154
+ re-typing it as a `content` argument.
155
+
156
+ 1. `get-sql-dashboard` with `includeConfig: true` on the source dashboard and
157
+ confirm the target panel is `chartType: "extension"`; grab its
158
+ `config.extensionId`.
159
+ 2. `get-extension` for that id with `forceContent: true` **exactly once**. Reuse
160
+ that body for the rest of the turn — a second same-run read intentionally
161
+ omits `content` and returns `contentOmitted` instead. That is not the content
162
+ disappearing; use the copy you already have. Do NOT try to re-fetch the body
163
+ with `run-code` (`appAction('get-extension')`) to page past a display
164
+ truncation — the same-run omit makes it return empty `content`, wasting turns.
165
+ If you need the full body again, read the workspace resource file (step 5) or
166
+ set `forceContent: true` on a single native `get-extension`.
167
+ 3. Change ONLY the small customer-specific static config (e.g. the
168
+ `ACCOUNT_USAGE_STATIC` block: company name, title, org-discovery filters,
169
+ messaging). Prefer a focused `update-extension` edit/patch over regenerating
170
+ the entire HTML.
171
+ 4. **Call `create-extension` / `update-extension` as native tools.** They are
172
+ mutating actions and are NOT callable from `run-code` / `appAction` (the
173
+ sandbox bridge only exposes read-only actions). Do not try to create or update
174
+ an extension from inside `run-code`.
175
+ 5. **If the source body already exists as a workspace/shared resource file**
176
+ (e.g. a pre-built `intuit-analytics-extension.html`), do the read AND the
177
+ customer swap in ONE `run-code` call, then create from the written file:
178
+ - Inside `run-code`: `const src = await workspaceRead('<source>.html')`
179
+ returns the WHOLE file (it auto-pages; there is no 50k cap here), do the
180
+ small string-replace on the static config block, then
181
+ `await workspaceWrite('<target>.html', modified)`.
182
+ - Then call `create-extension` (native) with
183
+ `contentFromWorkspaceFile: '<target>.html'` and leave `content` empty — the
184
+ server reads the full file verbatim.
185
+ Do NOT read the source body with the `resources` read tool (or `get-extension`)
186
+ first just to transform it: that display is capped and wastes a turn. And do
187
+ NOT re-emit an 80k+ char body as the `content` argument — it gets cut off
188
+ mid-stream. `contentFromAttachment` only sees files the user pasted into chat,
189
+ not workspace resources. `create-extension`/`update-extension` are mutating and
190
+ cannot run from `run-code`, so only the read+write+transform happens there.
191
+ 6. Finally `update-dashboard` to save a new dashboard embedding the new
192
+ extension panel (`chartType: "extension"`, `config.extensionId`), then
193
+ `navigate` to it.
194
+
195
+ ### Display truncation is cosmetic — do not chase the "missing" tail
196
+
197
+ A tool result ending in `...[truncated — full result was N chars; only first
198
+ 50,000 shown]` (from the `resources` read tool or `get-extension`) means only the
199
+ DISPLAYED text was capped. The file is intact. `run-code`'s `workspaceRead`
200
+ returns the full N chars, and `contentFromWorkspaceFile` hosts the full file.
201
+ Never read the same file twice or try to "page the rest" to recover the tail —
202
+ that is the single biggest source of wasted turns on clone requests. Decide to
203
+ clone, then go straight to the `run-code` read+transform+write path in step 5.
204
+
146
205
  ## Config Shape
147
206
 
148
207
  ```jsonc
@@ -14,10 +14,13 @@ import {
14
14
 
15
15
  const DASHBOARD_CONTEXT =
16
16
  "The user wants to create a new analytics dashboard. " +
17
- "REAL_DATA_REQUIRED: before saving or answering, run at least one real data-source query action; `data-source-status`, `list-data-dictionary`, `update-dashboard`, and dry-run validation do not count as data queries. " +
17
+ "TEMPLATE FIRST If the user names an existing dashboard as a template to clone/base this on, resolve its id first (use `list-sql-dashboards` if you only have a title), then call `get-sql-dashboard` with `includeConfig: true` immediately and inspect `panels[].chartType`. " +
18
+ 'If any panel is `chartType: "extension"`, this is an extension-backed dashboard: call `get-extension` for that panel\'s `config.extensionId`, clone/adapt it with `create-extension` (apply the requested customer/org filters), then save a new dashboard via `update-dashboard` that embeds the new extension panel (`chartType: "extension"`, `config.extensionId`). Do not rebuild an extension template as guessed SQL/BigQuery panels. ' +
19
+ "LARGE EXTENSION CLONE — Extension bodies can be very large (tens of thousands of characters). Call `get-extension` with `forceContent: true` exactly ONCE and reuse that body; a second same-run read intentionally omits `content` (you'll see `contentOmitted`), so don't treat that as the content being gone. Call `create-extension` / `update-extension` as NATIVE tools — they are mutating actions and cannot be invoked from `run-code`/`appAction`. For customer-specific clones, change only the small static config block (e.g. `ACCOUNT_USAGE_STATIC`) and prefer a focused `update-extension` edit over regenerating the whole HTML. Never shovel the full body through `run-code` or chat; if you stage it in a workspace scratch file, read it back with `workspaceRead` (which returns the whole file). " +
20
+ "REAL_DATA_REQUIRED: before presenting numbers or authoring new SQL that invents tables/columns/filters, run at least one real data-source query action; `data-source-status`, `list-data-dictionary`, `get-sql-dashboard`, `get-extension`, `update-dashboard`, `mutate-dashboard`, and dry-run validation do not count as data queries. It is OK to inspect a template, clone an extension shell, ask one clarifying question (org id / account filter), or report an exact unavailable/error result without running a data query, as long as you do not invent metrics. " +
18
21
  "The `demo` source is reserved for the built-in Node Exporter demo and does not satisfy REAL_DATA_REQUIRED unless the user explicitly asks to work on that demo dashboard. " +
19
22
  "If no source can answer, report the exact unavailable/error result instead of saving a dashboard with guessed schema or metrics. " +
20
- "Create a SQL-driven dashboard by calling the `update-dashboard` action with `dashboardId` and `config`. " +
23
+ "SQL PANELS — Only for native SQL dashboards (not template clones of an extension-backed dashboard): create a SQL-driven dashboard by calling the `update-dashboard` action with `dashboardId` and `config`. " +
21
24
  "The config shape is: { name: string, panels: [{ id, title, sql, source, chartType, width, tab?, config? }] }. " +
22
25
  "Each panel needs: id (unique string), title, sql (the query), source ('bigquery' | 'ga4' | 'amplitude' | 'first-party' | 'demo' | 'prometheus'), " +
23
26
  "chartType ('line' | 'area' | 'bar' | 'metric' | 'table' | 'pie'), width (1 or 2). " +
@@ -16,23 +16,32 @@ export const INITIAL_TOOL_NAMES = [
16
16
  "list-analyses",
17
17
  "get-analysis",
18
18
  "save-analysis",
19
+ // Dashboard/extension INSPECTION stays on the initial surface so a
20
+ // template-clone request can resolve and inspect the source on the first
21
+ // turn. The MUTATING writers (update-dashboard, mutate-dashboard,
22
+ // create-extension, update-extension) are intentionally left off: the
23
+ // dashboard-construction final-response guard retries with
24
+ // `expandToolSurface: true` (see server/plugins/agent-chat.ts), which opens
25
+ // the full run registry exactly when a save is needed, and tool-search can
26
+ // surface them otherwise. This keeps the first-request surface under the
27
+ // 40-tool ceiling enforced by scripts/guard-agent-chat-context.ts.
19
28
  "get-sql-dashboard",
20
- "mutate-dashboard",
29
+ "list-sql-dashboards",
30
+ "list-dashboard-templates",
31
+ "list-extensions",
32
+ "get-extension",
21
33
  "generate-chart",
22
34
  "query-agent-native-analytics",
23
35
  "bigquery",
24
36
  "search-bigquery-schema",
25
- "bigquery-table-info",
26
37
  "provider-api-catalog",
27
38
  "provider-api-docs",
28
39
  "provider-api-request",
29
40
  "run-code",
30
41
  "get-code-execution",
31
42
  "provider-corpus-job",
32
- "provider-corpus-jobs",
33
43
  "query-staged-dataset",
34
44
  "list-staged-datasets",
35
- "delete-staged-dataset",
36
45
  "account-deep-dive",
37
46
  "hubspot-deals",
38
47
  "hubspot-records",
@@ -57,6 +57,25 @@ export const CORPUS_SOURCE_ACTIONS = new Set([
57
57
 
58
58
  export const CORPUS_REDUCTION_ACTIONS = new Set(["run-code"]);
59
59
 
60
+ // Inspecting or cloning an existing dashboard/extension template is
61
+ // construction progress, not a metric query. These do not satisfy
62
+ // hasDataQueryAttempt, but they should stop the guard from steering a
63
+ // template-clone turn into "connect a missing source". Deliberately limited
64
+ // to read/inspection actions: update-dashboard/mutate-dashboard/
65
+ // compose-dashboard/install-dashboard-template/create-extension/
66
+ // update-extension can all author brand-new SQL or extension content, so
67
+ // calling one of those alone is not proof the turn actually inspected a
68
+ // template rather than inventing it from scratch. If the tool run also
69
+ // includes one of these read actions, the bypass still applies even when an
70
+ // authoring/save action ran alongside it.
71
+ export const DASHBOARD_CONSTRUCTION_ACTIONS = new Set([
72
+ "get-sql-dashboard",
73
+ "list-sql-dashboards",
74
+ "list-dashboard-templates",
75
+ "list-extensions",
76
+ "get-extension",
77
+ ]);
78
+
60
79
  const RUN_CODE_BRIDGE_TOOLS_USED = /^bridgeToolsUsed:\s*(.+)$/im;
61
80
 
62
81
  const MCP_DATA_SOURCE_TOKENS = [
@@ -97,6 +116,41 @@ function isDataQueryActionName(name: string): boolean {
97
116
  return DATA_QUERY_ACTIONS.has(normalizeActionToolName(name));
98
117
  }
99
118
 
119
+ function isDashboardConstructionActionName(name: string): boolean {
120
+ return DASHBOARD_CONSTRUCTION_ACTIONS.has(normalizeActionToolName(name));
121
+ }
122
+
123
+ // "Build/clone/template" language targeting a dashboard/extension/panel is
124
+ // dashboard construction, distinct from an analytics-result question. Turns
125
+ // like this may inspect and clone a template without running a metric query.
126
+ const DASHBOARD_CONSTRUCTION_INTENT_TERMS =
127
+ /\b(build|create|make|clone|copy|duplicate|adapt|template|based (?:off|on)|using .{1,80}? as a template)\b/i;
128
+
129
+ const DASHBOARD_CONSTRUCTION_TARGET_TERMS =
130
+ /\b(dashboard|extension|panel|widget)\b/i;
131
+
132
+ export function looksLikeDashboardConstructionRequest(text: string): boolean {
133
+ const requestText = stripInjectedAnalyticsGuardContext(text);
134
+ const lower = requestText.toLowerCase();
135
+ if (!lower) return false;
136
+ const wantsBuild = DASHBOARD_CONSTRUCTION_INTENT_TERMS.test(lower);
137
+ const targetsDashboard =
138
+ DASHBOARD_CONSTRUCTION_TARGET_TERMS.test(lower) ||
139
+ lower.includes(REAL_DATA_REQUIRED_MARKER.toLowerCase());
140
+ return wantsBuild && targetsDashboard;
141
+ }
142
+
143
+ export function hasDashboardConstructionAttempt(
144
+ toolResults:
145
+ | Array<{ name?: string; isError?: boolean; content?: string }>
146
+ | undefined,
147
+ ): boolean {
148
+ return (toolResults ?? []).some((result) => {
149
+ if (result.isError) return false;
150
+ return isDashboardConstructionActionName(String(result.name ?? ""));
151
+ });
152
+ }
153
+
100
154
  function isCorpusSourceActionName(name: string): boolean {
101
155
  return CORPUS_SOURCE_ACTIONS.has(normalizeActionToolName(name));
102
156
  }
@@ -253,7 +307,15 @@ export function looksLikeAnalyticsDataRequest(text: string): boolean {
253
307
  }
254
308
 
255
309
  const UNSUPPORTED_RESULT_CLAIM =
256
- /(?:\b\d[\d,.]*(?:\.\d+)?\s*(?:%|percent|users?|customers?|accounts?|sessions?|events?|deals?|tickets?|issues?|calls?|messages?|signups?|pageviews?)\b|\$\s*\d|\b(?:data|query|results?)\s+(?:shows?|showed|indicates?|returned|found)\b|\b(?:i found|the top|the bottom|highest|lowest|increased|decreased|grew|declined|converted|churned|retained|averaged|total(?:ed)?|count(?:ed)?)\b)/i;
310
+ /(?:\b\d[\d,.]*(?:\.\d+)?\s*(?:%|percent|users?|customers?|accounts?|sessions?|events?|deals?|tickets?|issues?|calls?|messages?|signups?|pageviews?)\b|\$\s*\d|\b(?:zero|no|none)\s+(?:users?|customers?|accounts?|sessions?|events?|deals?|tickets?|issues?|calls?|messages?|signups?|pageviews?)\b|\b(?:data|query|results?)\s+(?:shows?|showed|indicates?|returned|found)\b|\b(?:i found|the top|the bottom|highest|lowest|increased|decreased|grew|declined|converted|churned|retained|averaged|total(?:ed)?|count(?:ed)?)\b)/i;
311
+
312
+ // Reuse the same broad unsupported-result-claim vocabulary that gates
313
+ // isSafeNoDataAnalyticsResponse so a dashboard-construction turn cannot
314
+ // bypass the no-query fallback just by avoiding the narrower set of units a
315
+ // dashboard-specific regex would otherwise miss (e.g. "signups", "accounts").
316
+ export function draftClaimsAnalyticsMetrics(text: string): boolean {
317
+ return UNSUPPORTED_RESULT_CLAIM.test(String(text ?? "").trim());
318
+ }
257
319
 
258
320
  export const GENERIC_NO_DATA_FALLBACK_MESSAGE =
259
321
  "I can't provide a grounded analytics result yet because no real data-source query ran successfully. Tell me which source to use or connect the missing source, and I'll run it before giving numbers or source-record conclusions.";
@@ -14,7 +14,9 @@ import {
14
14
  import { ANALYTICS_CONNECTOR_CATALOG } from "../lib/analytics-connector-catalog";
15
15
  import { credentialProviderConfigs } from "../lib/credential-keys";
16
16
  import {
17
+ draftClaimsAnalyticsMetrics,
17
18
  failedDataQueryAttemptMessage,
19
+ hasDashboardConstructionAttempt,
18
20
  hasExplicitPartialDisclosure,
19
21
  hasFailedCorpusWorkflowEvidence,
20
22
  hasDataQueryAttempt,
@@ -23,6 +25,7 @@ import {
23
25
  isSafeNoDataAnalyticsResponse,
24
26
  hasOverstatedCoverageConfidenceClaim,
25
27
  looksLikeCoverageSensitiveAnalyticsRequest,
28
+ looksLikeDashboardConstructionRequest,
26
29
  looksLikeStrongCoverageClaim,
27
30
  looksLikeAnalyticsDataRequest,
28
31
  needsCorpusWorkflowForCoverageSensitiveRequest,
@@ -522,6 +525,33 @@ export function realDataFinalGuard(
522
525
  "I can't make a confident exhaustive analytics claim yet because part of the source evidence was aborted, truncated, or still paginated. I need to recover the missing coverage or state the answer as partial with the inspected sample size.",
523
526
  };
524
527
  }
528
+ // Dashboard construction/template-clone turns may inspect and clone an
529
+ // existing dashboard/extension without running a metric query, as long as
530
+ // the draft does not invent numbers. Check this before the generic
531
+ // "no data query ran" fallback so a template-based extension clone is not
532
+ // treated the same as an unanswerable analytics-result question.
533
+ if (
534
+ looksLikeDashboardConstructionRequest(userText) &&
535
+ !draftClaimsAnalyticsMetrics(context.text)
536
+ ) {
537
+ if (
538
+ hasDashboardConstructionAttempt(context.toolResults) ||
539
+ isSafeNoDataAnalyticsResponse(context.text)
540
+ ) {
541
+ return null;
542
+ }
543
+ return {
544
+ retryMessage:
545
+ 'This is a dashboard construction/template-clone request. Resolve the named template\'s id (use `list-sql-dashboards` if you only have a title) and call `get-sql-dashboard` with `includeConfig: true` first. If its panels are `chartType: "extension"`, use `get-extension` then `create-extension` to clone/adapt it, then `update-dashboard` to save the new dashboard. Do not invent SQL panels for an extension-backed template. Ask one clarifying filter question if needed. Only run a data-source query before presenting numbers or authoring invented SQL.',
546
+ fallbackMessage:
547
+ "I need to inspect the template dashboard (and its extension, if it uses one) before creating the new one. Tell me the template dashboard name, or confirm the org/account filter, and I'll clone it without inventing metrics.",
548
+ // list-sql-dashboards/list-dashboard-templates are on the initial
549
+ // surface, but expand anyway so a corrective retry can always reach
550
+ // the lookup/inspection tools this message asks for.
551
+ expandToolSurface: true,
552
+ };
553
+ }
554
+
525
555
  if (dataQueryAttempted) return null;
526
556
  if (isSafeNoDataAnalyticsResponse(context.text)) {
527
557
  if (firstPartySourceShouldBeTried) {