@rivus/gateway 0.21.1 → 0.22.0

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.
Files changed (31) hide show
  1. package/README.md +4 -1
  2. package/assets/audio-transcriber/fetch-model.mjs +63 -70
  3. package/assets/audio-transcriber/transcribe.mjs +38 -47
  4. package/assets/installation-policy.json +4 -3
  5. package/dist/bootstrap/feishu.d.ts +7 -2
  6. package/dist/bootstrap/feishu.js +19195 -17153
  7. package/dist/bootstrap/herdr-feishu.d.ts +1 -7
  8. package/dist/bootstrap/herdr-feishu.js +23 -12
  9. package/dist/chunks/automation-presentation.js +58 -60
  10. package/dist/chunks/feishu-receive-message.js +113 -0
  11. package/dist/chunks/herdr-feishu-runtime.js +1027 -642
  12. package/dist/chunks/public.d.ts +278 -0
  13. package/dist/chunks/public2.d.ts +10 -0
  14. package/dist/chunks/rivus-deployment-cli-process.d.ts +127 -455
  15. package/dist/chunks/rivus-home-deployment-env.js +1342 -1781
  16. package/dist/chunks/rivus-node-entrypoint.js +4351 -4061
  17. package/dist/index.d.ts +23 -11
  18. package/dist/mcp.d.ts +10 -9
  19. package/dist/mcp.js +43 -43
  20. package/package.json +15 -11
  21. package/templates/a-share-briefing-analysis.mjs +32 -34
  22. package/templates/a-share-briefing-renderer.mjs +175 -186
  23. package/templates/a-share-index-evidence.mjs +50 -54
  24. package/templates/a-share-market-briefing.mjs +37 -39
  25. package/templates/a-share-overseas-evidence.mjs +35 -39
  26. package/templates/a-share-policy-evidence.mjs +90 -96
  27. package/templates/a-share-sector-evidence.mjs +32 -35
  28. package/templates/acp-stdio-proxy.mjs +21 -22
  29. package/templates/current-weather.mjs +56 -58
  30. package/templates/html-drive-tools.mjs +130 -141
  31. package/templates/rivus-agents.plugin.mjs +55 -57
@@ -7,33 +7,6 @@ const INDEXES = Object.freeze([
7
7
  { name: "纳斯达克", symbol: "usIXIC" },
8
8
  { name: "标普 500", symbol: "usINX" }
9
9
  ]);
