@polycode-projects/the-mechanical-code-talker 5.0.25 → 5.0.27
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/README.md +74 -11
- package/bin/tmct.mjs +81 -0
- package/package.json +6 -1
- package/src/adapters/corpus/courtesy.mjs +91 -28
- package/src/adapters/corpus/dbpedia-lookup-live.mjs +116 -0
- package/src/adapters/corpus/news-sources.mjs +436 -0
- package/src/adapters/corpus/research-source.mjs +16 -3
- package/src/adapters/corpus/wiktionary-live.mjs +158 -0
- package/src/adapters/news-store.mjs +87 -0
- package/src/adapters/toml-config.mjs +18 -0
- package/src/domain/ask.mjs +19 -6
- package/src/domain/choice-question.mjs +275 -0
- package/src/domain/cli-verbs.mjs +20 -0
- package/src/domain/codegraph.mjs +8 -1
- package/src/domain/dialogue-acts.mjs +1 -0
- package/src/domain/el-classify.mjs +569 -0
- package/src/domain/fact-phrase.mjs +70 -0
- package/src/domain/feed-normalize.mjs +224 -0
- package/src/domain/grammar/ace.mjs +223 -7
- package/src/domain/grammar/lexicon-core.json +2 -0
- package/src/domain/memory/trust.mjs +15 -0
- package/src/domain/news-feed.mjs +219 -0
- package/src/domain/reasoning-config.mjs +56 -0
- package/src/domain/sprite-animation.mjs +20 -2
- package/src/domain/tableau.mjs +1225 -0
- package/src/domain/term-ledger.mjs +118 -0
- package/src/services/chat.mjs +523 -20
- package/src/services/extract-facts.mjs +91 -1
- package/src/services/index.mjs +12 -0
- package/src/services/init.mjs +33 -0
- package/src/services/news-viz.mjs +489 -0
- package/src/services/news.mjs +918 -0
- package/src/services/sprite-catalog-viz.mjs +148 -78
- package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
- package/src/surfaces/web/news-browser-entry.mjs +384 -0
- package/src/surfaces/web/sprites-browser-entry.mjs +4 -4
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
// corpus/news-sources.mjs — the news source registry and fetch adapters
|
|
2
|
+
// (PLAN_NEWS_FEED.md section 9.2): the ten browser-verified sources from the
|
|
3
|
+
// probe rounds (section 4), one fetcher per wire format, each behind its own
|
|
4
|
+
// courtesy gate. Every URL is https; every fetch failure of any kind reads as
|
|
5
|
+
// null, never a throw; every fetched string passes stripMarkup before it
|
|
6
|
+
// leaves this module — the second half of the two-layer sanitisation rule
|
|
7
|
+
// (escapeHtml at render time) is the caller's job.
|
|
8
|
+
//
|
|
9
|
+
// A poll cycle must see a FRESH feed every time it asks, never a cached one —
|
|
10
|
+
// unlike a term lookup, where the same answer forever is exactly right. So
|
|
11
|
+
// every network call here goes through `gate.cachedFetch(url, work, {
|
|
12
|
+
// remember: false })`: still slot-gated (the courtesy pacing a repeated or
|
|
13
|
+
// multi-step fetch needs — Hacker News's ten sequential item fetches are the
|
|
14
|
+
// reason this matters, section 4's "10 × 250ms" arithmetic only holds if each
|
|
15
|
+
// one really waits for its own slot) but never cached, so a second poll
|
|
16
|
+
// always re-fetches.
|
|
17
|
+
//
|
|
18
|
+
// No node builtins — this module ships in the browser bundle unchanged; the
|
|
19
|
+
// only I/O is fetch.
|
|
20
|
+
|
|
21
|
+
import { detectFeedFormat, parseFeed, normalizeFeedItems, feedItemId, stripMarkup } from "../../domain/feed-normalize.mjs";
|
|
22
|
+
import { createCourtesyGate, DEFAULT_TIMEOUT_MS, DEFAULT_MIN_INTERVAL_MS } from "./courtesy.mjs";
|
|
23
|
+
|
|
24
|
+
export const NEWS_USER_AGENT = "the-mechanical-code-talker (+https://tmct.polycode.co.uk/)";
|
|
25
|
+
|
|
26
|
+
// Hacker News's Firebase-backed API tolerates a much faster anonymous poll
|
|
27
|
+
// than an RSS host does (PLAN_NEWS_FEED.md section 4); every other source
|
|
28
|
+
// keeps the shared DEFAULT_MIN_INTERVAL_MS floor.
|
|
29
|
+
const HACKER_NEWS_MIN_INTERVAL_MS = 250;
|
|
30
|
+
const HACKER_NEWS_ITEM_CAP = 10;
|
|
31
|
+
|
|
32
|
+
/** The ten browser-verified sources from the probe rounds (section 4.1 and
|
|
33
|
+
* 4.2): three contemporary defaults (Wikimedia featured, Hacker News, USGS
|
|
34
|
+
* quakes), two contemporary selectables (NYT World, Wikinews); three
|
|
35
|
+
* knowledge-base defaults (Simple English Wikipedia, Wikidata, Wiktionary),
|
|
36
|
+
* two knowledge-base selectables (DBpedia Lookup, English Wikipedia). The
|
|
37
|
+
* `kind: "kb"` records describe the knowledge-base sources for the
|
|
38
|
+
* registry/config/health surfaces; their actual lookups run through the
|
|
39
|
+
* existing research-source seam (getResearchProvider in wikipedia-live.mjs),
|
|
40
|
+
* not through createNewsFetcher below — a knowledge-base source is a
|
|
41
|
+
* targeted term lookup, not a feed to poll. */
|
|
42
|
+
export const NEWS_SOURCE_RECORDS = Object.freeze([
|
|
43
|
+
{
|
|
44
|
+
id: "wikimedia-featured",
|
|
45
|
+
name: "Wikimedia featured feed",
|
|
46
|
+
kind: "contemporary",
|
|
47
|
+
format: "wikimedia-feed",
|
|
48
|
+
url: "https://api.wikimedia.org/feed/v1/wikipedia/en/featured",
|
|
49
|
+
homepage: "https://www.wikipedia.org/",
|
|
50
|
+
licence: "CC BY-SA 4.0",
|
|
51
|
+
browserVerified: "2026-08-08",
|
|
52
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
53
|
+
enabledByDefault: true,
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
id: "hacker-news",
|
|
57
|
+
name: "Hacker News",
|
|
58
|
+
kind: "contemporary",
|
|
59
|
+
format: "hn",
|
|
60
|
+
url: "https://hacker-news.firebaseio.com/v0",
|
|
61
|
+
homepage: "https://news.ycombinator.com/",
|
|
62
|
+
licence: "user-submitted, discussion linked",
|
|
63
|
+
browserVerified: "2026-08-08",
|
|
64
|
+
minIntervalMs: HACKER_NEWS_MIN_INTERVAL_MS,
|
|
65
|
+
enabledByDefault: true,
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
id: "usgs-quakes",
|
|
69
|
+
name: "USGS earthquakes",
|
|
70
|
+
kind: "contemporary",
|
|
71
|
+
format: "usgs",
|
|
72
|
+
url: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson",
|
|
73
|
+
homepage: "https://earthquake.usgs.gov/",
|
|
74
|
+
licence: "US public domain",
|
|
75
|
+
browserVerified: "2026-08-08",
|
|
76
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
77
|
+
enabledByDefault: true,
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
id: "nyt-world",
|
|
81
|
+
name: "NYT World News",
|
|
82
|
+
kind: "contemporary",
|
|
83
|
+
format: "rss",
|
|
84
|
+
url: "https://rss.nytimes.com/services/xml/rss/nyt/World.xml",
|
|
85
|
+
homepage: "https://www.nytimes.com/section/world",
|
|
86
|
+
licence: "personal use with attribution",
|
|
87
|
+
browserVerified: "2026-08-08",
|
|
88
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
89
|
+
// The licence terms (personal, non-commercial, with attribution) sit
|
|
90
|
+
// awkwardly on a source that would fetch without the user asking first.
|
|
91
|
+
enabledByDefault: false,
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
id: "wikinews-published",
|
|
95
|
+
name: "Wikinews",
|
|
96
|
+
kind: "contemporary",
|
|
97
|
+
format: "mediawiki",
|
|
98
|
+
url: "https://en.wikinews.org/w/api.php",
|
|
99
|
+
homepage: "https://en.wikinews.org/",
|
|
100
|
+
licence: "CC BY 2.5",
|
|
101
|
+
browserVerified: "2026-08-08",
|
|
102
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
103
|
+
// Wikinews' own lead story announces the Wikimedia Foundation closing
|
|
104
|
+
// it; shipped selectable so its health row can tell users when it goes.
|
|
105
|
+
enabledByDefault: false,
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
id: "simple-wikipedia",
|
|
109
|
+
name: "Simple English Wikipedia",
|
|
110
|
+
kind: "kb",
|
|
111
|
+
format: "wikipedia-summary",
|
|
112
|
+
url: "https://simple.wikipedia.org",
|
|
113
|
+
homepage: "https://simple.wikipedia.org/",
|
|
114
|
+
licence: "CC BY-SA 4.0",
|
|
115
|
+
browserVerified: "2026-08-08",
|
|
116
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
117
|
+
enabledByDefault: true,
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
id: "wikidata",
|
|
121
|
+
name: "Wikidata",
|
|
122
|
+
kind: "kb",
|
|
123
|
+
format: "wikidata",
|
|
124
|
+
url: "https://www.wikidata.org",
|
|
125
|
+
homepage: "https://www.wikidata.org/",
|
|
126
|
+
licence: "CC0 1.0",
|
|
127
|
+
browserVerified: "2026-08-08",
|
|
128
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
129
|
+
enabledByDefault: true,
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
id: "wiktionary",
|
|
133
|
+
name: "Wiktionary",
|
|
134
|
+
kind: "kb",
|
|
135
|
+
format: "wiktionary",
|
|
136
|
+
url: "https://en.wiktionary.org",
|
|
137
|
+
homepage: "https://en.wiktionary.org/",
|
|
138
|
+
licence: "CC BY-SA 3.0",
|
|
139
|
+
browserVerified: "2026-08-08",
|
|
140
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
141
|
+
enabledByDefault: true,
|
|
142
|
+
},
|
|
143
|
+
{
|
|
144
|
+
id: "dbpedia-lookup",
|
|
145
|
+
name: "DBpedia Lookup",
|
|
146
|
+
kind: "kb",
|
|
147
|
+
format: "dbpedia-lookup",
|
|
148
|
+
url: "https://lookup.dbpedia.org",
|
|
149
|
+
homepage: "https://www.dbpedia.org/",
|
|
150
|
+
licence: "CC BY-SA 3.0",
|
|
151
|
+
browserVerified: "2026-08-08",
|
|
152
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
153
|
+
enabledByDefault: false,
|
|
154
|
+
},
|
|
155
|
+
{
|
|
156
|
+
id: "english-wikipedia",
|
|
157
|
+
name: "English Wikipedia",
|
|
158
|
+
kind: "kb",
|
|
159
|
+
format: "wikipedia-summary",
|
|
160
|
+
url: "https://en.wikipedia.org",
|
|
161
|
+
homepage: "https://en.wikipedia.org/",
|
|
162
|
+
licence: "CC BY-SA 4.0",
|
|
163
|
+
browserVerified: "2026-08-08",
|
|
164
|
+
minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
|
|
165
|
+
enabledByDefault: false,
|
|
166
|
+
},
|
|
167
|
+
]);
|
|
168
|
+
|
|
169
|
+
export const DEFAULT_NEWS_SOURCE_IDS = Object.freeze(["wikimedia-featured", "hacker-news", "usgs-quakes"]);
|
|
170
|
+
export const DEFAULT_NEWS_KB_IDS = Object.freeze(["simple-wikipedia", "wikidata", "wiktionary"]);
|
|
171
|
+
|
|
172
|
+
const registry = new Map(NEWS_SOURCE_RECORDS.map((record) => [record.id, record]));
|
|
173
|
+
|
|
174
|
+
/** Register (or replace) a source record: add-by-URL and tests extend the
|
|
175
|
+
* registry this way, the same idiom registerResearchSource uses. */
|
|
176
|
+
export function registerNewsSource(record) {
|
|
177
|
+
if (!record || typeof record.id !== "string" || !record.id) {
|
|
178
|
+
throw new Error("registerNewsSource: expected a record with a non-empty string id");
|
|
179
|
+
}
|
|
180
|
+
registry.set(record.id, record);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Every registered source record, insertion order (the shipped ten first,
|
|
184
|
+
* then whatever registerNewsSource added). */
|
|
185
|
+
export function newsSourceRecords() {
|
|
186
|
+
return [...registry.values()];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** `ids` folded onto known registry ids only, order preserved, duplicates
|
|
190
|
+
* dropped — an unrecognised id is silently absent rather than an error, so a
|
|
191
|
+
* config written against an older registry degrades instead of failing. */
|
|
192
|
+
export function normalizeNewsSourceIds(ids) {
|
|
193
|
+
if (!Array.isArray(ids)) return [];
|
|
194
|
+
const seen = new Set();
|
|
195
|
+
const out = [];
|
|
196
|
+
for (const raw of ids) {
|
|
197
|
+
const id = String(raw ?? "");
|
|
198
|
+
if (!id || !registry.has(id) || seen.has(id)) continue;
|
|
199
|
+
seen.add(id);
|
|
200
|
+
out.push(id);
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function byteLength(text) {
|
|
206
|
+
return new TextEncoder().encode(String(text ?? "")).length;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function jsonByteLength(body) {
|
|
210
|
+
try {
|
|
211
|
+
return byteLength(JSON.stringify(body ?? null));
|
|
212
|
+
} catch {
|
|
213
|
+
return 0;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function isNotModified(result) {
|
|
218
|
+
return !!result && typeof result === "object" && result.notModified === true;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A slot-gated but never-cached GET: paced against the gate's minIntervalMs
|
|
222
|
+
* like every other courtesy fetch, but a repeated call always re-fetches —
|
|
223
|
+
* the news poll loop's own requirement (module header). */
|
|
224
|
+
function pacedFetchText(gate, url) {
|
|
225
|
+
return gate.cachedFetch(url, () => gate.fetchText(url), { remember: false });
|
|
226
|
+
}
|
|
227
|
+
function pacedFetchJson(gate, url) {
|
|
228
|
+
return gate.cachedFetch(url, () => gate.fetchJson(url), { remember: false });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function utcDateParts(now) {
|
|
232
|
+
const d = new Date(now);
|
|
233
|
+
return {
|
|
234
|
+
yyyy: d.getUTCFullYear(),
|
|
235
|
+
mm: String(d.getUTCMonth() + 1).padStart(2, "0"),
|
|
236
|
+
dd: String(d.getUTCDate()).padStart(2, "0"),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function wikimediaFeedUrl(base, now) {
|
|
241
|
+
const { yyyy, mm, dd } = utcDateParts(now);
|
|
242
|
+
return `${base}/${yyyy}/${mm}/${dd}`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function fetchFeedFormat(record, gate, { format, now }) {
|
|
246
|
+
const result = await pacedFetchText(gate, record.url);
|
|
247
|
+
if (result === null) return null;
|
|
248
|
+
if (isNotModified(result)) return { items: [], bytes: 0, notModified: true };
|
|
249
|
+
const raw = parseFeed(result, { format });
|
|
250
|
+
const items = normalizeFeedItems(record.id, raw, { now });
|
|
251
|
+
return { items, bytes: byteLength(result) };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** `body.news` (when present — only some days) links every story listed
|
|
255
|
+
* under it; otherwise the day's `mostread` articles. Each raw item also
|
|
256
|
+
* carries `wikibaseItem` when the article names one, past normalizeFeedItems
|
|
257
|
+
* (which only knows the snapshot's own fixed fields) so the news
|
|
258
|
+
* enrichment loop can short-circuit straight to the Wikidata KB source with
|
|
259
|
+
* the Q-id already in hand, no lookup needed. */
|
|
260
|
+
async function fetchWikimediaFeed(record, gate, { now }) {
|
|
261
|
+
const primaryUrl = wikimediaFeedUrl(record.url, now);
|
|
262
|
+
let body = await pacedFetchJson(gate, primaryUrl);
|
|
263
|
+
if (body === null) {
|
|
264
|
+
// A 404 means the day's page is not yet published; retry once against
|
|
265
|
+
// the previous UTC day before giving up.
|
|
266
|
+
const prevDay = new Date(now);
|
|
267
|
+
prevDay.setUTCDate(prevDay.getUTCDate() - 1);
|
|
268
|
+
body = await pacedFetchJson(gate, wikimediaFeedUrl(record.url, prevDay.toISOString()));
|
|
269
|
+
if (body === null) return null;
|
|
270
|
+
}
|
|
271
|
+
if (isNotModified(body)) return { items: [], bytes: 0, notModified: true };
|
|
272
|
+
|
|
273
|
+
const articles = Array.isArray(body?.news)
|
|
274
|
+
? body.news.flatMap((story) => (Array.isArray(story?.links) ? story.links : []))
|
|
275
|
+
: Array.isArray(body?.mostread?.articles)
|
|
276
|
+
? body.mostread.articles
|
|
277
|
+
: [];
|
|
278
|
+
|
|
279
|
+
const raw = articles.map((a) => ({
|
|
280
|
+
guid: a?.wikibase_item || a?.normalizedtitle || a?.title || "",
|
|
281
|
+
title: stripMarkup(a?.normalizedtitle || a?.displaytitle || a?.title || ""),
|
|
282
|
+
url: a?.content_urls?.desktop?.page || "",
|
|
283
|
+
summary: stripMarkup(a?.extract || ""),
|
|
284
|
+
publishedAt: "",
|
|
285
|
+
wikibaseItem: a?.wikibase_item || "",
|
|
286
|
+
}));
|
|
287
|
+
|
|
288
|
+
const items = normalizeFeedItems(record.id, raw, { now });
|
|
289
|
+
const wikibaseItemById = new Map(raw.map((r) => [feedItemId(record.id, r.guid || r.url), r.wikibaseItem]));
|
|
290
|
+
for (const item of items) {
|
|
291
|
+
const wikibaseItem = wikibaseItemById.get(item.id);
|
|
292
|
+
if (wikibaseItem) item.wikibaseItem = wikibaseItem;
|
|
293
|
+
}
|
|
294
|
+
return { items, bytes: jsonByteLength(body) };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** topstories.json, then item/<id>.json for the first ten ids, through the
|
|
298
|
+
* same gate — each item fetch takes its own slot, so the ten round trips
|
|
299
|
+
* are genuinely paced by the gate's minIntervalMs rather than firing back
|
|
300
|
+
* to back (section 4's "10 × 250ms" latency budget only holds this way). */
|
|
301
|
+
async function fetchHackerNews(record, gate, { now }) {
|
|
302
|
+
const ids = await pacedFetchJson(gate, `${record.url}/topstories.json`);
|
|
303
|
+
if (!Array.isArray(ids)) return null;
|
|
304
|
+
const raw = [];
|
|
305
|
+
let bytes = 0;
|
|
306
|
+
for (const id of ids.slice(0, HACKER_NEWS_ITEM_CAP)) {
|
|
307
|
+
const item = await pacedFetchJson(gate, `${record.url}/item/${id}.json`);
|
|
308
|
+
if (!item) continue;
|
|
309
|
+
bytes += jsonByteLength(item);
|
|
310
|
+
raw.push({
|
|
311
|
+
guid: String(item.id ?? id),
|
|
312
|
+
title: stripMarkup(item.title || ""),
|
|
313
|
+
url: item.url || `https://news.ycombinator.com/item?id=${item.id ?? id}`,
|
|
314
|
+
summary: "",
|
|
315
|
+
publishedAt: Number.isFinite(item.time) ? new Date(item.time * 1000).toISOString() : "",
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
const items = normalizeFeedItems(record.id, raw, { now });
|
|
319
|
+
return { items, bytes };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function fetchUsgs(record, gate, { now }) {
|
|
323
|
+
const body = await pacedFetchJson(gate, record.url);
|
|
324
|
+
if (body === null) return null;
|
|
325
|
+
if (isNotModified(body)) return { items: [], bytes: 0, notModified: true };
|
|
326
|
+
const features = Array.isArray(body?.features) ? body.features : [];
|
|
327
|
+
const raw = features.map((f) => ({
|
|
328
|
+
guid: String(f?.id ?? f?.properties?.detail ?? f?.properties?.url ?? ""),
|
|
329
|
+
title: stripMarkup(f?.properties?.title || ""),
|
|
330
|
+
url: f?.properties?.url || "",
|
|
331
|
+
summary: stripMarkup(`magnitude ${f?.properties?.mag ?? "unknown"} earthquake near ${f?.properties?.place || "an unreported location"}`),
|
|
332
|
+
publishedAt: Number.isFinite(f?.properties?.time) ? new Date(f.properties.time).toISOString() : "",
|
|
333
|
+
}));
|
|
334
|
+
const items = normalizeFeedItems(record.id, raw, { now });
|
|
335
|
+
return { items, bytes: jsonByteLength(body) };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function wikinewsArticleOrigin(apiUrl) {
|
|
339
|
+
return String(apiUrl ?? "").replace(/\/w\/api\.php$/, "");
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Wikinews' recently-published mainspace articles via the action API's
|
|
343
|
+
* recentchanges list — the smallest query that names what is new without a
|
|
344
|
+
* category to maintain by hand. */
|
|
345
|
+
async function fetchWikinews(record, gate, { now }) {
|
|
346
|
+
const url = `${record.url}?action=query&list=recentchanges&rcnamespace=0&rcnewonly=1&rclimit=20&format=json&formatversion=2&origin=*`;
|
|
347
|
+
const body = await pacedFetchJson(gate, url);
|
|
348
|
+
if (body === null) return null;
|
|
349
|
+
if (isNotModified(body)) return { items: [], bytes: 0, notModified: true };
|
|
350
|
+
const changes = Array.isArray(body?.query?.recentchanges) ? body.query.recentchanges : [];
|
|
351
|
+
const origin = wikinewsArticleOrigin(record.url);
|
|
352
|
+
const raw = changes.map((c) => ({
|
|
353
|
+
guid: String(c?.pageid ?? c?.title ?? ""),
|
|
354
|
+
title: stripMarkup(c?.title || ""),
|
|
355
|
+
url: c?.title ? `${origin}/wiki/${encodeURIComponent(String(c.title).replace(/ /g, "_"))}` : "",
|
|
356
|
+
summary: "",
|
|
357
|
+
publishedAt: Number.isFinite(Date.parse(c?.timestamp)) ? new Date(c.timestamp).toISOString() : "",
|
|
358
|
+
}));
|
|
359
|
+
const items = normalizeFeedItems(record.id, raw, { now });
|
|
360
|
+
return { items, bytes: jsonByteLength(body) };
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** One source record's fetcher: `{ id, async fetchItems() -> { items, bytes,
|
|
364
|
+
* notModified? } | null }`. The gate's minIntervalMs defaults to
|
|
365
|
+
* `record.minIntervalMs` when the caller doesn't override it, so Hacker
|
|
366
|
+
* News runs at its own lower floor while every other source keeps the
|
|
367
|
+
* shared default. `validators`, when given, is the Map the caller keeps
|
|
368
|
+
* across polls (per source id, not per fetcher instance) for the
|
|
369
|
+
* conditional-request memory courtesy.mjs implements. */
|
|
370
|
+
export function createNewsFetcher(record, { fetchImpl, minIntervalMs, validators = null, now } = {}) {
|
|
371
|
+
const gate = createCourtesyGate({
|
|
372
|
+
fetchImpl,
|
|
373
|
+
minIntervalMs: minIntervalMs ?? record.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS,
|
|
374
|
+
userAgent: NEWS_USER_AGENT,
|
|
375
|
+
waitForSlot: true,
|
|
376
|
+
validators,
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
async function fetchItems() {
|
|
380
|
+
const resolvedNow = typeof now === "function" ? now() : (now ?? new Date().toISOString());
|
|
381
|
+
switch (record.format) {
|
|
382
|
+
case "rss":
|
|
383
|
+
case "atom":
|
|
384
|
+
case "jsonfeed":
|
|
385
|
+
return fetchFeedFormat(record, gate, { format: record.format, now: resolvedNow });
|
|
386
|
+
case "wikimedia-feed":
|
|
387
|
+
return fetchWikimediaFeed(record, gate, { now: resolvedNow });
|
|
388
|
+
case "hn":
|
|
389
|
+
return fetchHackerNews(record, gate, { now: resolvedNow });
|
|
390
|
+
case "usgs":
|
|
391
|
+
return fetchUsgs(record, gate, { now: resolvedNow });
|
|
392
|
+
case "mediawiki":
|
|
393
|
+
return fetchWikinews(record, gate, { now: resolvedNow });
|
|
394
|
+
default:
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
return { id: record.id, fetchItems };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** The add-by-URL preflight: https-only, one fetch, detectFeedFormat on the
|
|
403
|
+
* body. A thrown fetch (a browser's CORS rejection reads this way — the
|
|
404
|
+
* rejection carries no response to inspect) reads as "browser-blocked"; a
|
|
405
|
+
* response that resolves but is not a readable feed reads as "no-feed". A
|
|
406
|
+
* courtesy-gate slot is deliberately NOT used here: this is one user-
|
|
407
|
+
* initiated action outside the poll cadence, not a repeated fetch a
|
|
408
|
+
* throttle needs to pace. */
|
|
409
|
+
export async function preflightNewsUrl(url, { fetchImpl } = {}) {
|
|
410
|
+
const target = String(url ?? "").trim();
|
|
411
|
+
if (!target.startsWith("https://")) return { ok: false, reason: "not-https" };
|
|
412
|
+
|
|
413
|
+
const doFetch = fetchImpl ?? ((...args) => globalThis.fetch(...args));
|
|
414
|
+
const controller = typeof AbortController === "function" ? new AbortController() : null;
|
|
415
|
+
const timer = controller ? setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS) : null;
|
|
416
|
+
let res;
|
|
417
|
+
try {
|
|
418
|
+
const opts = { headers: { "User-Agent": NEWS_USER_AGENT } };
|
|
419
|
+
if (controller) opts.signal = controller.signal;
|
|
420
|
+
res = await doFetch(target, opts);
|
|
421
|
+
} catch {
|
|
422
|
+
return { ok: false, reason: "browser-blocked" };
|
|
423
|
+
} finally {
|
|
424
|
+
if (timer !== null) clearTimeout(timer);
|
|
425
|
+
}
|
|
426
|
+
if (!res || !res.ok) return { ok: false, reason: "no-feed" };
|
|
427
|
+
|
|
428
|
+
let text;
|
|
429
|
+
try {
|
|
430
|
+
text = await res.text();
|
|
431
|
+
} catch {
|
|
432
|
+
return { ok: false, reason: "no-feed" };
|
|
433
|
+
}
|
|
434
|
+
const format = detectFeedFormat(text);
|
|
435
|
+
return format ? { ok: true, format } : { ok: false, reason: "no-feed" };
|
|
436
|
+
}
|
|
@@ -119,11 +119,24 @@ export function researchSources() {
|
|
|
119
119
|
return [...sourceFactories.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
120
120
|
}
|
|
121
121
|
|
|
122
|
-
/** The config-facing choice words a user, tmct.toml or a CLI flag may name.
|
|
123
|
-
|
|
122
|
+
/** The config-facing choice words a user, tmct.toml or a CLI flag may name.
|
|
123
|
+
* "wikipedia" and "simple-wikipedia" are deliberate synonyms — both name the
|
|
124
|
+
* same registered source, "wikipedia" for backward compatibility with the
|
|
125
|
+
* original single-source config, "simple-wikipedia" so the news `kb_sources`
|
|
126
|
+
* list (news-sources.mjs) can name every source by the same id its own
|
|
127
|
+
* registry uses. */
|
|
128
|
+
export const RESEARCH_SOURCE_CHOICES = Object.freeze([
|
|
129
|
+
"wikipedia", "wikidata", "simple-wikipedia", "wiktionary", "dbpedia",
|
|
130
|
+
]);
|
|
124
131
|
export const DEFAULT_RESEARCH_SOURCE_CHOICE = "wikipedia";
|
|
125
132
|
|
|
126
|
-
const CHOICE_TO_SOURCE_NAME = Object.freeze({
|
|
133
|
+
const CHOICE_TO_SOURCE_NAME = Object.freeze({
|
|
134
|
+
wikipedia: "simple-wikipedia",
|
|
135
|
+
wikidata: "wikidata",
|
|
136
|
+
"simple-wikipedia": "simple-wikipedia",
|
|
137
|
+
wiktionary: "wiktionary",
|
|
138
|
+
dbpedia: "dbpedia-lookup",
|
|
139
|
+
});
|
|
127
140
|
|
|
128
141
|
/** The config-facing choice folded to a known one — an absent, empty or
|
|
129
142
|
* unrecognized value reads as the default. */
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// corpus/wiktionary-live.mjs — the live Wiktionary research source: one GET
|
|
2
|
+
// against en.wiktionary.org's REST definition endpoint, mapped into the
|
|
3
|
+
// shipped reference-pack article-row shape. A dictionary definition has no
|
|
4
|
+
// copula ("a heart is a...") to key off — it opens directly on the genus
|
|
5
|
+
// noun phrase ("a muscular organ that pumps blood...") — so the isa
|
|
6
|
+
// extraction here is its own small parse, not reference-pack.mjs's isaOf,
|
|
7
|
+
// which expects the sentence-with-copula shape a Wikipedia lead uses.
|
|
8
|
+
//
|
|
9
|
+
// Courtesy is structural, mirroring wikipedia-live.mjs and wikidata-live.mjs:
|
|
10
|
+
// one in-flight lookup at a time, a minimum interval between round trips, a
|
|
11
|
+
// 429 cool-off honouring Retry-After, an abort timeout on every fetch, and a
|
|
12
|
+
// cache that keeps hits AND misses so a term is never asked twice. Every
|
|
13
|
+
// failure of any kind reads as null, so the caller's honest miss stands.
|
|
14
|
+
//
|
|
15
|
+
// No node builtins — this module ships in the browser bundles unchanged; the
|
|
16
|
+
// only I/O is fetch.
|
|
17
|
+
|
|
18
|
+
import { normFactTerm } from "../../domain/hash.mjs";
|
|
19
|
+
import { stripMarkup } from "../../domain/feed-normalize.mjs";
|
|
20
|
+
import { isResearchSourceRow, registerResearchSource, researchSourceTag } from "./research-source.mjs";
|
|
21
|
+
import { createCourtesyGate, DEFAULT_TIMEOUT_MS, DEFAULT_MIN_INTERVAL_MS } from "./courtesy.mjs";
|
|
22
|
+
|
|
23
|
+
export const WIKTIONARY_LIVE_ORIGIN = "https://en.wiktionary.org";
|
|
24
|
+
export const WIKTIONARY_SOURCE_NAME = "wiktionary";
|
|
25
|
+
export const WIKTIONARY_SOURCE_LABEL = "Wiktionary";
|
|
26
|
+
export const WIKTIONARY_LICENCE = "CC BY-SA 3.0";
|
|
27
|
+
|
|
28
|
+
export const WIKTIONARY_USER_AGENT = "the-mechanical-code-talker (+https://tmct.polycode.co.uk/)";
|
|
29
|
+
|
|
30
|
+
// The definition endpoint has no revision id to cite (unlike the page-summary
|
|
31
|
+
// APIs wikipedia-live.mjs and wikidata-live.mjs read); the row shape needs a
|
|
32
|
+
// positive integer regardless, so every Wiktionary row cites this fixed
|
|
33
|
+
// placeholder rather than a real revision.
|
|
34
|
+
const NO_REVISION_ID = 1;
|
|
35
|
+
|
|
36
|
+
const GROUNDED_PARTS_OF_SPEECH = new Set(["noun", "verb"]);
|
|
37
|
+
|
|
38
|
+
/** Wiktionary's REST endpoint nests definitions by language code
|
|
39
|
+
* (`{ en: [...] }`) on the live API; a caller may also hand a flat array
|
|
40
|
+
* directly (the shape the committed test fixture uses). Both read the same
|
|
41
|
+
* way past this point. */
|
|
42
|
+
function definitionEntries(body) {
|
|
43
|
+
if (Array.isArray(body)) return body;
|
|
44
|
+
if (body && typeof body === "object") return Object.values(body).flat();
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The first English noun-or-verb sense's definition sentence, or "". */
|
|
49
|
+
function firstGroundedDefinition(body) {
|
|
50
|
+
for (const entry of definitionEntries(body)) {
|
|
51
|
+
if (entry?.language && entry.language !== "English") continue;
|
|
52
|
+
if (!GROUNDED_PARTS_OF_SPEECH.has(String(entry?.partOfSpeech ?? "").toLowerCase())) continue;
|
|
53
|
+
const definition = entry?.definitions?.[0]?.definition;
|
|
54
|
+
if (typeof definition === "string" && definition.trim()) return stripMarkup(definition);
|
|
55
|
+
}
|
|
56
|
+
return "";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Where the genus noun phrase ends: a second alternative ("a vent OR
|
|
60
|
+
// fissure..."), a relative clause, or a trailing modifier all carry detail
|
|
61
|
+
// past what the class itself is.
|
|
62
|
+
const GENUS_STOP = new Set([
|
|
63
|
+
"or", "that", "which", "who", "whose", "used", "found", "made", "with",
|
|
64
|
+
"in", "on", "for", "from", "by", "to", "and",
|
|
65
|
+
]);
|
|
66
|
+
const GENUS_WINDOW_CAP = 4;
|
|
67
|
+
|
|
68
|
+
/** The genus term a Wiktionary definition opens on: a leading "a"/"an"
|
|
69
|
+
* introduces the noun phrase, read word by word up to the first stop word,
|
|
70
|
+
* and the PHRASE'S HEAD is its last word — English noun phrases are
|
|
71
|
+
* head-final, so "a muscular organ that..." keeps "organ", not the
|
|
72
|
+
* adjective in front of it, while "a vent or fissure..." keeps "vent"
|
|
73
|
+
* because "or" stops the window at one word. Null when the definition does
|
|
74
|
+
* not open on an article at all — a verb-phrase or bare-plural definition
|
|
75
|
+
* names no single genus this parse can trust. */
|
|
76
|
+
function genusOf(definition) {
|
|
77
|
+
const m = /^(?:a|an)\s+([a-z][\w' -]*)/i.exec(String(definition ?? "").trim());
|
|
78
|
+
if (!m) return null;
|
|
79
|
+
const window = [];
|
|
80
|
+
for (const raw of m[1].split(/\s+/)) {
|
|
81
|
+
const word = raw.toLowerCase().replace(/[.,;:]+$/, "");
|
|
82
|
+
if (!word || GENUS_STOP.has(word)) break;
|
|
83
|
+
window.push(word);
|
|
84
|
+
if (window.length >= GENUS_WINDOW_CAP) break;
|
|
85
|
+
}
|
|
86
|
+
return window.length ? normFactTerm(window[window.length - 1]) : null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* A live Wiktionary research source: { name, origin, lookup(term),
|
|
91
|
+
* provenanceTag(term) } — the research-source.mjs contract.
|
|
92
|
+
*
|
|
93
|
+
* `fetchImpl` defaults to the global fetch. `waitForSlot` picks the throttle
|
|
94
|
+
* posture: false answers null the moment a slot is unavailable (never block a
|
|
95
|
+
* chat turn), true waits for it (the research queue and the news enrichment
|
|
96
|
+
* loop, both paced turn-by-turn, where a false miss would be dishonest).
|
|
97
|
+
*/
|
|
98
|
+
export function createWiktionaryLiveProvider({
|
|
99
|
+
fetchImpl,
|
|
100
|
+
origin = WIKTIONARY_LIVE_ORIGIN,
|
|
101
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
102
|
+
minIntervalMs = DEFAULT_MIN_INTERVAL_MS,
|
|
103
|
+
userAgent = WIKTIONARY_USER_AGENT,
|
|
104
|
+
waitForSlot = false,
|
|
105
|
+
sourceName = WIKTIONARY_SOURCE_NAME,
|
|
106
|
+
} = {}) {
|
|
107
|
+
const gate = createCourtesyGate({ fetchImpl, timeoutMs, minIntervalMs, userAgent, waitForSlot });
|
|
108
|
+
|
|
109
|
+
async function roundTrip(key) {
|
|
110
|
+
const body = await gate.fetchJson(
|
|
111
|
+
`${origin}/api/rest_v1/page/definition/${encodeURIComponent(key)}`,
|
|
112
|
+
);
|
|
113
|
+
if (!body) return null;
|
|
114
|
+
const definition = firstGroundedDefinition(body);
|
|
115
|
+
if (!definition) return null;
|
|
116
|
+
const row = {
|
|
117
|
+
term: key,
|
|
118
|
+
title: key,
|
|
119
|
+
text: definition,
|
|
120
|
+
summary: definition,
|
|
121
|
+
url: `${origin}/wiki/${encodeURIComponent(key.replace(/ /g, "_"))}`,
|
|
122
|
+
revid: NO_REVISION_ID,
|
|
123
|
+
source: WIKTIONARY_SOURCE_LABEL,
|
|
124
|
+
licence: WIKTIONARY_LICENCE,
|
|
125
|
+
};
|
|
126
|
+
const isa = genusOf(definition);
|
|
127
|
+
if (isa && isa !== key) row.isa = isa;
|
|
128
|
+
return isResearchSourceRow(row) ? row : null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
name: sourceName,
|
|
133
|
+
origin,
|
|
134
|
+
|
|
135
|
+
provenanceTag(term) {
|
|
136
|
+
return researchSourceTag(sourceName, term);
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
async lookup(term) {
|
|
140
|
+
const key = normFactTerm(term ?? "");
|
|
141
|
+
if (!key) return null;
|
|
142
|
+
return gate.cachedFetch(key, () => roundTrip(key));
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The Wiktionary research source with `waitForSlot` on: paced callers (the
|
|
148
|
+
* research queue, the news enrichment loop) wait for their polite slot
|
|
149
|
+
* rather than reporting a false miss. Every option the caller passes wins,
|
|
150
|
+
* so a test can hand it a stub transport and a zero interval. */
|
|
151
|
+
export function createWiktionaryResearchSource(options = {}) {
|
|
152
|
+
return createWiktionaryLiveProvider({ waitForSlot: true, ...options });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
registerResearchSource({
|
|
156
|
+
name: WIKTIONARY_SOURCE_NAME,
|
|
157
|
+
create: createWiktionaryResearchSource,
|
|
158
|
+
});
|