google-trends-for-agent 0.2.45 → 0.2.46

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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.46 — 2026-11-30
4
+
5
+ ### One-click dsh plugin upgrade & cloud Actor 429 UX polish
6
+ - Add a one-click **Upgrade now** action (`POST /api/gtfa.plugin-upgrade`) in the dsh update banner with automatic profile detection (`desktop` vs `web`/`tui`), using DeepSeek Harness's bundled `pnpm` runtime for the Electron-managed `desktop` profile and `dsh plugin --profile <name>` for CLI profiles, plus matching fallback commands (`src/version-check.ts`, `src/dsh-version.ts`, `src/dsh-routes.ts`, `src/client/update-banner.tsx`).
7
+ - Downgrade Dashboard display from red **Blocked** to **Partial** with a calm hint whenever primary trend chart data already loaded and only secondary related queries or companion windows hit HTTP 429 (`src/client/dashboard.tsx`, `src/client/dashboard-locale.ts`).
8
+ - Replace local-only `HTTPS_PROXY/HTTP_PROXY` hints on cloud Actor 429/challenge errors with accurate Apify Actor guidance, and raise the Actor's proxy-rotation retry budget from `2` to `4` (`src/actor-on-demand.ts`, `src/actor.ts`, `src/core.ts`, `src/trending.ts`, `src/client.ts`).
9
+
3
10
  ## 0.2.45 — 2026-11-30
4
11
 
5
12
  ### npm package metadata & migration guide links
@@ -45,6 +45,8 @@ export declare class OnDemandActorClient {
45
45
  runId: string;
46
46
  }>;
47
47
  }
48
+ /** Replace local-CLI proxy hints in Actor-originated 429/challenge errors with cloud Actor guidance. */
49
+ export declare function rewriteActorErrorMessage(result: Record<string, unknown>): Record<string, unknown>;
48
50
  /** Local result reuse avoids starting an Actor at all on a snapshot cache hit. */
49
51
  export declare function callActorTool(client: OnDemandActorClient, options: {
50
52
  token: string;
@@ -188,6 +188,27 @@ export class OnDemandActorClient {
188
188
  }
189
189
  }
190
190
  }
191
+ /** Replace local-CLI proxy hints in Actor-originated 429/challenge errors with cloud Actor guidance. */
192
+ export function rewriteActorErrorMessage(result) {
193
+ const err = row(result.error);
194
+ if (typeof err.code !== 'string' || typeof err.message !== 'string')
195
+ return result;
196
+ if (!/HTTPS_PROXY|HTTP_PROXY/i.test(err.message))
197
+ return result;
198
+ let nextMessage = null;
199
+ if (err.code === 'RATE_LIMITED') {
200
+ nextMessage = 'Google Trends rate limit (HTTP 429) on the Apify Actor. Proxies were rotated, but Google still rate-limited this run—wait a few seconds and retry.';
201
+ }
202
+ else if (err.code === 'BLOCKED') {
203
+ nextMessage = 'Google Trends returned a challenge (CAPTCHA/unusual traffic) on the Apify Actor. Wait a moment and retry.';
204
+ }
205
+ else if (err.code === 'TRENDS_TIMEOUT') {
206
+ nextMessage = 'Google Trends timed out on the Apify Actor. Wait a moment and retry.';
207
+ }
208
+ if (!nextMessage)
209
+ return result;
210
+ return { ...result, error: { ...err, message: nextMessage } };
211
+ }
191
212
  /** Local result reuse avoids starting an Actor at all on a snapshot cache hit. */
192
213
  export async function callActorTool(client, options) {
193
214
  throwIfAborted(options.signal);
@@ -233,8 +254,8 @@ export async function callActorTool(client, options) {
233
254
  settings: cloudSettings, history: history.slice(0, 12),
234
255
  }, options.signal, options.progress, options.started, options.onRunFinished);
235
256
  throwIfAborted(options.signal);
236
- result = { ...output.result, meta: { ...row(output.result.meta), actorRunId: output.runId, execution: 'on-demand', actorRuntime: output.runtime,
237
- ...(output.usageUsd !== undefined ? { actorUsageUsd: output.usageUsd } : {}) } };
257
+ result = rewriteActorErrorMessage({ ...output.result, meta: { ...row(output.result.meta), actorRunId: output.runId, execution: 'on-demand', actorRuntime: output.runtime,
258
+ ...(output.usageUsd !== undefined ? { actorUsageUsd: output.usageUsd } : {}) } });
238
259
  const runtimeWarning = describeActorRuntimeDrift(output.runtime, VERSION, BASELINE_CATALOG_REVISION, options.egress).warning;
239
260
  if (runtimeWarning)
240
261
  result.warnings = [...(Array.isArray(result.warnings) ? result.warnings : []), runtimeWarning];
