@anuma/sdk 6.39.0 → 6.39.1

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.
@@ -6022,15 +6022,17 @@ Build ONLY when the user gives an explicit instruction to build, create, generat
6022
6022
 
6023
6023
  Once the user HAS given an explicit build instruction, you are in App Builder mode: you produce polished, production-quality React apps that feel designed \u2014 not generic.
6024
6024
 
6025
- DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a logic, data, or behavior-only change, skip the brief and just make the change.
6025
+ DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a text, logic, data, or behavior-only change, skip the brief and just make the change.
6026
+
6027
+ EDIT SCOPE: Change only the files and lines required by the current user request. A title rename is a text edit, not a design change. Preserve styles, dependencies, and unrelated logic on text edits. Design feedback does not authorize unrelated edits.
6026
6028
 
6027
6029
  WORKFLOW:
6028
6030
  1. NEVER output code as text or markdown. ALWAYS use tools.
6029
6031
  2. Initial build: state your design brief, then create_file with a "files" array writing ALL files in one call. The preview renders automatically.
6030
6032
  3. patch_file requires read_file for that path earlier in the conversation (or create_file in the same conversation, which counts). read_file output is numbered "42: <text>" \u2014 the prefix is display-only; never copy it into "find". Each "find" must match exactly one location \u2014 include 2-3 lines of surrounding context. Pass multiple patches per call to change distinct locations.
6031
6033
  4. Prefer patch_file for changes to existing files \u2014 surgical, reviewable, preserves surrounding code. Reserve create_file overwrites for substantial restructuring. Inserts: find the line before, replace with that line + the new line. Deletes: empty replace.
6032
- 5. After substantial changes, call critique_design first (taste, hierarchy, distinctiveness, weakest decision) and then audit_design (mechanical: tokens, focus states, aria-labels, alt, heading order). Patch what each surfaces. critique catches taste issues no checklist would; audit catches mechanics you'd miss. Run both; act on both.
6033
- 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip \u2014 audit + critique are your feedback in that case.
6034
+ 5. On the initial build, when adding new UI, or after user-requested design changes, call critique_design first and then audit_design. Critique checks taste, hierarchy, and distinctiveness. Audit checks tokens, focus states, aria-labels, alt text, and heading order. Patch only issues within the current user request. For text, logic, or data edits, skip both design tools.
6035
+ 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip runtime verification. An unavailable runtime verifier does not authorize design changes. Use audit_design and critique_design only for the initial build, adding new UI, or user-requested design changes.
6034
6036
  7. Keep responses to a sentence or two. Exception: when responding to critique_design, write a substantive paragraph per rubric question.
6035
6037
 
6036
6038
  STRUCTURE:
@@ -6196,12 +6198,13 @@ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
6196
6198
  if (!cache) return true;
6197
6199
  return Date.now() - cache.timestamp > expirationMs;
6198
6200
  }