10
-
11
- export async function readAShareOverseasEvidence({ occurrence }) {
12
- const url = new URL("https://qt.gtimg.cn/");
13
- url.searchParams.set("q", INDEXES.map(({ symbol }) => symbol).join(","));
14
- const responseBody = await readAShareProviderResponse({
15
- accept: "text/plain",
16
- maxBytes: 64 * 1024,
17
- referer: "https://finance.qq.com/",
18
- source: "a-share overseas evidence",
19
- url
20
- });
21
- const body = new TextDecoder("gbk").decode(responseBody);
22
- const quotes = INDEXES.map((index) => parseQuote(index, body));
23
- const asOf = quotes
24
- .map(({ providerTime }) => providerTime)
25
- .sort((left, right) => left.localeCompare(right))
26
- .at(-1);
27
- if (new Set(quotes.map(({ providerTime }) => providerTime)).size !== 1) {
28
- throw new Error("a-share overseas evidence timestamps are inconsistent");
29
- }
30
- const age = providerClockTime(occurrence) - providerClockTime(asOf);
31
- if (age < 0 || age > MAX_AGE_MS) {
32
- throw new Error("a-share overseas evidence is stale for the occurrence");
33
- }
34
- return Object.freeze({ asOf, quotes: Object.freeze(quotes), source: SOURCE });
35
- }
36
-
37
10
  function providerClockTime(value) {
38
11
  if (value.includes("T")) {
39
12
  const parts = new Intl.DateTimeFormat("en-CA", {
@@ -53,7 +26,19 @@ function providerClockTime(value) {
53
26
  }
54
27
  return Date.parse(`${value.replace(" ", "T")}Z`);
55
28
  }
29
+ function isValidProviderTimestamp(value) {
30
+ const normalized = value.replace(" ", "T");
31
+ const timestamp = Date.parse(`${normalized}Z`);
32
+ return Number.isFinite(timestamp) && new Date(timestamp).toISOString().slice(0, 19) === normalized;
33
+ }
56
34
 
35
+ function readFiniteNumber(value, symbol, field) {
36
+ const number = Number(value);
37
+ if (!Number.isFinite(number)) {
38
+ throw new Error(`a-share overseas evidence is missing ${field} for ${symbol}`);
39
+ }
40
+ return number;
41
+ }
57
42
  function parseQuote(index, body) {
58
43
  const match = body.match(new RegExp(`(?:^|\\n)v_${index.symbol}="([^"]+)";`, "u"));
59
44
  if (!match) {
@@ -78,17 +63,28 @@ function parseQuote(index, body) {
78
63
  symbol: index.symbol
79
64
  });
80
65
  }
81
-
82
- function isValidProviderTimestamp(value) {
83
- const normalized = value.replace(" ", "T");
84
- const timestamp = Date.parse(`${normalized}Z`);
85
- return Number.isFinite(timestamp) && new Date(timestamp).toISOString().slice(0, 19) === normalized;
86
- }
87
-
88
- function readFiniteNumber(value, symbol, field) {
89
- const number = Number(value);
90
- if (!Number.isFinite(number)) {
91
- throw new Error(`a-share overseas evidence is missing ${field} for ${symbol}`);
66
+ export async function readAShareOverseasEvidence({ occurrence }) {
67
+ const url = new URL("https://qt.gtimg.cn/");
68
+ url.searchParams.set("q", INDEXES.map(({ symbol }) => symbol).join(","));
69
+ const responseBody = await readAShareProviderResponse({
70
+ accept: "text/plain",
71
+ maxBytes: 64 * 1024,
72
+ referer: "https://finance.qq.com/",
73
+ source: "a-share overseas evidence",
74
+ url
75
+ });
76
+ const body = new TextDecoder("gbk").decode(responseBody);
77
+ const quotes = INDEXES.map((index) => parseQuote(index, body));
78
+ const asOf = quotes
79
+ .map(({ providerTime }) => providerTime)
80
+ .sort((left, right) => left.localeCompare(right))
81
+ .at(-1);
82
+ if (new Set(quotes.map(({ providerTime }) => providerTime)).size !== 1) {
83
+ throw new Error("a-share overseas evidence timestamps are inconsistent");
92
84
  }
93
- return number;
85
+ const age = providerClockTime(occurrence) - providerClockTime(asOf);
86
+ if (age < 0 || age > MAX_AGE_MS) {
87
+ throw new Error("a-share overseas evidence is stale for the occurrence");
88
+ }
89
+ return Object.freeze({ asOf, quotes: Object.freeze(quotes), source: SOURCE });
94
90
  }
@@ -1,73 +1,6 @@
1
1
  import { readAShareProviderResponse } from "./a-share-provider-response.mjs";
2
2
 
3
3
  const LOOKBACK_MS = 3 * 24 * 60 * 60 * 1000;
4
-
5
- export async function readASharePolicyEvidence({ occurrence }) {
6
- const occurrenceTime = Date.parse(occurrence);
7
- const readers = [
8
- { read: readPbcHeadlines, source: "中国人民银行" },
9
- { read: readCsrcHeadlines, source: "中国证监会" }
10
- ];
11
- const settled = await Promise.allSettled(readers.map(({ read }) => read()));
12
- const available = settled.flatMap((result, index) =>
13
- result.status === "fulfilled" ? [{ items: result.value, source: readers[index].source }] : []
14
- );
15
- if (available.length === 0) {
16
- throw new Error("a-share policy evidence sources are unavailable");
17
- }
18
- const items = available
19
- .flatMap(({ items }) => items)
20
- .filter(({ publishedAt }) => {
21
- const publishedTime = Date.parse(publishedAt);
22
- return publishedTime <= occurrenceTime && publishedTime >= occurrenceTime - LOOKBACK_MS;
23
- })
24
- .sort((left, right) => right.publishedAt.localeCompare(left.publishedAt))
25
- .slice(0, 4);
26
- const sources = available.map(({ source }) => source);
27
- const unavailableSources = settled.flatMap((result, index) =>
28
- result.status === "rejected" ? [readers[index].source] : []
29
- );
30
- return Object.freeze({
31
- items: Object.freeze(items),
32
- sources: Object.freeze(sources),
33
- unavailableSources: Object.freeze(unavailableSources)
34
- });
35
- }
36
-
37
- async function readPbcHeadlines() {
38
- const url = new URL("https://www.pbc.gov.cn/goutongjiaoliu/113456/113469/index.html");
39
- const body = await readText(url, "中国人民银行");
40
- const items = [];
41
- const pattern =
42
- /<a\s+([^>]*\bistitle="true"[^>]*)>[\s\S]*?<\/a>\s*<\/font>\s*<span[^>]*>\s*(\d{4}-\d{2}-\d{2})\s*<\/span>/giu;
43
- for (const match of body.matchAll(pattern)) {
44
- const href = readHtmlAttribute(match[1], "href");
45
- const title = decodeHtml(readHtmlAttribute(match[1], "title"));
46
- if (!href || !title || title.length > 200) {
47
- continue;
48
- }
49
- const itemUrl = normalizeSourceUrl(href, url, "www.pbc.gov.cn");
50
- if (!itemUrl) {
51
- continue;
52
- }
53
- items.push(
54
- Object.freeze({
55
- publishedAt: readPbcPublishedAt(itemUrl, match[2]),
56
- source: "中国人民银行",
57
- title,
58
- url: itemUrl
59
- })
60
- );
61
- if (items.length === 2) {
62
- break;
63
- }
64
- }
65
- if (items.length === 0) {
66
- throw new Error("PBC policy evidence contains no valid headlines");
67
- }
68
- return Object.freeze(items);
69
- }
70
-
71
4
  function readPbcPublishedAt(itemUrl, displayedDate) {
72
5
  const timestamp = new URL(itemUrl).pathname.match(/\/(\d{14})\d*\/index\.html$/u)?.[1];
73
6
  if (!timestamp) {
@@ -75,7 +8,33 @@ function readPbcPublishedAt(itemUrl, displayedDate) {
75
8
  }
76
9
  return `${timestamp.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/u, "$1-$2-$3T$4:$5:$6")}+08:00`;
77
10
  }
11
+ async function readText(url, source, maxBytes = 128 * 1024) {
12
+ const body = await readAShareProviderResponse({
13
+ accept: "text/html,application/json",
14
+ maxBytes,
15
+ referer: `${url.origin}/`,
16
+ source: `${source} policy evidence`,
17
+ url
18
+ });
19
+ return body.toString("utf8");
20
+ }
21
+
22
+ function readHtmlAttribute(attributes, name) {
23
+ return attributes.match(new RegExp(`\\b${name}="([^"]+)"`, "iu"))?.[1];
24
+ }
78
25
 
26
+ function normalizeSourceUrl(value, baseUrl, expectedHostname) {
27
+ let url;
28
+ try {
29
+ url = new URL(value, baseUrl);
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ if (url.protocol !== "https:" || url.hostname !== expectedHostname) {
34
+ return undefined;
35
+ }
36
+ return url.href;
37
+ }
79
38
  async function readCsrcHeadlines() {
80
39
  const url = new URL("https://www.csrc.gov.cn/searchList/a1a078ee0bc54721ab6b148884c784a8");
81
40
  url.searchParams.set("_isAgg", "true");
@@ -126,35 +85,6 @@ async function readCsrcHeadlines() {
126
85
  }
127
86
  return Object.freeze(items);
128
87
  }
129
-
130
- async function readText(url, source, maxBytes = 128 * 1024) {
131
- const body = await readAShareProviderResponse({
132
- accept: "text/html,application/json",
133
- maxBytes,
134
- referer: `${url.origin}/`,
135
- source: `${source} policy evidence`,
136
- url
137
- });
138
- return body.toString("utf8");
139
- }
140
-
141
- function readHtmlAttribute(attributes, name) {
142
- return attributes.match(new RegExp(`\\b${name}="([^"]+)"`, "iu"))?.[1];
143
- }
144
-
145
- function normalizeSourceUrl(value, baseUrl, expectedHostname) {
146
- let url;
147
- try {
148
- url = new URL(value, baseUrl);
149
- } catch {
150
- return undefined;
151
- }
152
- if (url.protocol !== "https:" || url.hostname !== expectedHostname) {
153
- return undefined;
154
- }
155
- return url.href;
156
- }
157
-
158
88
  function decodeHtml(value) {
159
89
  return value
160
90
  .replaceAll("&amp;", "&")
@@ -163,3 +93,67 @@ function decodeHtml(value) {
163
93
  .replaceAll("&lt;", "<")
164
94
  .replaceAll("&gt;", ">");
165
95
  }
96
+ async function readPbcHeadlines() {
97
+ const url = new URL("https://www.pbc.gov.cn/goutongjiaoliu/113456/113469/index.html");
98
+ const body = await readText(url, "中国人民银行");
99
+ const items = [];
100
+ const pattern =
101
+ /<a\s+([^>]*\bistitle="true"[^>]*)>[\s\S]*?<\/a>\s*<\/font>\s*<span[^>]*>\s*(\d{4}-\d{2}-\d{2})\s*<\/span>/giu;
102
+ for (const match of body.matchAll(pattern)) {
103
+ const href = readHtmlAttribute(match[1], "href");
104
+ const title = decodeHtml(readHtmlAttribute(match[1], "title"));
105
+ if (!href || !title || title.length > 200) {
106
+ continue;
107
+ }
108
+ const itemUrl = normalizeSourceUrl(href, url, "www.pbc.gov.cn");
109
+ if (!itemUrl) {
110
+ continue;
111
+ }
112
+ items.push(
113
+ Object.freeze({
114
+ publishedAt: readPbcPublishedAt(itemUrl, match[2]),
115
+ source: "中国人民银行",
116
+ title,
117
+ url: itemUrl
118
+ })
119
+ );
120
+ if (items.length === 2) {
121
+ break;
122
+ }
123
+ }
124
+ if (items.length === 0) {
125
+ throw new Error("PBC policy evidence contains no valid headlines");
126
+ }
127
+ return Object.freeze(items);
128
+ }
129
+ export async function readASharePolicyEvidence({ occurrence }) {
130
+ const occurrenceTime = Date.parse(occurrence);
131
+ const readers = [
132
+ { read: readPbcHeadlines, source: "中国人民银行" },
133
+ { read: readCsrcHeadlines, source: "中国证监会" }
134
+ ];
135
+ const settled = await Promise.allSettled(readers.map(({ read }) => read()));
136
+ const available = settled.flatMap((result, index) =>
137
+ result.status === "fulfilled" ? [{ items: result.value, source: readers[index].source }] : []
138
+ );
139
+ if (available.length === 0) {
140
+ throw new Error("a-share policy evidence sources are unavailable");
141
+ }
142
+ const items = available
143
+ .flatMap(({ items }) => items)
144
+ .filter(({ publishedAt }) => {
145
+ const publishedTime = Date.parse(publishedAt);
146
+ return publishedTime <= occurrenceTime && publishedTime >= occurrenceTime - LOOKBACK_MS;
147
+ })
148
+ .sort((left, right) => right.publishedAt.localeCompare(left.publishedAt))
149
+ .slice(0, 4);
150
+ const sources = available.map(({ source }) => source);
151
+ const unavailableSources = settled.flatMap((result, index) =>
152
+ result.status === "rejected" ? [readers[index].source] : []
153
+ );
154
+ return Object.freeze({
155
+ items: Object.freeze(items),
156
+ sources: Object.freeze(sources),
157
+ unavailableSources: Object.freeze(unavailableSources)
158
+ });
159
+ }
@@ -2,41 +2,6 @@ import { dateInShanghai } from "./a-share-market-date.mjs";
2
2
  import { readAShareProviderResponse } from "./a-share-provider-response.mjs";
3
3
 
4
4
  const SOURCE = "东方财富行业板块公开行情";
5
-
6
- export async function readAShareSectorEvidence({ marketDate }) {
7
- const [leaders, laggards] = await Promise.all([readSectorRanking(true), readSectorRanking(false)]);
8
- const sectors = [...leaders, ...laggards];
9
- const asOf = sectors
10
- .map(({ asOf }) => asOf)
11
- .sort((left, right) => left.localeCompare(right))
12
- .at(-1);
13
- if (!sectors.every((sector) => dateInShanghai(new Date(sector.asOf)) === marketDate)) {
14
- throw new Error("a-share sector evidence is stale for the market date");
15
- }
16
- return Object.freeze({ asOf, laggards, leaders, source: SOURCE });
17
- }
18
-
19
- async function readSectorRanking(descending) {
20
- const url = new URL("https://push2delay.eastmoney.com/api/qt/clist/get");
21
- url.searchParams.set("pn", "1");
22
- url.searchParams.set("pz", "3");
23
- url.searchParams.set("po", descending ? "1" : "0");
24
- url.searchParams.set("np", "1");
25
- url.searchParams.set("fltt", "2");
26
- url.searchParams.set("invt", "2");
27
- url.searchParams.set("fid", "f3");
28
- url.searchParams.set("fs", "m:90+t:2");
29
- url.searchParams.set("fields", "f12,f14,f3,f124");
30
- const body = await readAShareProviderResponse({
31
- accept: "application/json",
32
- maxBytes: 64 * 1024,
33
- referer: "https://quote.eastmoney.com/",
34
- source: "a-share sector evidence",
35
- url
36
- });
37
- return parseSectorRanking(body.toString("utf8"));
38
- }
39
-
40
5
  function parseSectorRanking(body) {
41
6
  let payload;
42
7
  try {
@@ -70,3 +35,35 @@ function parseSectorRanking(body) {
70
35
  })
71
36
  );
72
37
  }
38
+ async function readSectorRanking(descending) {
39
+ const url = new URL("https://push2delay.eastmoney.com/api/qt/clist/get");
40
+ url.searchParams.set("pn", "1");
41
+ url.searchParams.set("pz", "3");
42
+ url.searchParams.set("po", descending ? "1" : "0");
43
+ url.searchParams.set("np", "1");
44
+ url.searchParams.set("fltt", "2");
45
+ url.searchParams.set("invt", "2");
46
+ url.searchParams.set("fid", "f3");
47
+ url.searchParams.set("fs", "m:90+t:2");
48
+ url.searchParams.set("fields", "f12,f14,f3,f124");
49
+ const body = await readAShareProviderResponse({
50
+ accept: "application/json",
51
+ maxBytes: 64 * 1024,
52
+ referer: "https://quote.eastmoney.com/",
53
+ source: "a-share sector evidence",
54
+ url
55
+ });
56
+ return parseSectorRanking(body.toString("utf8"));
57
+ }
58
+ export async function readAShareSectorEvidence({ marketDate }) {
59
+ const [leaders, laggards] = await Promise.all([readSectorRanking(true), readSectorRanking(false)]);
60
+ const sectors = [...leaders, ...laggards];
61
+ const asOf = sectors
62
+ .map(({ asOf }) => asOf)
63
+ .sort((left, right) => left.localeCompare(right))
64
+ .at(-1);
65
+ if (!sectors.every((sector) => dateInShanghai(new Date(sector.asOf)) === marketDate)) {
66
+ throw new Error("a-share sector evidence is stale for the market date");
67
+ }
68
+ return Object.freeze({ asOf, laggards, leaders, source: SOURCE });
69
+ }
@@ -16,28 +16,6 @@ if (!command) {
16
16
  const workingDirectory = process.env.RIVUS_ACP_WORKING_DIRECTORY?.trim() || process.cwd();
17
17
  const sessionStorePath = process.env.RIVUS_ACP_SESSION_STORE?.trim();
18
18
  const permissionBridge = createAcpPermissionBridge();
19
- const downstream = createAcpStdioAgentLoop({
20
- arguments: parseArguments(process.env.RIVUS_ACP_SERVER_ARGUMENTS),
21
- command,
22
- environment: selectEnvironment(process.env.RIVUS_ACP_SERVER_ENV_KEYS),
23
- onStderr: (text) => process.stderr.write(text),
24
- permissionPolicy: permissionBridge.policy,
25
- ...(sessionStorePath ? { sessionStore: createJsonAcpSessionStore({ filePath: sessionStorePath }) } : {}),
26
- workingDirectory
27
- });
28
- const server = createAcpAgentServer({
29
- agentName: "rivus-acp-proxy",
30
- loop: downstream.loop,
31
- permissionBridge,
32
- workingDirectory
33
- });
34
-
35
- try {
36
- await serveAcpAgentOnStdio(server);
37
- } finally {
38
- await downstream.dispose();
39
- }
40
-
41
19
  function parseArguments(value) {
42
20
  if (!value?.trim()) {
43
21
  return [];
@@ -62,3 +40,24 @@ function selectEnvironment(value) {
62
40
  }
63
41
  return selected;
64
42
  }
43
+ const downstream = createAcpStdioAgentLoop({
44
+ arguments: parseArguments(process.env.RIVUS_ACP_SERVER_ARGUMENTS),
45
+ command,
46
+ environment: selectEnvironment(process.env.RIVUS_ACP_SERVER_ENV_KEYS),
47
+ onStderr: (text) => process.stderr.write(text),
48
+ permissionPolicy: permissionBridge.policy,
49
+ ...(sessionStorePath ? { sessionStore: createJsonAcpSessionStore({ filePath: sessionStorePath }) } : {}),
50
+ workingDirectory
51
+ });
52
+ const server = createAcpAgentServer({
53
+ agentName: "rivus-acp-proxy",
54
+ loop: downstream.loop,
55
+ permissionBridge,
56
+ workingDirectory
57
+ });
58
+
59
+ try {
60
+ await serveAcpAgentOnStdio(server);
61
+ } finally {
62
+ await downstream.dispose();
63
+ }
@@ -1,62 +1,4 @@
1
1
  import { readBoundedHttpsResponse } from "./https-response-reader.mjs";
2
-
3
- export async function readCurrentWeather(input) {
4
- if (input !== undefined && (typeof input !== "object" || input === null || Array.isArray(input))) {
5
- throw new Error("current-weather input must be an object");
6
- }
7
- const requestedLocation = input?.location;
8
- if (
9
- requestedLocation !== undefined &&
10
- (typeof requestedLocation !== "string" || !requestedLocation.trim() || requestedLocation.length > 100)
11
- ) {
12
- throw new Error("current-weather location must be a non-empty string up to 100 characters");
13
- }
14
- const location = requestedLocation?.trim() || process.env.RIVUS_WEATHER_DEFAULT_LOCATION?.trim() || "北京";
15
- const geocodingUrl = new URL("https://geocoding-api.open-meteo.com/v1/search");
16
- geocodingUrl.search = new URLSearchParams({ count: "1", format: "json", language: "zh", name: location }).toString();
17
- const geocoding = await fetchJson(geocodingUrl, "weather location lookup");
18
- const place = Array.isArray(geocoding.results) ? geocoding.results[0] : undefined;
19
- if (
20
- !place ||
21
- typeof place.name !== "string" ||
22
- typeof place.latitude !== "number" ||
23
- typeof place.longitude !== "number"
24
- ) {
25
- throw new Error(`current-weather could not resolve location: ${location}`);
26
- }
27
-
28
- const forecastUrl = new URL("https://api.open-meteo.com/v1/forecast");
29
- forecastUrl.search = new URLSearchParams({
30
- current: "temperature_2m,apparent_temperature,weather_code,wind_speed_10m",
31
- daily: "temperature_2m_max,temperature_2m_min,precipitation_probability_max",
32
- forecast_days: "1",
33
- latitude: String(place.latitude),
34
- longitude: String(place.longitude),
35
- timezone: "auto"
36
- }).toString();
37
- const forecast = await fetchJson(forecastUrl, "weather forecast lookup");
38
- const current = forecast.current;
39
- const daily = forecast.daily;
40
- if (!current || typeof current !== "object" || !daily || typeof daily !== "object") {
41
- throw new Error("current-weather provider returned an incomplete forecast");
42
- }
43
- const weatherCode = readNumber(current.weather_code, "weather_code");
44
- return {
45
- apparentTemperatureC: readNumber(current.apparent_temperature, "apparent_temperature"),
46
- condition: describeWeatherCode(weatherCode),
47
- date: readFirst(daily.time, "date"),
48
- location: place.country ? `${place.name}, ${place.country}` : place.name,
49
- observedAt: readString(current.time, "observed time"),
50
- precipitationProbabilityPercent: readFirstNumber(daily.precipitation_probability_max, "precipitation probability"),
51
- temperatureC: readNumber(current.temperature_2m, "temperature"),
52
- temperatureMaxC: readFirstNumber(daily.temperature_2m_max, "maximum temperature"),
53
- temperatureMinC: readFirstNumber(daily.temperature_2m_min, "minimum temperature"),
54
- timezone: readString(forecast.timezone ?? place.timezone, "timezone"),
55
- weatherCode,
56
- windSpeedKmh: readNumber(current.wind_speed_10m, "wind speed")
57
- };
58
- }
59
-
60
2
  async function fetchJson(url, operation) {
61
3
  let response;
62
4
  try {
@@ -139,3 +81,59 @@ function describeWeatherCode(code) {
139
81
  }
140
82
  return "未知";
141
83
  }
84
+ export async function readCurrentWeather(input) {
85
+ if (input !== undefined && (typeof input !== "object" || input === null || Array.isArray(input))) {
86
+ throw new Error("current-weather input must be an object");
87
+ }
88
+ const requestedLocation = input?.location;
89
+ if (
90
+ requestedLocation !== undefined &&
91
+ (typeof requestedLocation !== "string" || !requestedLocation.trim() || requestedLocation.length > 100)
92
+ ) {
93
+ throw new Error("current-weather location must be a non-empty string up to 100 characters");
94
+ }
95
+ const location = requestedLocation?.trim() || process.env.RIVUS_WEATHER_DEFAULT_LOCATION?.trim() || "北京";
96
+ const geocodingUrl = new URL("https://geocoding-api.open-meteo.com/v1/search");
97
+ geocodingUrl.search = new URLSearchParams({ count: "1", format: "json", language: "zh", name: location }).toString();
98
+ const geocoding = await fetchJson(geocodingUrl, "weather location lookup");
99
+ const place = Array.isArray(geocoding.results) ? geocoding.results[0] : undefined;
100
+ if (
101
+ !place ||
102
+ typeof place.name !== "string" ||
103
+ typeof place.latitude !== "number" ||
104
+ typeof place.longitude !== "number"
105
+ ) {
106
+ throw new Error(`current-weather could not resolve location: ${location}`);
107
+ }
108
+
109
+ const forecastUrl = new URL("https://api.open-meteo.com/v1/forecast");
110
+ forecastUrl.search = new URLSearchParams({
111
+ current: "temperature_2m,apparent_temperature,weather_code,wind_speed_10m",
112
+ daily: "temperature_2m_max,temperature_2m_min,precipitation_probability_max",
113
+ forecast_days: "1",
114
+ latitude: String(place.latitude),
115
+ longitude: String(place.longitude),
116
+ timezone: "auto"
117
+ }).toString();
118
+ const forecast = await fetchJson(forecastUrl, "weather forecast lookup");
119
+ const current = forecast.current;
120
+ const daily = forecast.daily;
121
+ if (!current || typeof current !== "object" || !daily || typeof daily !== "object") {
122
+ throw new Error("current-weather provider returned an incomplete forecast");
123
+ }
124
+ const weatherCode = readNumber(current.weather_code, "weather_code");
125
+ return {
126
+ apparentTemperatureC: readNumber(current.apparent_temperature, "apparent_temperature"),
127
+ condition: describeWeatherCode(weatherCode),
128
+ date: readFirst(daily.time, "date"),
129
+ location: place.country ? `${place.name}, ${place.country}` : place.name,
130
+ observedAt: readString(current.time, "observed time"),
131
+ precipitationProbabilityPercent: readFirstNumber(daily.precipitation_probability_max, "precipitation probability"),
132
+ temperatureC: readNumber(current.temperature_2m, "temperature"),
133
+ temperatureMaxC: readFirstNumber(daily.temperature_2m_max, "maximum temperature"),
134
+ temperatureMinC: readFirstNumber(daily.temperature_2m_min, "minimum temperature"),
135
+ timezone: readString(forecast.timezone ?? place.timezone, "timezone"),
136
+ weatherCode,
137
+ windSpeedKmh: readNumber(current.wind_speed_10m, "wind speed")
138
+ };
139
+ }