package/dist/actor.js CHANGED
@@ -58,7 +58,7 @@ try {
58
58
  const snapshotDir = process.env.GTFA_SNAPSHOT_DIR || '/tmp/gtfa/snapshots';
59
59
  const chartDir = process.env.GTFA_CHART_DIR || '/tmp/gtfa/charts';
60
60
  const relayTransport = proxyTransport ?? createDefaultTransport();
61
- const retryOptions = proxyTransport ? { defaultMaxRetries: 2 } : {};
61
+ const retryOptions = proxyTransport ? { defaultMaxRetries: 4 } : {};
62
62
  const tools = createTools({
63
63
  transport: relayTransport,
64
64
  defaultGeo: geo,
package/dist/client.d.ts CHANGED
@@ -21,7 +21,7 @@ export interface ClientOptions extends RateLimitOptions {
21
21
  limiter?: RateLimiter;
22
22
  signal?: AbortSignal;
23
23
  timeoutSurface?: TimeoutSurface;
24
- defaultMaxRetries?: 0 | 1 | 2;
24
+ defaultMaxRetries?: 0 | 1 | 2 | 3 | 4;
25
25
  }
26
26
  export declare class TrendsClient {
27
27
  private readonly transport;
package/dist/core.js CHANGED
@@ -160,8 +160,8 @@ export function parseGTrendsInput(raw, now = new Date()) {
160
160
  if (raw.timeoutMs !== undefined && (!Number.isSafeInteger(raw.timeoutMs) || raw.timeoutMs < 1000 || raw.timeoutMs > 60000))
161
161
  throw bad('timeoutMs must be an integer between 1000 and 60000');
162
162
  const maxRetries = raw.maxRetries ?? 1;
163
- if (!Number.isSafeInteger(maxRetries) || maxRetries < 0 || maxRetries > 2)
164
- throw bad('maxRetries must be an integer between 0 and 2');
163
+ if (!Number.isSafeInteger(maxRetries) || maxRetries < 0 || maxRetries > 4)
164
+ throw bad('maxRetries must be an integer between 0 and 4');
165
165
  return { ...(raw.timeoutMs !== undefined ? { timeoutMs: raw.timeoutMs } : {}), maxRetries, queries, geo, timeRange, startDate, endDate, category, searchType, locale, timezoneOffsetMinutes, dataTypes };
166
166
  }
167
167
  export function publicInput(input) {
@@ -2166,6 +2166,14 @@ function parseActorRuntime(value) {
2166
2166
  // src/version-check.ts
2167
2167
  var GTFA_RELEASES_URL = `${GTFA_SOURCE_URL}/releases`;
2168
2168
  var GTFA_UPGRADE_COMMAND = "dsh plugin --profile web add google-trends-for-agent@latest";
2169
+ var SAFE_PROFILE_RE = /^[a-zA-Z0-9._-]{1,64}$/;
2170
+ function formatUpgradeCommand(profileName) {
2171
+ const clean = typeof profileName === "string" && SAFE_PROFILE_RE.test(profileName.trim()) ? profileName.trim() : "web";
2172
+ if (clean === "desktop") {
2173
+ return "pnpm --dir ~/.dsh/profiles/desktop add google-trends-for-agent@latest";
2174
+ }
2175
+ return `dsh plugin --profile ${clean} add google-trends-for-agent@latest`;
2176
+ }
2169
2177
  var SEMVER_RE = /^v?(\d{1,5})\.(\d{1,5})\.(\d{1,5})(?:-([a-zA-Z0-9.-]{1,40}))?$/;
2170
2178
  function parseSemver(raw) {
2171
2179
  if (typeof raw !== "string") return null;
@@ -2232,6 +2240,8 @@ function parseVersionStatus(value) {
2232
2240
  }
2233
2241
  }
2234
2242
  const checkError = row2.checkError === "network" || row2.checkError === "rate-limited" || row2.checkError === "http" ? row2.checkError : null;
2243
+ const profileName = typeof row2.profileName === "string" && SAFE_PROFILE_RE.test(row2.profileName.trim()) ? row2.profileName.trim() : null;
2244
+ const upgradeCommand = typeof row2.upgradeCommand === "string" && (row2.upgradeCommand.trim().startsWith("dsh plugin ") || row2.upgradeCommand.trim().startsWith("pnpm ")) ? row2.upgradeCommand.trim() : profileName ? formatUpgradeCommand(profileName) : null;
2235
2245
  return {
2236
2246
  pluginVersion: row2.pluginVersion,
2237
2247
  baselineCatalogRevision: row2.baselineCatalogRevision,
@@ -2242,14 +2252,17 @@ function parseVersionStatus(value) {
2242
2252
  observedActor,
2243
2253
  actorUpdateAvailable: row2.actorUpdateAvailable === true,
2244
2254
  checkedAt: typeof row2.checkedAt === "string" && Number.isFinite(Date.parse(row2.checkedAt)) ? row2.checkedAt : null,
2245
- checkError
2255
+ checkError,
2256
+ ...profileName ? { profileName } : {},
2257
+ ...upgradeCommand ? { upgradeCommand } : {}
2246
2258
  };
2247
2259
  }
2248
2260
 
2249
2261
  // src/client/update-banner.tsx
2250
2262
  var import_jsx_runtime5 = require("react/jsx-runtime");
2251
- var CLIENT_VERSION = "0.2.45" ? "0.2.45" : null;
2263
+ var CLIENT_VERSION = "0.2.46" ? "0.2.46" : null;
2252
2264
  var VERSION_URL = "api/gtfa.version";
2265
+ var PLUGIN_UPGRADE_URL = "api/gtfa.plugin-upgrade";
2253
2266
  var DISMISS_STORAGE_KEY = "gtfa.update.dismissed.1";
2254
2267
  function template2(text2, values) {
2255
2268
  return text2.replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? ""));
@@ -2269,6 +2282,44 @@ async function loadVersionStatus(refresh = false, signal) {
2269
2282
  return null;
2270
2283
  }
2271
2284
  }
2285
+ async function triggerPluginUpgrade(signal) {
2286
+ try {
2287
+ const response = await fetch(PLUGIN_UPGRADE_URL, {
2288
+ method: "POST",
2289
+ cache: "no-store",
2290
+ headers: { accept: "application/json" },
2291
+ signal
2292
+ });
2293
+ const raw = await response.json().catch(() => null);
2294
+ if (raw && typeof raw.ok === "boolean") {
2295
+ return {
2296
+ ok: raw.ok,
2297
+ profileName: typeof raw.profileName === "string" ? raw.profileName : "web",
2298
+ command: typeof raw.command === "string" ? raw.command : GTFA_UPGRADE_COMMAND,
2299
+ installedVersion: typeof raw.installedVersion === "string" ? raw.installedVersion : null,
2300
+ restartRequired: raw.restartRequired === true,
2301
+ ...typeof raw.message === "string" && raw.message ? { message: raw.message } : {}
2302
+ };
2303
+ }
2304
+ return {
2305
+ ok: false,
2306
+ profileName: "web",
2307
+ command: GTFA_UPGRADE_COMMAND,
2308
+ installedVersion: null,
2309
+ restartRequired: false,
2310
+ message: `HTTP ${response.status}`
2311
+ };
2312
+ } catch (error) {
2313
+ return {
2314
+ ok: false,
2315
+ profileName: "web",
2316
+ command: GTFA_UPGRADE_COMMAND,
2317
+ installedVersion: null,
2318
+ restartRequired: false,
2319
+ message: error instanceof Error ? error.message : "Network error"
2320
+ };
2321
+ }
2322
+ }
2272
2323
  async function acknowledgeActorRebuilt(actorId, signal) {
2273
2324
  try {
2274
2325
  const response = await fetch(VERSION_URL, {
@@ -2352,6 +2403,10 @@ function UpdateBanner({
2352
2403
  }) {
2353
2404
  const [drawerOpen, setDrawerOpen] = (0, import_react4.useState)(false);
2354
2405
  const [copied, setCopied] = (0, import_react4.useState)(false);
2406
+ const [upgradingPlugin, setUpgradingPlugin] = (0, import_react4.useState)(false);
2407
+ const [upgradeDoneVersion, setUpgradeDoneVersion] = (0, import_react4.useState)(null);
2408
+ const [upgradeError, setUpgradeError] = (0, import_react4.useState)(null);
2409
+ const [resolvedCommand, setResolvedCommand] = (0, import_react4.useState)(null);
2355
2410
  (0, import_react4.useEffect)(() => {
2356
2411
  if (!copied) return;
2357
2412
  const timer = setTimeout(() => setCopied(false), 1800);
@@ -2361,23 +2416,39 @@ function UpdateBanner({
2361
2416
  const mode = resolveUpdateMode(status, clientVersion, egressOverride, actorIdOverride);
2362
2417
  const { targetPluginVersion } = effectiveUpdateFlags(status, egressOverride, actorIdOverride);
2363
2418
  if (surface === "dashboard") {
2364
- if (mode === "up-to-date") return null;
2365
- if (dismissed && mode !== "restart-needed") return null;
2419
+ if (mode === "up-to-date" && !upgradeDoneVersion) return null;
2420
+ if (dismissed && mode !== "restart-needed" && !upgradeDoneVersion) return null;
2366
2421
  }
2367
2422
  const releaseUrl = status.latestRelease?.url ?? GTFA_RELEASES_URL;
2368
2423
  const nextVersion = targetPluginVersion ?? status.latestRelease?.version ?? "";
2369
2424
  const actorVer = status.observedActor?.version ?? "";
2425
+ const upgradeCommand = resolvedCommand ?? status.upgradeCommand ?? GTFA_UPGRADE_COMMAND;
2370
2426
  const checkedLabel = status.checkedAt ? new Date(status.checkedAt).toLocaleString(locale, { month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" }) : null;
2371
2427
  const copyCommand = async () => {
2372
2428
  try {
2373
2429
  if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
2374
- await navigator.clipboard.writeText(GTFA_UPGRADE_COMMAND);
2430
+ await navigator.clipboard.writeText(upgradeCommand);
2375
2431
  }
2376
2432
  setCopied(true);
2377
2433
  } catch {
2378
2434
  setCopied(false);
2379
2435
  }
2380
2436
  };
2437
+ const runOneClickUpgrade = async () => {
2438
+ if (upgradingPlugin) return;
2439
+ setUpgradingPlugin(true);
2440
+ setUpgradeError(null);
2441
+ const result = await triggerPluginUpgrade();
2442
+ setUpgradingPlugin(false);
2443
+ if (result.command) setResolvedCommand(result.command);
2444
+ if (result.ok) {
2445
+ setUpgradeDoneVersion(result.installedVersion ?? (nextVersion || "latest"));
2446
+ setDrawerOpen(false);
2447
+ } else {
2448
+ setUpgradeError(result.message || t("updateFailedFallback"));
2449
+ setDrawerOpen(true);
2450
+ }
2451
+ };
2381
2452
  const pendingPublicSwitch = surface === "settings" && status.egress === "actor-own" && egressOverride === "actor-public";
2382
2453
  if (mode === "up-to-date") {
2383
2454
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("aside", { className: "gtfa-update-banner neutral", "aria-label": t("updateUpToDateTitle"), children: [
@@ -2405,6 +2476,23 @@ function UpdateBanner({
2405
2476
  status.checkError ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "gtfa-update-feedback", role: "status", children: t(status.checkError === "rate-limited" ? "updateCheckRateLimited" : "updateCheckFailed") }) : null
2406
2477
  ] });
2407
2478
  }
2479
+ if (upgradeDoneVersion) {
2480
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("aside", { className: "gtfa-update-banner warn", role: "status", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "gtfa-update-row", children: [
2481
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "gtfa-update-icon", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Icon, { name: "check", size: 14 }) }),
2482
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "gtfa-update-copy", children: [
2483
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "gtfa-update-title", children: [
2484
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { children: t("updateDoneTitle") }),
2485
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("span", { className: "gtfa-ver-pill ok", children: [
2486
+ "v",
2487
+ status.pluginVersion,
2488
+ " \u2192 v",
2489
+ upgradeDoneVersion
2490
+ ] })
2491
+ ] }),
2492
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "gtfa-update-sub", children: template2(t("updateDoneSub"), { version: upgradeDoneVersion }) })
2493
+ ] })
2494
+ ] }) });
2495
+ }
2408
2496
  if (mode === "restart-needed") {
2409
2497
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("aside", { className: "gtfa-update-banner warn", role: "status", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "gtfa-update-row", children: [
2410
2498
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "gtfa-update-icon", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Icon, { name: "alert", size: 14 }) }),
@@ -2486,11 +2574,26 @@ function UpdateBanner({
2486
2574
  /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "gtfa-update-sub", children: isBoth ? template2(t("updateBothSub"), { next: nextVersion || status.pluginVersion }) : highlights[0] ?? t("updatePluginSubFallback") })
2487
2575
  ] }),