6199
- function buildCacheEntry(tools, checksum) {
6201
+ function buildCacheEntry(tools, checksum, etag) {
6200
6202
  return {
6201
6203
  tools,
6202
6204
  timestamp: Date.now(),
6203
6205
  version: CACHE_VERSION,
6204
- ...checksum && { checksum }
6206
+ ...checksum && { checksum },
6207
+ ...etag && { etag }
6205
6208
  };
6206
6209
  }
6207
6210
  function writeLocalStorageCache(entry) {
@@ -6236,19 +6239,36 @@ function shouldRefreshTools(responseChecksum, cache = localStorageToolsCache) {
6236
6239
  const cachedChecksum = getToolsChecksum2(cache);
6237
6240
  return cachedChecksum instanceof Promise ? cachedChecksum.then(decide) : decide(cachedChecksum);
6238
6241
  }
6239
- async function fetchServerToolsFromApi(baseUrl, token) {
6240
- const response = await fetch(`${baseUrl}/api/v1/tools`, {
6242
+ async function fetchServerToolsFromApi(baseUrl, authHeaders, etag) {
6243
+ const request = (validator) => fetch(`${baseUrl}/api/v1/tools`, {
6241
6244
  method: "GET",
6242
6245
  headers: {
6243
- Authorization: `Bearer ${token}`,
6244
- "Content-Type": "application/json"
6246
+ ...authHeaders,
6247
+ "Content-Type": "application/json",
6248
+ ...validator && { "If-None-Match": validator }
6245
6249
  }
6246
6250
  });
6251
+ let response;
6252
+ try {
6253
+ response = await request(etag);
6254
+ } catch (error) {
6255
+ if (!etag || !(error instanceof TypeError)) throw error;
6256
+ etag = void 0;
6257
+ response = await request();
6258
+ }
6259
+ if (etag && response.status === 304) {
6260
+ return { notModified: true };
6261
+ }
6247
6262
  if (!response.ok) {
6248
6263
  throw new Error(`Failed to fetch server tools: ${response.status}`);
6249
6264
  }
6250
6265
  const data = await response.json();
6251
- return convertServerToolsResponse(data);
6266
+ const responseEtag = response.headers?.get("ETag") ?? void 0;
6267
+ return {
6268
+ notModified: false,
6269
+ ...convertServerToolsResponse(data),
6270
+ ...responseEtag && { etag: responseEtag }
6271
+ };
6252
6272
  }
6253
6273
  async function getServerTools(options) {
6254
6274
  const {
@@ -6280,34 +6300,30 @@ async function getServerTools(options) {
6280
6300
  try {
6281
6301
  const { BASE_URL: BASE_URL2 } = await import("./clientConfig-VPOGQRNP.mjs");
6282
6302
  const effectiveBaseUrl = baseUrl ?? BASE_URL2;
6303
+ const validator = cached && !forceRefresh ? cached.etag : void 0;
6304
+ let authHeaders;
6283
6305
  if (apiKey) {
6284
- const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
6285
- method: "GET",
6286
- headers: {
6287
- "X-API-Key": apiKey,
6288
- "Content-Type": "application/json"
6289
- }
6290
- });
6291
- if (!response.ok) {
6292
- throw new Error(`Failed to fetch server tools: ${response.status}`);
6306
+ authHeaders = { "X-API-Key": apiKey };
6307
+ } else {
6308
+ if (!getToken) {
6309
+ getLogger().warn("[serverTools] No auth method available for fetching tools");
6310
+ return cached?.tools ?? [];
6311
+ }
6312
+ const token = await getToken();
6313
+ if (!token) {
6314
+ getLogger().warn("[serverTools] No auth token available for fetching tools");
6315
+ return cached?.tools ?? [];
6293
6316
  }
6294
- const data = await response.json();
6295
- const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
6296
- await persistCache(buildCacheEntry(tools2, checksum2));
6297
- return tools2;
6317
+ authHeaders = { Authorization: `Bearer ${token}` };
6298
6318
  }
6299
- if (!getToken) {
6300
- getLogger().warn("[serverTools] No auth method available for fetching tools");
6301
- return cached?.tools ?? [];
6319
+ const result = await fetchServerToolsFromApi(effectiveBaseUrl, authHeaders, validator);
6320
+ if (result.notModified) {
6321
+ const confirmed = cached;
6322
+ await persistCache({ ...confirmed, timestamp: Date.now() });
6323
+ return confirmed.tools;
6302
6324
  }
6303
- const token = await getToken();
6304
- if (!token) {
6305
- getLogger().warn("[serverTools] No auth token available for fetching tools");
6306
- return cached?.tools ?? [];
6307
- }
6308
- const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
6309
- await persistCache(buildCacheEntry(tools, checksum));
6310
- return tools;
6325
+ await persistCache(buildCacheEntry(result.tools, result.checksum, result.etag));
6326
+ return result.tools;
6311
6327
  } catch (error) {
6312
6328
  getLogger().error("[serverTools] Failed to fetch server tools:", error);
6313
6329
  if (cached?.tools) {
@@ -34824,6 +34840,128 @@ function useICloudBackup(options) {
34824
34840
 
34825
34841
  // src/react/useModels.ts
34826
34842
  import { useCallback as useCallback15, useEffect as useEffect10, useRef as useRef6, useState as useState12 } from "react";
34843
+ var MODELS_CACHE_TTL_MS = 5 * 60 * 1e3;
34844
+ var modelsCache = /* @__PURE__ */ new Map();
34845
+ var modelsInFlight = /* @__PURE__ */ new Map();
34846
+ var cacheGeneration = 0;
34847
+ function clearModelsCache() {
34848
+ cacheGeneration++;
34849
+ modelsCache.clear();
34850
+ modelsInFlight.clear();
34851
+ }
34852
+ function pruneStaleTokenEntries(newKey) {
34853
+ const [newBaseUrl, newProvider] = JSON.parse(newKey);
34854
+ for (const existingKey of modelsCache.keys()) {
34855
+ if (existingKey === newKey) continue;
34856
+ const [existingBaseUrl, existingProvider] = JSON.parse(existingKey);
34857
+ if (existingBaseUrl === newBaseUrl && existingProvider === newProvider) {
34858
+ modelsCache.delete(existingKey);
34859
+ }
34860
+ }
34861
+ }
34862
+ function fingerprintToken(token) {
34863
+ if (!token) return "anon";
34864
+ let h1 = 3735928559;
34865
+ let h2 = 1103547991;
34866
+ for (let i = 0; i < token.length; i++) {
34867
+ const ch = token.charCodeAt(i);
34868
+ h1 = Math.imul(h1 ^ ch, 2654435761);
34869
+ h2 = Math.imul(h2 ^ ch, 1597334677);
34870
+ }
34871
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
34872
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
34873
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
34874
+ }
34875
+ function modelsCacheKey(baseUrl, provider, token) {
34876
+ return JSON.stringify([baseUrl, provider ?? null, fingerprintToken(token)]);
34877
+ }
34878
+ async function fetchAllModelPages(baseUrl, provider, headers, previous, signal) {
34879
+ const pages = /* @__PURE__ */ new Map();
34880
+ const models = [];
34881
+ let pageToken;
34882
+ do {
34883
+ const pageKey = pageToken ?? "";
34884
+ const stored2 = previous?.pages.get(pageKey);
34885
+ const request = (etag) => getApiV1Models({
34886
+ baseUrl,
34887
+ headers: etag ? { ...headers, "If-None-Match": etag } : headers,
34888
+ query: { provider, page_token: pageToken },
34889
+ signal
34890
+ });
34891
+ let response = await request(stored2?.etag);
34892
+ if (stored2?.etag && !response.response && response.error) {
34893
+ response = await request();
34894
+ }
34895
+ let page;
34896
+ if (response.response?.status === 304) {
34897
+ if (!stored2) throw new Error("Failed to fetch models");
34898
+ page = stored2;
34899
+ } else {
34900
+ if (response.error) {
34901
+ const errorMsg = response.error.error ?? "Failed to fetch models";
34902
+ throw new Error(errorMsg);
34903
+ }
34904
+ page = {
34905
+ body: response.data ?? {},
34906
+ etag: response.response?.headers?.get("ETag") ?? void 0
34907
+ };
34908
+ }
34909
+ pages.set(pageKey, page);
34910
+ models.push(...page.body.data || []);
34911
+ pageToken = page.body.next_page_token;
34912
+ } while (pageToken);
34913
+ return { pages, models, fetchedAt: Date.now() };
34914
+ }
34915
+ function loadModels(key, baseUrl, provider, headers, force, signal) {
34916
+ const cached = modelsCache.get(key);
34917
+ if (cached && !force && Date.now() - cached.fetchedAt < MODELS_CACHE_TTL_MS) {
34918
+ return Promise.resolve([...cached.models]);
34919
+ }
34920
+ const shared = (force ? void 0 : modelsInFlight.get(key)) ?? startSharedRequest(key, baseUrl, provider, headers, cached);
34921
+ return waitForSharedRequest(key, shared, signal).then((models) => [...models]);
34922
+ }
34923
+ function startSharedRequest(key, baseUrl, provider, headers, previous) {
34924
+ const controller = new AbortController();
34925
+ const generation = cacheGeneration;
34926
+ const shared = {
34927
+ controller,
34928
+ waiters: 0,
34929
+ promise: Promise.resolve([])
34930
+ };
34931
+ shared.promise = fetchAllModelPages(baseUrl, provider, headers, previous, controller.signal).then((entry) => {
34932
+ if (modelsInFlight.get(key) === shared && generation === cacheGeneration) {
34933
+ pruneStaleTokenEntries(key);
34934
+ modelsCache.set(key, entry);
34935
+ }
34936
+ return entry.models;
34937
+ }).finally(() => {
34938
+ if (modelsInFlight.get(key) === shared) modelsInFlight.delete(key);
34939
+ });
34940
+ modelsInFlight.set(key, shared);
34941
+ return shared;
34942
+ }
34943
+ function waitForSharedRequest(key, shared, signal) {
34944
+ shared.waiters++;
34945
+ let left = false;
34946
+ const leave = () => {
34947
+ if (left) return;
34948
+ left = true;
34949
+ shared.waiters--;
34950
+ if (shared.waiters === 0) {
34951
+ shared.controller.abort();
34952
+ if (modelsInFlight.get(key) === shared) modelsInFlight.delete(key);
34953
+ }
34954
+ };
34955
+ if (signal.aborted) {
34956
+ leave();
34957
+ } else {
34958
+ signal.addEventListener("abort", leave, { once: true });
34959
+ }
34960
+ return shared.promise.finally(() => {
34961
+ left = true;
34962
+ signal.removeEventListener("abort", leave);
34963
+ });
34964
+ }
34827
34965
  function useModels(options = {}) {
34828
34966
  const { getToken, baseUrl = BASE_URL, provider, autoFetch = true } = options;
34829
34967
  const [models, setModels] = useState12([]);
@@ -34846,7 +34984,7 @@ function useModels(options = {}) {
34846
34984
  }
34847
34985
  };
34848
34986
  }, []);
34849
- const fetchModels = useCallback15(async () => {
34987
+ const fetchModels = useCallback15(async (force = false) => {
34850
34988
  if (abortControllerRef.current) {
34851
34989
  abortControllerRef.current.abort();
34852
34990
  }
@@ -34865,35 +35003,17 @@ function useModels(options = {}) {
34865
35003
  if (token) {
34866
35004
  headers["Authorization"] = `Bearer ${token}`;
34867
35005
  }
34868
- let allModels = [];
34869
- let nextPageToken;
34870
- do {
34871
- if (signal.aborted) return;
34872
- const response = await getApiV1Models({
34873
- baseUrl: baseUrlRef.current,
34874
- headers,
34875
- query: {
34876
- provider: providerRef.current,
34877
- page_token: nextPageToken
34878
- },
34879
- signal
34880
- });
34881
- if (response.error) {
34882
- const errorMsg = response.error.error ?? "Failed to fetch models";
34883
- throw new Error(errorMsg);
34884
- }
34885
- if (response.data) {
34886
- const newModels = response.data.data || [];
34887
- allModels = [...allModels, ...newModels];
34888
- nextPageToken = response.data.next_page_token;
34889
- }
34890
- } while (nextPageToken);
35006
+ const baseUrl2 = baseUrlRef.current;
35007
+ const provider2 = providerRef.current;
35008
+ const key = modelsCacheKey(baseUrl2, provider2, token);
35009
+ const allModels = await loadModels(key, baseUrl2, provider2, headers, force, signal);
34891
35010
  if (signal.aborted) return;
34892
35011
  setModels(allModels);
34893
35012
  } catch (err) {
34894
35013
  if (err instanceof Error && err.name === "AbortError") {
34895
35014
  return;
34896
35015
  }
35016
+ if (signal.aborted) return;
34897
35017
  setError(err instanceof Error ? err : new Error(String(err)));
34898
35018
  } finally {
34899
35019
  if (!signal.aborted) {
@@ -34906,7 +35026,7 @@ function useModels(options = {}) {
34906
35026
  }, []);
34907
35027
  const refetch = useCallback15(async () => {
34908
35028
  setModels([]);
34909
- await fetchModels();
35029
+ await fetchModels(true);
34910
35030
  }, [fetchModels]);
34911
35031
  const hasFetchedRef = useRef6(false);
34912
35032
  useEffect10(() => {
@@ -36958,6 +37078,7 @@ export {
36958
37078
  clearKeyPair,
36959
37079
  clearLazyTitleCache,
36960
37080
  clearMemoryTopicsOverrideOp,
37081
+ clearModelsCache,
36961
37082
  clearNotionToken,
36962
37083
  clearServerToolsCache,
36963
37084
  consoleLogger,
@@ -20430,15 +20430,17 @@ Build ONLY when the user gives an explicit instruction to build, create, generat
20430
20430
 
20431
20431
  Once the user HAS given an explicit build instruction, you are in App Builder mode: you produce polished, production-quality React apps that feel designed \u2014 not generic.
20432
20432
 
20433
- DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a logic, data, or behavior-only change, skip the brief and just make the change.
20433
+ DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a text, logic, data, or behavior-only change, skip the brief and just make the change.
20434
+
20435
+ EDIT SCOPE: Change only the files and lines required by the current user request. A title rename is a text edit, not a design change. Preserve styles, dependencies, and unrelated logic on text edits. Design feedback does not authorize unrelated edits.
20434
20436
 
20435
20437
  WORKFLOW:
20436
20438
  1. NEVER output code as text or markdown. ALWAYS use tools.
20437
20439
  2. Initial build: state your design brief, then create_file with a "files" array writing ALL files in one call. The preview renders automatically.
20438
20440
  3. patch_file requires read_file for that path earlier in the conversation (or create_file in the same conversation, which counts). read_file output is numbered "42: <text>" \u2014 the prefix is display-only; never copy it into "find". Each "find" must match exactly one location \u2014 include 2-3 lines of surrounding context. Pass multiple patches per call to change distinct locations.
20439
20441
  4. Prefer patch_file for changes to existing files \u2014 surgical, reviewable, preserves surrounding code. Reserve create_file overwrites for substantial restructuring. Inserts: find the line before, replace with that line + the new line. Deletes: empty replace.
20440
- 5. After substantial changes, call critique_design first (taste, hierarchy, distinctiveness, weakest decision) and then audit_design (mechanical: tokens, focus states, aria-labels, alt, heading order). Patch what each surfaces. critique catches taste issues no checklist would; audit catches mechanics you'd miss. Run both; act on both.
20441
- 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip \u2014 audit + critique are your feedback in that case.
20442
+ 5. On the initial build, when adding new UI, or after user-requested design changes, call critique_design first and then audit_design. Critique checks taste, hierarchy, and distinctiveness. Audit checks tokens, focus states, aria-labels, alt text, and heading order. Patch only issues within the current user request. For text, logic, or data edits, skip both design tools.
20443
+ 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip runtime verification. An unavailable runtime verifier does not authorize design changes. Use audit_design and critique_design only for the initial build, adding new UI, or user-requested design changes.
20442
20444
  7. Keep responses to a sentence or two. Exception: when responding to critique_design, write a substantive paragraph per rubric question.
20443
20445
 
20444
20446
  STRUCTURE:
@@ -20584,12 +20586,13 @@ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
20584
20586
  if (!cache) return true;
20585
20587
  return Date.now() - cache.timestamp > expirationMs;
20586
20588
  }
20587
- function buildCacheEntry(tools, checksum) {
20589
+ function buildCacheEntry(tools, checksum, etag) {
20588
20590
  return {
20589
20591
  tools,
20590
20592
  timestamp: Date.now(),
20591
20593
  version: CACHE_VERSION,
20592
- ...checksum && { checksum }
20594
+ ...checksum && { checksum },
20595
+ ...etag && { etag }
20593
20596
  };
20594
20597
  }
20595
20598
  function writeLocalStorageCache(entry) {
@@ -20624,19 +20627,36 @@ function shouldRefreshTools(responseChecksum, cache = localStorageToolsCache) {
20624
20627
  const cachedChecksum = getToolsChecksum(cache);
20625
20628
  return cachedChecksum instanceof Promise ? cachedChecksum.then(decide) : decide(cachedChecksum);
20626
20629
  }
20627
- async function fetchServerToolsFromApi(baseUrl, token) {
20628
- const response = await fetch(`${baseUrl}/api/v1/tools`, {
20630
+ async function fetchServerToolsFromApi(baseUrl, authHeaders, etag) {
20631
+ const request = (validator) => fetch(`${baseUrl}/api/v1/tools`, {
20629
20632
  method: "GET",
20630
20633
  headers: {
20631
- Authorization: `Bearer ${token}`,
20632
- "Content-Type": "application/json"
20634
+ ...authHeaders,
20635
+ "Content-Type": "application/json",
20636
+ ...validator && { "If-None-Match": validator }
20633
20637
  }
20634
20638
  });
20639
+ let response;
20640
+ try {
20641
+ response = await request(etag);
20642
+ } catch (error) {
20643
+ if (!etag || !(error instanceof TypeError)) throw error;
20644
+ etag = void 0;
20645
+ response = await request();
20646
+ }
20647
+ if (etag && response.status === 304) {
20648
+ return { notModified: true };
20649
+ }
20635
20650
  if (!response.ok) {
20636
20651
  throw new Error(`Failed to fetch server tools: ${response.status}`);
20637
20652
  }
20638
20653
  const data = await response.json();
20639
- return convertServerToolsResponse(data);
20654
+ const responseEtag = response.headers?.get("ETag") ?? void 0;
20655
+ return {
20656
+ notModified: false,
20657
+ ...convertServerToolsResponse(data),
20658
+ ...responseEtag && { etag: responseEtag }
20659
+ };
20640
20660
  }
20641
20661
  async function getServerTools(options) {
20642
20662
  const {
@@ -20668,34 +20688,30 @@ async function getServerTools(options) {
20668
20688
  try {
20669
20689
  const { BASE_URL: BASE_URL2 } = await Promise.resolve().then(() => (init_clientConfig(), clientConfig_exports));
20670
20690
  const effectiveBaseUrl = baseUrl ?? BASE_URL2;
20691
+ const validator = cached && !forceRefresh ? cached.etag : void 0;
20692
+ let authHeaders;
20671
20693
  if (apiKey) {
20672
- const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
20673
- method: "GET",
20674
- headers: {
20675
- "X-API-Key": apiKey,
20676
- "Content-Type": "application/json"
20677
- }
20678
- });
20679
- if (!response.ok) {
20680
- throw new Error(`Failed to fetch server tools: ${response.status}`);
20694
+ authHeaders = { "X-API-Key": apiKey };
20695
+ } else {
20696
+ if (!getToken) {
20697
+ getLogger().warn("[serverTools] No auth method available for fetching tools");
20698
+ return cached?.tools ?? [];
20681
20699
  }
20682
- const data = await response.json();
20683
- const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
20684
- await persistCache(buildCacheEntry(tools2, checksum2));
20685
- return tools2;
20686
- }
20687
- if (!getToken) {
20688
- getLogger().warn("[serverTools] No auth method available for fetching tools");
20689
- return cached?.tools ?? [];
20700
+ const token = await getToken();
20701
+ if (!token) {
20702
+ getLogger().warn("[serverTools] No auth token available for fetching tools");
20703
+ return cached?.tools ?? [];
20704
+ }
20705
+ authHeaders = { Authorization: `Bearer ${token}` };
20690
20706
  }
20691
- const token = await getToken();
20692
- if (!token) {
20693
- getLogger().warn("[serverTools] No auth token available for fetching tools");
20694
- return cached?.tools ?? [];
20707
+ const result = await fetchServerToolsFromApi(effectiveBaseUrl, authHeaders, validator);
20708
+ if (result.notModified) {
20709
+ const confirmed = cached;
20710
+ await persistCache({ ...confirmed, timestamp: Date.now() });
20711
+ return confirmed.tools;
20695
20712
  }
20696
- const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
20697
- await persistCache(buildCacheEntry(tools, checksum));
20698
- return tools;
20713
+ await persistCache(buildCacheEntry(result.tools, result.checksum, result.etag));
20714
+ return result.tools;
20699
20715
  } catch (error) {
20700
20716
  getLogger().error("[serverTools] Failed to fetch server tools:", error);
20701
20717
  if (cached?.tools) {
@@ -6468,6 +6468,8 @@ interface CachedServerTools {
6468
6468
  version: string;
6469
6469
  /** Checksum from the server for cache invalidation */
6470
6470
  checksum?: string;
6471
+ /** ETag from the server. The next refresh sends it in an If-None-Match header. */
6472
+ etag?: string;
6471
6473
  }
6472
6474
  /**
6473
6475
  * Pluggable persistence for the fetched server-tools list.
@@ -6564,7 +6566,9 @@ declare function shouldRefreshTools(responseChecksum: string | undefined, cache:
6564
6566
  * Flow:
6565
6567
  * 1. Check the cache backend (localStorage by default; override via `cache`)
6566
6568
  * 2. If cache valid and not force refresh, return cached tools
6567
- * 3. Otherwise, fetch from API, cache, and return
6569
+ * 3. Otherwise, fetch from API, cache, and return. When the cache holds an ETag,
6570
+ * the request sends If-None-Match. On 304 the cached tools stay and only the
6571
+ * stored timestamp changes.
6568
6572
  * 4. On fetch failure, return cached tools if available (stale-while-error)
6569
6573
  */
6570
6574
  declare function getServerTools(options: ServerToolsOptions): Promise<ServerTool[]>;
@@ -6468,6 +6468,8 @@ interface CachedServerTools {
6468
6468
  version: string;
6469
6469
  /** Checksum from the server for cache invalidation */
6470
6470
  checksum?: string;
6471
+ /** ETag from the server. The next refresh sends it in an If-None-Match header. */
6472
+ etag?: string;
6471
6473
  }
6472
6474
  /**
6473
6475
  * Pluggable persistence for the fetched server-tools list.
@@ -6564,7 +6566,9 @@ declare function shouldRefreshTools(responseChecksum: string | undefined, cache:
6564
6566
  * Flow:
6565
6567
  * 1. Check the cache backend (localStorage by default; override via `cache`)
6566
6568
  * 2. If cache valid and not force refresh, return cached tools
6567
- * 3. Otherwise, fetch from API, cache, and return
6569
+ * 3. Otherwise, fetch from API, cache, and return. When the cache holds an ETag,
6570
+ * the request sends If-None-Match. On 304 the cached tools stay and only the
6571
+ * stored timestamp changes.
6568
6572
  * 4. On fetch failure, return cached tools if available (stale-while-error)
6569
6573
  */
6570
6574
  declare function getServerTools(options: ServerToolsOptions): Promise<ServerTool[]>;
@@ -18764,15 +18764,17 @@ Build ONLY when the user gives an explicit instruction to build, create, generat
18764
18764
 
18765
18765
  Once the user HAS given an explicit build instruction, you are in App Builder mode: you produce polished, production-quality React apps that feel designed \u2014 not generic.
18766
18766
 
18767
- DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a logic, data, or behavior-only change, skip the brief and just make the change.
18767
+ DESIGN: on the initial build, before writing code, briefly state (2-3 sentences) what you want this app to feel like \u2014 name the specific fonts, the palette in hex, and one signature detail. Be concrete: "Fraunces display + Inter body + JetBrains Mono metadata, terracotta #b75432 accent on bone #f3efe6, paper-grain texture via inline SVG noise" is the kind of specificity that anchors the build. Default to nothing: don't pick "safe modern productivity" unless the brief literally asks for utilitarian. On later turns, state a design brief only when the change is visual (a restyle, new theme, or new UI); for a text, logic, data, or behavior-only change, skip the brief and just make the change.
18768
+
18769
+ EDIT SCOPE: Change only the files and lines required by the current user request. A title rename is a text edit, not a design change. Preserve styles, dependencies, and unrelated logic on text edits. Design feedback does not authorize unrelated edits.
18768
18770
 
18769
18771
  WORKFLOW:
18770
18772
  1. NEVER output code as text or markdown. ALWAYS use tools.
18771
18773
  2. Initial build: state your design brief, then create_file with a "files" array writing ALL files in one call. The preview renders automatically.
18772
18774
  3. patch_file requires read_file for that path earlier in the conversation (or create_file in the same conversation, which counts). read_file output is numbered "42: <text>" \u2014 the prefix is display-only; never copy it into "find". Each "find" must match exactly one location \u2014 include 2-3 lines of surrounding context. Pass multiple patches per call to change distinct locations.
18773
18775
  4. Prefer patch_file for changes to existing files \u2014 surgical, reviewable, preserves surrounding code. Reserve create_file overwrites for substantial restructuring. Inserts: find the line before, replace with that line + the new line. Deletes: empty replace.
18774
- 5. After substantial changes, call critique_design first (taste, hierarchy, distinctiveness, weakest decision) and then audit_design (mechanical: tokens, focus states, aria-labels, alt, heading order). Patch what each surfaces. critique catches taste issues no checklist would; audit catches mechanics you'd miss. Run both; act on both.
18775
- 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip \u2014 audit + critique are your feedback in that case.
18776
+ 5. On the initial build, when adding new UI, or after user-requested design changes, call critique_design first and then audit_design. Critique checks taste, hierarchy, and distinctiveness. Audit checks tokens, focus states, aria-labels, alt text, and heading order. Patch only issues within the current user request. For text, logic, or data edits, skip both design tools.
18777
+ 6. Before declaring done, call verify_app. The host's preview runtime reports whether your app actually mounted and surfaces any errors it captured \u2014 hallucinated imports, syntax the bundler rejected, undefined components, runtime crashes. If \`rendered\` is false or \`errors\` is non-empty, fix every error before the next message. If the response includes a \`note\` that verify_app isn't wired in this host, skip runtime verification. An unavailable runtime verifier does not authorize design changes. Use audit_design and critique_design only for the initial build, adding new UI, or user-requested design changes.
18776
18778
  7. Keep responses to a sentence or two. Exception: when responding to critique_design, write a substantive paragraph per rubric question.
18777
18779
 
18778
18780
  STRUCTURE:
@@ -18917,12 +18919,13 @@ function isCacheExpired(cache, expirationMs = DEFAULT_CACHE_EXPIRATION_MS) {
18917
18919
  if (!cache) return true;
18918
18920
  return Date.now() - cache.timestamp > expirationMs;
18919
18921
  }
18920
- function buildCacheEntry(tools, checksum) {
18922
+ function buildCacheEntry(tools, checksum, etag) {
18921
18923
  return {
18922
18924
  tools,
18923
18925
  timestamp: Date.now(),
18924
18926
  version: CACHE_VERSION,
18925
- ...checksum && { checksum }
18927
+ ...checksum && { checksum },
18928
+ ...etag && { etag }
18926
18929
  };
18927
18930
  }
18928
18931
  function writeLocalStorageCache(entry) {
@@ -18957,19 +18960,36 @@ function shouldRefreshTools(responseChecksum, cache = localStorageToolsCache) {
18957
18960
  const cachedChecksum = getToolsChecksum(cache);
18958
18961
  return cachedChecksum instanceof Promise ? cachedChecksum.then(decide) : decide(cachedChecksum);
18959
18962
  }
18960
- async function fetchServerToolsFromApi(baseUrl, token) {
18961
- const response = await fetch(`${baseUrl}/api/v1/tools`, {
18963
+ async function fetchServerToolsFromApi(baseUrl, authHeaders, etag) {
18964
+ const request = (validator) => fetch(`${baseUrl}/api/v1/tools`, {
18962
18965
  method: "GET",
18963
18966
  headers: {
18964
- Authorization: `Bearer ${token}`,
18965
- "Content-Type": "application/json"
18967
+ ...authHeaders,
18968
+ "Content-Type": "application/json",
18969
+ ...validator && { "If-None-Match": validator }
18966
18970
  }
18967
18971
  });
18972
+ let response;
18973
+ try {
18974
+ response = await request(etag);
18975
+ } catch (error) {
18976
+ if (!etag || !(error instanceof TypeError)) throw error;
18977
+ etag = void 0;
18978
+ response = await request();
18979
+ }
18980
+ if (etag && response.status === 304) {
18981
+ return { notModified: true };
18982
+ }
18968
18983
  if (!response.ok) {
18969
18984
  throw new Error(`Failed to fetch server tools: ${response.status}`);
18970
18985
  }
18971
18986
  const data = await response.json();
18972
- return convertServerToolsResponse(data);
18987
+ const responseEtag = response.headers?.get("ETag") ?? void 0;
18988
+ return {
18989
+ notModified: false,
18990
+ ...convertServerToolsResponse(data),
18991
+ ...responseEtag && { etag: responseEtag }
18992
+ };
18973
18993
  }
18974
18994
  async function getServerTools(options) {
18975
18995
  const {
@@ -19001,34 +19021,30 @@ async function getServerTools(options) {
19001
19021
  try {
19002
19022
  const { BASE_URL: BASE_URL2 } = await import("./clientConfig-VIMT6Q32.mjs");
19003
19023
  const effectiveBaseUrl = baseUrl ?? BASE_URL2;
19024
+ const validator = cached && !forceRefresh ? cached.etag : void 0;
19025
+ let authHeaders;
19004
19026
  if (apiKey) {
19005
- const response = await fetch(`${effectiveBaseUrl}/api/v1/tools`, {
19006
- method: "GET",
19007
- headers: {
19008
- "X-API-Key": apiKey,
19009
- "Content-Type": "application/json"
19010
- }
19011
- });
19012
- if (!response.ok) {
19013
- throw new Error(`Failed to fetch server tools: ${response.status}`);
19027
+ authHeaders = { "X-API-Key": apiKey };
19028
+ } else {
19029
+ if (!getToken) {
19030
+ getLogger().warn("[serverTools] No auth method available for fetching tools");
19031
+ return cached?.tools ?? [];
19014
19032
  }
19015
- const data = await response.json();
19016
- const { tools: tools2, checksum: checksum2 } = convertServerToolsResponse(data);
19017
- await persistCache(buildCacheEntry(tools2, checksum2));
19018
- return tools2;
19019
- }
19020
- if (!getToken) {
19021
- getLogger().warn("[serverTools] No auth method available for fetching tools");
19022
- return cached?.tools ?? [];
19033
+ const token = await getToken();
19034
+ if (!token) {
19035
+ getLogger().warn("[serverTools] No auth token available for fetching tools");
19036
+ return cached?.tools ?? [];
19037
+ }
19038
+ authHeaders = { Authorization: `Bearer ${token}` };
19023
19039
  }
19024
- const token = await getToken();
19025
- if (!token) {
19026
- getLogger().warn("[serverTools] No auth token available for fetching tools");
19027
- return cached?.tools ?? [];
19040
+ const result = await fetchServerToolsFromApi(effectiveBaseUrl, authHeaders, validator);
19041
+ if (result.notModified) {
19042
+ const confirmed = cached;
19043
+ await persistCache({ ...confirmed, timestamp: Date.now() });
19044
+ return confirmed.tools;
19028
19045
  }
19029
- const { tools, checksum } = await fetchServerToolsFromApi(effectiveBaseUrl, token);
19030
- await persistCache(buildCacheEntry(tools, checksum));
19031
- return tools;
19046
+ await persistCache(buildCacheEntry(result.tools, result.checksum, result.etag));
19047
+ return result.tools;
19032
19048
  } catch (error) {
19033
19049
  getLogger().error("[serverTools] Failed to fetch server tools:", error);
19034
19050
  if (cached?.tools) {