2488
2576
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "gtfa-update-actions", children: [
2489
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2577
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
2490
2578
  "button",
2491
2579
  {
2492
2580
  type: "button",
2493
2581
  className: "gtfa-update-btn primary",
2582
+ disabled: upgradingPlugin,
2583
+ onClick: () => {
2584
+ void runOneClickUpgrade();
2585
+ },
2586
+ children: [
2587
+ upgradingPlugin ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("span", { className: "gtfa-spin", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Icon, { name: "refresh", size: 12 }) }) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(Icon, { name: "upload", size: 12 }),
2588
+ t(upgradingPlugin ? "updateUpgrading" : "updateNow")
2589
+ ]
2590
+ }
2591
+ ),
2592
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
2593
+ "button",
2594
+ {
2595
+ type: "button",
2596
+ className: "gtfa-update-btn",
2494
2597
  "aria-expanded": drawerOpen,
2495
2598
  onClick: () => setDrawerOpen((open) => !open),
2496
2599
  children: t(drawerOpen ? "updateHideSteps" : "updateShowSteps")
@@ -2526,9 +2629,10 @@ function UpdateBanner({
2526
2629
  ] })
2527
2630
  ] }),
2528
2631
  drawerOpen ? /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "gtfa-update-drawer", children: [
2632
+ upgradeError ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("p", { className: "gtfa-update-feedback", role: "alert", children: upgradeError }) : null,
2529
2633
  highlights.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("ul", { className: "gtfa-update-highlights", children: highlights.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("li", { children: line }, index)) }) : null,
2530
2634
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { className: "gtfa-update-cmd", children: [
2531
- /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("code", { children: GTFA_UPGRADE_COMMAND }),
2635
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)("code", { children: upgradeCommand }),
2532
2636
  /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("button", { type: "button", className: `gtfa-update-btn${copied ? " primary" : ""}`, onClick: () => {
2533
2637
  void copyCommand();
2534
2638
  }, children: [
@@ -3752,6 +3856,8 @@ function Result({ saved, actorRuns, metric, setMetric, t, egress, estimate, busy
3752
3856
  errorMessage && !isLocalFailure && !isActorConfigError ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "gd-error", role: "alert", children: errorMessage }) : null
3753
3857
  ] });
3754
3858
  const showLegend = !failedEmpty && (legend.length > 1 || legend.some((row2) => !hasChartPoints(row2) || row2.range?.points.length));
3859
+ const partialRateLimited = record2.status === "blocked" && !failedEmpty;
3860
+ const displayRecord = partialRateLimited ? { ...record2, status: "partial" } : record2;
3755
3861
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "gd-results", children: [
3756
3862
  actionBanner,
3757
3863
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "gd-result-grid", children: [
@@ -3760,7 +3866,7 @@ function Result({ saved, actorRuns, metric, setMetric, t, egress, estimate, busy
3760
3866
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "gd-result-title-block", children: [
3761
3867
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "gd-result-title-row", children: [
3762
3868
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("h2", { children: record2.terms.join(" vs ") }),
3763
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Badge, { record: record2, t })
3869
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(Badge, { record: displayRecord, t })
3764
3870
  ] }),
3765
3871
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "gd-result-meta", children: [
3766
3872
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { children: t(currentMetric === "traffic" ? "dashMetricVolume" : "dashMetricIndex") }),
@@ -3883,7 +3989,7 @@ function Result({ saved, actorRuns, metric, setMetric, t, egress, estimate, busy
3883
3989
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(VolumeCards, { saved, t, busy, egress, estimate }),
3884
3990
  !result.ok && errorCode ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "gd-status-box", children: [
3885
3991
  /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { children: t("dashQueryStatus") }),
3886
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "gd-badge blocked", children: errorCode })
3992
+ /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: `gd-badge ${partialRateLimited ? "partial" : "blocked"}`, children: partialRateLimited ? t("dashPartial") : errorCode })
3887
3993
  ] }) : null,
3888
3994
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("details", { className: "gd-query-details", open: !result.ok, children: [
3889
3995
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("summary", { children: [
@@ -3936,7 +4042,7 @@ function Result({ saved, actorRuns, metric, setMetric, t, egress, estimate, busy
3936
4042
  ] }) : null
3937
4043
  ] })
3938
4044
  ] }),
3939
- errorMessage && !isLocalFailure && !isActorConfigError ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "gd-error", role: "alert", children: errorMessage }) : null,
4045
+ partialRateLimited ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "gd-chart-note", role: "status", children: t("dashPartialRateLimitedHint") }) : errorMessage && !isLocalFailure && !isActorConfigError ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { className: "gd-error", role: "alert", children: errorMessage }) : null,
3940
4046
  warnings.length ? /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("details", { className: "gd-warnings", children: [
3941
4047
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("summary", { children: [
3942
4048
  t("dashResultInfo"),
@@ -4108,6 +4214,7 @@ var DASHBOARD_EN = {
4108
4214
  dashError: "Failed",
4109
4215
  dashNoData: "No data",
4110
4216
  dashPartial: "Partial",
4217
+ dashPartialRateLimitedHint: "Primary trend data loaded. Secondary related queries or companion window hit Google rate limits (HTTP 429) \u2014 retry in a moment if you need them.",
4111
4218
  dashClearSelected: "Clear selected",
4112
4219
  dashClearAll: "Clear all",
4113
4220
  dashClear: "Clear",
@@ -4350,6 +4457,7 @@ var DASHBOARD_ZH = {
4350
4457
  dashError: "\u5931\u8D25",
4351
4458
  dashNoData: "\u65E0\u6570\u636E",
4352
4459
  dashPartial: "\u90E8\u5206\u6210\u529F",
4460
+ dashPartialRateLimitedHint: "\u4E3B\u8D8B\u52BF\u6570\u636E\u5DF2\u83B7\u53D6\uFF0C\u9644\u5E26\u7684\u76F8\u5173\u8BCD\u6216\u8F85\u52A9\u7A97\u53E3\u89E6\u53D1\u4E86 Google \u9650\u6D41\uFF08HTTP 429\uFF09\uFF0C\u5982\u9700\u8865\u5168\u53EF\u7A0D\u540E\u91CD\u8BD5\u3002",
4353
4461
  dashClearSelected: "\u6E05\u7406\u6240\u9009",
4354
4462
  dashClearAll: "\u6E05\u7A7A\u5168\u90E8",
4355
4463
  dashClear: "\u6E05\u7406",
@@ -4514,6 +4622,11 @@ var EN = {
4514
4622
  updateBothSub: "Upgrade the plugin to v{next}, and rebuild your personal Actor (or switch to the Public Actor).",
4515
4623
  updateRestartTitle: "Restart dsh to finish upgrading",
4516
4624
  updateRestartSub: "Frontend loaded v{frontend} while the dsh backend is still running v{backend}. Fully quit and reopen dsh.",
4625
+ updateNow: "Upgrade now",
4626
+ updateUpgrading: "Upgrading\u2026",
4627
+ updateDoneTitle: "Upgrade installed \u2014 restart dsh",
4628
+ updateDoneSub: "Installed v{version} into this profile. Fully quit and reopen dsh to load the new version.",
4629
+ updateFailedFallback: "Automatic upgrade failed. Run the command below in your terminal instead.",
4517
4630
  updateShowSteps: "Upgrade steps",
4518
4631
  updateHideSteps: "Hide steps",
4519
4632
  updateCopyCmd: "Copy command",
@@ -4855,6 +4968,11 @@ var ZH = {
4855
4968
  updateBothSub: "\u5EFA\u8BAE\u5148\u5347\u7EA7\u63D2\u4EF6\u81F3 v{next}\uFF0C\u5E76\u66F4\u65B0\u4E2A\u4EBA Actor\uFF08\u6216\u6539\u7528\u514D\u7EF4\u62A4\u7684\u516C\u5171 Actor\uFF09\u3002",
4856
4969
  updateRestartTitle: "\u68C0\u6D4B\u5230\u65B0\u7248\u672C\u5DF2\u5B89\u88C5\uFF0C\u9700\u8981\u91CD\u542F dsh",
4857
4970
  updateRestartSub: "\u524D\u7AEF\u5DF2\u52A0\u8F7D v{frontend}\uFF0C\u4F46 dsh \u540E\u7AEF\u4ECD\u5728\u8FD0\u884C v{backend}\u3002\u8BF7\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u65B0\u6253\u5F00 dsh\u3002",
4971
+ updateNow: "\u7ACB\u5373\u5347\u7EA7",
4972
+ updateUpgrading: "\u6B63\u5728\u5347\u7EA7\u2026",
4973
+ updateDoneTitle: "\u5DF2\u5B89\u88C5\u65B0\u7248\u672C\uFF0C\u8BF7\u91CD\u542F dsh",
4974
+ updateDoneSub: "\u5DF2\u5C06 v{version} \u5B89\u88C5\u5230\u5F53\u524D profile\u3002\u8BF7\u5B8C\u5168\u9000\u51FA\u5E76\u91CD\u65B0\u6253\u5F00\u684C\u9762\u7AEF / dsh \u4EE5\u751F\u6548\u3002",
4975
+ updateFailedFallback: "\u81EA\u52A8\u5347\u7EA7\u672A\u6210\u529F\uFF0C\u8BF7\u590D\u5236\u4E0B\u65B9\u547D\u4EE4\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002",
4858
4976
  updateShowSteps: "\u5347\u7EA7\u6B65\u9AA4",
4859
4977
  updateHideSteps: "\u6536\u8D77\u6B65\u9AA4",
4860
4978
  updateCopyCmd: "\u590D\u5236\u547D\u4EE4",
@@ -6,7 +6,7 @@ import { type EgressMode } from './options.js';
6
6
  import { type DashboardBoundary } from './dashboard-routes.js';
7
7
  import type { MekaBaselineBoundary } from './dsh-baselines-sync.js';
8
8
  import type { VersionStatusBoundary } from './dsh-version.js';
9
- import { VERSION_STATUS_PATH } from './version-check.js';
9
+ import { PLUGIN_UPGRADE_PATH, VERSION_STATUS_PATH } from './version-check.js';
10
10
  import { type ConnectionCode, type ConnectionDiagnostics, type ConnectionResult } from './connection-check.js';
11
11
  export declare const APIFY_USAGE_PATH = "/api/gtfa.apify-usage";
12
12
  export declare const APIFY_ACTORS_PATH = "/api/gtfa.apify-actors";
@@ -15,7 +15,7 @@ export declare const APIFY_UPDATE_PATH = "/api/gtfa.apify-update";
15
15
  export declare const TEST_CONNECTION_PATH = "/api/gtfa.test-connection";
16
16
  export declare const BASELINES_STATUS_PATH = "/api/gtfa.baselines";
17
17
  export declare const BASELINES_SYNC_PATH = "/api/gtfa.baselines-sync";
18
- export { VERSION_STATUS_PATH };
18
+ export { PLUGIN_UPGRADE_PATH, VERSION_STATUS_PATH };
19
19
  export interface RouteSettings {
20
20
  egress: EgressMode;
21
21
  apifyToken?: string;
@@ -8,7 +8,7 @@ import { GTrendsError } from './core.js';
8
8
  import { VERSION } from './version.js';
9
9
  import { createTools } from './tools.js';
10
10
  import { dashboardRoute } from './dashboard-routes.js';
11
- import { VERSION_STATUS_PATH } from './version-check.js';
11
+ import { PLUGIN_UPGRADE_PATH, VERSION_STATUS_PATH } from './version-check.js';
12
12
  import { CONNECTION_FILTER, CONNECTION_KEYWORDS, CONNECTION_PROBE_PROTOCOL, connectionErrorCode, emptyDataCheck, summarizeConnectionProbe, } from './connection-check.js';
13
13
  export const APIFY_USAGE_PATH = '/api/gtfa.apify-usage';
14
14
  export const APIFY_ACTORS_PATH = '/api/gtfa.apify-actors';
@@ -17,7 +17,7 @@ export const APIFY_UPDATE_PATH = '/api/gtfa.apify-update';
17
17
  export const TEST_CONNECTION_PATH = '/api/gtfa.test-connection';
18
18
  export const BASELINES_STATUS_PATH = '/api/gtfa.baselines';
19
19
  export const BASELINES_SYNC_PATH = '/api/gtfa.baselines-sync';
20
- export { VERSION_STATUS_PATH };
20
+ export { PLUGIN_UPGRADE_PATH, VERSION_STATUS_PATH };
21
21
  const TRENDS_URL = 'https://trends.google.com/trends/';
22
22
  const DEFAULT_TIMEOUT_MS = 10_000;
23
23
  /** Remove proxy credentials and any accidental token text from an error message. */
@@ -557,6 +557,34 @@ function attachRoutes(connection, getSettings, overrides) {
557
557
  }
558
558
  },
559
559
  }));
560
+ if (typeof overrides.versionStatus.upgradePlugin === 'function') {
561
+ disposers.push(service.fetch.register({
562
+ path: PLUGIN_UPGRADE_PATH,
563
+ methods: ['POST'],
564
+ requestBody: 'buffered',
565
+ fetch: async (request) => {
566
+ if (request.method !== 'POST')
567
+ return json({ error: 'method not allowed' }, 405);
568
+ const rejected = rejectCrossSite(request);
569
+ if (rejected)
570
+ return rejected;
571
+ try {
572
+ const result = await overrides.versionStatus.upgradePlugin(request.signal);
573
+ return json(result, result.ok ? 200 : 500);
574
+ }
575
+ catch {
576
+ return json({
577
+ ok: false,
578
+ profileName: 'web',
579
+ command: 'dsh plugin --profile web add google-trends-for-agent@latest',
580
+ installedVersion: null,
581
+ restartRequired: false,
582
+ message: 'Could not complete the plugin upgrade.',
583
+ }, 500);
584
+ }
585
+ },
586
+ }));
587
+ }
560
588
  }
561
589
  if (overrides.oauth) {
562
590
  disposers.push(service.fetch.register({
@@ -1,6 +1,11 @@
1
1
  import { type ActorRuntime } from './actor-runtime.js';
2
2
  import { type EgressMode } from './options.js';
3
- import { type VersionStatusSnapshot } from './version-check.js';
3
+ import { type PluginUpgradeResult, type VersionStatusSnapshot } from './version-check.js';
4
+ /** Detect the active dsh profile name (e.g. desktop, web, tui) from env or runtime paths. */
5
+ export declare function detectDshProfileName(options?: {
6
+ env?: NodeJS.ProcessEnv;
7
+ paths?: (string | null | undefined)[];
8
+ }): string;
4
9
  export interface VersionStatusQuery {
5
10
  egress: EgressMode;
6
11
  apifyActor?: string;
@@ -12,6 +17,7 @@ export interface VersionStatusBoundary {
12
17
  recordActorRuntime(actorId: string, runtime: ActorRuntime | null | undefined): Promise<void>;
13
18
  markActorRebuilt(actorId: string): Promise<void>;
14
19
  clearActorRuntime(actorId: string): Promise<void>;
20
+ upgradePlugin?: (signal?: AbortSignal) => Promise<PluginUpgradeResult>;
15
21
  }
16
22
  export interface VersionStatusMonitorOptions {
17
23
  getSnapshotDir: () => string;
@@ -21,6 +27,12 @@ export interface VersionStatusMonitorOptions {
21
27
  pluginVersion?: string;
22
28
  baselineCatalogRevision?: string;
23
29
  releaseApiUrl?: string;
30
+ profileName?: string;
31
+ runUpgrade?: (profileName: string, signal?: AbortSignal) => Promise<{
32
+ ok: boolean;
33
+ installedVersion?: string | null;
34
+ message?: string;
35
+ }>;
24
36
  }
25
37
  /** Extract up to 3 concise highlights from a GitHub Release body. */
26
38
  export declare function extractReleaseHighlights(body: unknown, fallbackName?: unknown): string[];
@@ -1,12 +1,83 @@
1
+ import { execFile } from 'node:child_process';
1
2
  import { randomUUID } from 'node:crypto';
2
- import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
- import { dirname, resolve } from 'node:path';
3
+ import { access, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { promisify } from 'node:util';
4
8
  import { parseActorRuntime } from './actor-runtime.js';
5
9
  import { BASELINE_CATALOG_REVISION } from './baseline-catalog.js';
6
10
  import { GTFA_PUBLIC_ACTOR_ID } from './options.js';
7
11
  import { QueryHistoryStore } from './query-history.js';
8
12
  import { VERSION } from './version.js';
9
- import { GTFA_LATEST_RELEASE_API_URL, GTFA_RELEASES_URL, compareSemver, isSafeReleaseUrl, parseSemver, } from './version-check.js';
13
+ import { GTFA_LATEST_RELEASE_API_URL, GTFA_RELEASES_URL, compareSemver, formatUpgradeCommand, isSafeReleaseUrl, parseSemver, } from './version-check.js';
14
+ const execFileAsync = promisify(execFile);
15
+ const SAFE_PROFILE_RE = /^[a-zA-Z0-9._-]{1,64}$/;
16
+ const PROFILE_PATH_RE = /(?:^|[/\\])profiles[/\\]([a-zA-Z0-9._-]{1,64})(?:[/\\]|$)/;
17
+ /** Detect the active dsh profile name (e.g. desktop, web, tui) from env or runtime paths. */
18
+ export function detectDshProfileName(options = {}) {
19
+ const env = options.env ?? process.env;
20
+ const fromEnv = typeof env.DSH_PROFILE === 'string' ? env.DSH_PROFILE.trim() : '';
21
+ if (fromEnv && SAFE_PROFILE_RE.test(fromEnv))
22
+ return fromEnv;
23
+ const candidates = options.paths ?? [
24
+ (() => { try {
25
+ return dirname(fileURLToPath(import.meta.url));
26
+ }
27
+ catch {
28
+ return '';
29
+ } })(),
30
+ process.cwd(),
31
+ ];
32
+ for (const raw of candidates) {
33
+ if (!raw)
34
+ continue;
35
+ const match = PROFILE_PATH_RE.exec(raw);
36
+ if (match?.[1] && SAFE_PROFILE_RE.test(match[1]))
37
+ return match[1];
38
+ }
39
+ return 'web';
40
+ }
41
+ async function resolveCliBinary(name, envKey, env) {
42
+ const explicit = typeof env[envKey] === 'string' ? env[envKey].trim() : '';
43
+ if (explicit)
44
+ return explicit;
45
+ const home = env.HOME?.trim() || homedir();
46
+ const candidates = [
47
+ join(home, '.local', 'bin', name),
48
+ `/opt/homebrew/bin/${name}`,
49
+ `/usr/local/bin/${name}`,
50
+ ];
51
+ for (const candidate of candidates) {
52
+ try {
53
+ await access(candidate);
54
+ return candidate;
55
+ }
56
+ catch { /* Try next candidate. */ }
57
+ }
58
+ return name;
59
+ }
60
+ function buildAugmentedPath(env) {
61
+ const home = env.HOME?.trim() || homedir();
62
+ const extras = [join(home, '.local', 'bin'), '/opt/homebrew/bin', '/usr/local/bin'];
63
+ const current = (env.PATH ?? '').split(':').filter(Boolean);
64
+ for (const dir of extras) {
65
+ if (!current.includes(dir))
66
+ current.push(dir);
67
+ }
68
+ return current.join(':');
69
+ }
70
+ async function readInstalledProfileVersion(profileName, env) {
71
+ const dshHome = env.DSH_HOME?.trim() || join(env.HOME?.trim() || homedir(), '.dsh');
72
+ const pkgPath = join(dshHome, 'profiles', profileName, 'node_modules', 'google-trends-for-agent', 'package.json');
73
+ try {
74
+ const raw = JSON.parse(await readFile(pkgPath, 'utf8'));
75
+ return typeof raw.version === 'string' && parseSemver(raw.version) ? raw.version : null;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
10
81
  const CACHE_FILE = '.version-status.json';
11
82
  const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
12
83
  const FETCH_TIMEOUT_MS = 8_000;
@@ -246,6 +317,18 @@ export function createVersionStatusMonitor(options) {
246
317
  && observedActor
247
318
  && ((compareSemver(observedActor.version, pluginVersion) ?? 0) < 0
248
319
  || observedActor.baselineCatalogRevision < baselineCatalogRevision));
320
+ const profileName = options.profileName?.trim() || detectDshProfileName({
321
+ paths: [
322
+ (() => { try {
323
+ return dirname(fileURLToPath(import.meta.url));
324
+ }
325
+ catch {
326
+ return '';
327
+ } })(),
328
+ options.getSnapshotDir(),
329
+ process.cwd(),
330
+ ],
331
+ });
249
332
  return {
250
333
  pluginVersion,
251
334
  baselineCatalogRevision,
@@ -257,6 +340,8 @@ export function createVersionStatusMonitor(options) {
257
340
  actorUpdateAvailable,
258
341
  checkedAt: cache.checkedAt,
259
342
  checkError,
343
+ profileName,
344
+ upgradeCommand: formatUpgradeCommand(profileName),
260
345
  };
261
346
  };
262
347
  const bootstrapObservedActorFromHistory = async (actorId) => {
@@ -296,7 +381,115 @@ export function createVersionStatusMonitor(options) {
296
381
  /* History bootstrap is best-effort and must never fail version status reads. */
297
382
  }
298
383
  };
384
+ let upgradeInFlight = null;
385
+ const resolveProfileName = () => options.profileName?.trim() || detectDshProfileName({
386
+ paths: [
387
+ (() => { try {
388
+ return dirname(fileURLToPath(import.meta.url));
389
+ }
390
+ catch {
391
+ return '';
392
+ } })(),
393
+ options.getSnapshotDir(),
394
+ process.cwd(),
395
+ ],
396
+ });
397
+ const executePluginUpgrade = async (signal) => {
398
+ const profileName = resolveProfileName();
399
+ const command = formatUpgradeCommand(profileName);
400
+ if (options.runUpgrade) {
401
+ const outcome = await options.runUpgrade(profileName, signal);
402
+ return {
403
+ ok: outcome.ok,
404
+ profileName,
405
+ command,
406
+ installedVersion: outcome.installedVersion ?? null,
407
+ restartRequired: outcome.ok,
408
+ ...(outcome.message ? { message: outcome.message } : {}),
409
+ };
410
+ }
411
+ const env = { ...process.env, PATH: buildAugmentedPath(process.env) };
412
+ const dshHome = env.DSH_HOME?.trim() || join(env.HOME?.trim() || homedir(), '.dsh');
413
+ const profileDir = join(dshHome, 'profiles', profileName);
414
+ try {
415
+ if (profileName === 'desktop') {
416
+ const argvPnpm = process.argv.find(arg => /(?:^|[/\\])pnpm\.[cm]?js$/.test(arg));
417
+ const runtimePnpm = join(dshHome, 'dsh-runtimes', 'dsh-primary-runtime', 'dependencies', 'pnpm', 'bin', 'pnpm.cjs');
418
+ let bundledPnpm = null;
419
+ for (const candidate of [argvPnpm, runtimePnpm]) {
420
+ if (!candidate)
421
+ continue;
422
+ try {
423
+ await access(candidate);
424
+ bundledPnpm = candidate;
425
+ break;
426
+ }
427
+ catch { /* Try next candidate. */ }
428
+ }
429
+ if (bundledPnpm) {
430
+ await execFileAsync(process.execPath, [bundledPnpm, 'add', 'google-trends-for-agent@latest'], {
431
+ cwd: profileDir,
432
+ timeout: 120_000,
433
+ maxBuffer: 2 * 1024 * 1024,
434
+ signal,
435
+ env,
436
+ });
437
+ }
438
+ else {
439
+ const pnpmBin = await resolveCliBinary('pnpm', 'PNPM_BIN', env);
440
+ await execFileAsync(pnpmBin, ['add', 'google-trends-for-agent@latest'], {
441
+ cwd: profileDir,
442
+ timeout: 120_000,
443
+ maxBuffer: 2 * 1024 * 1024,
444
+ signal,
445
+ env,
446
+ });
447
+ }
448
+ }
449
+ else {
450
+ const dshBin = await resolveCliBinary('dsh', 'DSH_BIN', env);
451
+ await execFileAsync(dshBin, ['plugin', '--profile', profileName, 'add', 'google-trends-for-agent@latest'], {
452
+ timeout: 120_000,
453
+ maxBuffer: 2 * 1024 * 1024,
454
+ signal,
455
+ env,
456
+ });
457
+ }
458
+ const installedVersion = await readInstalledProfileVersion(profileName, env);
459
+ return {
460
+ ok: true,
461
+ profileName,
462
+ command,
463
+ installedVersion,
464
+ restartRequired: true,
465
+ };
466
+ }
467
+ catch (error) {
468
+ const err = error;
469
+ const detail = [err.stderr, err.stdout, err.message]
470
+ .find((part) => typeof part === 'string' && part.trim().length > 0)
471
+ ?.trim()
472
+ .split(/\r?\n/)
473
+ .slice(-3)
474
+ .join(' ')
475
+ .slice(0, 260) ?? 'Plugin upgrade command failed.';
476
+ return {
477
+ ok: false,
478
+ profileName,
479
+ command,
480
+ installedVersion: null,
481
+ restartRequired: false,
482
+ message: detail,
483
+ };
484
+ }
485
+ };
299
486
  return {
487
+ async upgradePlugin(signal) {
488
+ if (!upgradeInFlight) {
489
+ upgradeInFlight = executePluginUpgrade(signal).finally(() => { upgradeInFlight = null; });
490
+ }
491
+ return upgradeInFlight;
492
+ },
300
493
  async status(query) {
301
494
  await ensureLoaded();
302
495
  if (query.egress === 'actor-own' && query.apifyActor?.trim()) {
package/dist/trending.js CHANGED
@@ -106,7 +106,7 @@ export async function fetchTrending(input, options = {}) {
106
106
  [input.minVolume, input.limit].some(n => n !== undefined && (!Number.isSafeInteger(n) || n < 0)) ||
107
107
  (input.categories !== undefined && (!Array.isArray(input.categories) || !input.categories.every(n => Number.isSafeInteger(n) && n > 0))) ||
108
108
  (options.timeoutMs !== undefined && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) ||
109
- (options.maxRetries !== undefined && (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0 || options.maxRetries > 2))) {
109
+ (options.maxRetries !== undefined && (!Number.isSafeInteger(options.maxRetries) || options.maxRetries < 0 || options.maxRetries > 4))) {
110
110
  throw new GTrendsError('INVALID_INPUT', 'invalid geo, hours, language, filters, retries, or timeout');
111
111
  }
112
112
  const limiter = options.limiter ?? new RateLimiter({ ...options, minIntervalMs: options.minIntervalMs ?? 1500 });
@@ -4,6 +4,17 @@ export declare const GTFA_RELEASES_URL = "https://github.com/meka-im/google-tren
4
4
  export declare const GTFA_LATEST_RELEASE_API_URL = "https://api.github.com/repos/meka-im/google-trends-for-agent/releases/latest";
5
5
  export declare const GTFA_UPGRADE_COMMAND = "dsh plugin --profile web add google-trends-for-agent@latest";
6
6
  export declare const VERSION_STATUS_PATH = "/api/gtfa.version";
7
+ export declare const PLUGIN_UPGRADE_PATH = "/api/gtfa.plugin-upgrade";
8
+ /** Build the profile-specific upgrade command (Desktop profile is Electron-managed, so dsh CLI blocks --profile desktop). */
9
+ export declare function formatUpgradeCommand(profileName?: string | null): string;
10
+ export interface PluginUpgradeResult {
11
+ ok: boolean;
12
+ profileName: string;
13
+ command: string;
14
+ installedVersion: string | null;
15
+ restartRequired: boolean;
16
+ message?: string;
17
+ }
7
18
  export interface ReleaseInfo {
8
19
  version: string;
9
20
  tagName: string;
@@ -27,6 +38,8 @@ export interface VersionStatusSnapshot {
27
38
  actorUpdateAvailable: boolean;
28
39
  checkedAt: string | null;
29
40
  checkError: VersionCheckErrorCode | null;
41
+ profileName?: string | null;
42
+ upgradeCommand?: string | null;
30
43
  }
31
44
  export interface ParsedSemver {
32
45
  major: number;
@@ -4,6 +4,18 @@ export const GTFA_RELEASES_URL = `${GTFA_SOURCE_URL}/releases`;
4
4
  export const GTFA_LATEST_RELEASE_API_URL = 'https://api.github.com/repos/meka-im/google-trends-for-agent/releases/latest';
5
5
  export const GTFA_UPGRADE_COMMAND = 'dsh plugin --profile web add google-trends-for-agent@latest';
6
6
  export const VERSION_STATUS_PATH = '/api/gtfa.version';
7
+ export const PLUGIN_UPGRADE_PATH = '/api/gtfa.plugin-upgrade';
8
+ const SAFE_PROFILE_RE = /^[a-zA-Z0-9._-]{1,64}$/;
9
+ /** Build the profile-specific upgrade command (Desktop profile is Electron-managed, so dsh CLI blocks --profile desktop). */
10
+ export function formatUpgradeCommand(profileName) {
11
+ const clean = typeof profileName === 'string' && SAFE_PROFILE_RE.test(profileName.trim())
12
+ ? profileName.trim()
13
+ : 'web';
14
+ if (clean === 'desktop') {
15
+ return 'pnpm --dir ~/.dsh/profiles/desktop add google-trends-for-agent@latest';
16
+ }
17
+ return `dsh plugin --profile ${clean} add google-trends-for-agent@latest`;
18
+ }
7
19
  const SEMVER_RE = /^v?(\d{1,5})\.(\d{1,5})\.(\d{1,5})(?:-([a-zA-Z0-9.-]{1,40}))?$/;
8
20
  /** Parse a bounded X.Y.Z(-prerelease) version string. */
9
21
  export function parseSemver(raw) {
@@ -127,6 +139,12 @@ export function parseVersionStatus(value) {
127
139
  }
128
140
  const checkError = row.checkError === 'network' || row.checkError === 'rate-limited' || row.checkError === 'http'
129
141
  ? row.checkError : null;
142
+ const profileName = typeof row.profileName === 'string' && SAFE_PROFILE_RE.test(row.profileName.trim())
143
+ ? row.profileName.trim() : null;
144
+ const upgradeCommand = typeof row.upgradeCommand === 'string'
145
+ && (row.upgradeCommand.trim().startsWith('dsh plugin ') || row.upgradeCommand.trim().startsWith('pnpm '))
146
+ ? row.upgradeCommand.trim()
147
+ : profileName ? formatUpgradeCommand(profileName) : null;
130
148
  return {
131
149
  pluginVersion: row.pluginVersion,
132
150
  baselineCatalogRevision: row.baselineCatalogRevision,
@@ -138,5 +156,7 @@ export function parseVersionStatus(value) {
138
156
  actorUpdateAvailable: row.actorUpdateAvailable === true,
139
157
  checkedAt: typeof row.checkedAt === 'string' && Number.isFinite(Date.parse(row.checkedAt)) ? row.checkedAt : null,
140
158
  checkError,
159
+ ...(profileName ? { profileName } : {}),
160
+ ...(upgradeCommand ? { upgradeCommand } : {}),
141
161
  };
142
162
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "google-trends-for-agent",
3
- "version": "0.2.45",
3
+ "version": "0.2.46",
4
4
  "description": "Search-interest signals for AI agents — an unofficial Google Trends client",
5
5
  "type": "module",
6
6
  "license": "MIT",