@polycode-projects/the-mechanical-code-talker 5.0.26 → 5.0.28
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/corpus/worlds/index.json.gz +0 -0
- package/corpus/worlds/manifest.json +27 -17
- package/corpus/worlds/shards/river-crossing.jsonl.gz +0 -0
- package/corpus/worlds/shards/town-square-chapel.jsonl.gz +0 -0
- package/corpus/worlds/shards/town-square-market.jsonl.gz +0 -0
- package/corpus/worlds/shards/town-square.jsonl.gz +0 -0
- package/corpus/worlds/src/river-crossing.jsonl +29 -0
- package/corpus/worlds/src/town-square-chapel.jsonl +12 -8
- package/corpus/worlds/src/town-square-market.jsonl +12 -8
- package/corpus/worlds/src/town-square.jsonl +12 -8
- package/package.json +2 -1
- package/src/adapters/memory/inspect.mjs +37 -0
- package/src/domain/agent-traits.mjs +282 -0
- package/src/domain/ask.mjs +19 -6
- package/src/domain/choice-question.mjs +135 -6
- package/src/domain/codegraph.mjs +8 -1
- package/src/domain/el-classify.mjs +39 -7
- package/src/domain/fact-phrase.mjs +7 -4
- package/src/domain/interpret/normalize.mjs +58 -2
- package/src/domain/town-square-world.mjs +44 -19
- package/src/services/adventure.mjs +5 -16
- package/src/services/agent-editor.mjs +216 -0
- package/src/services/chat-session.mjs +26 -5
- package/src/services/chat.mjs +221 -58
- package/src/services/mudiii-scene.mjs +32 -5
- package/src/services/mudiii-turn.mjs +7 -3
- package/src/services/mudiii-viz.mjs +215 -1
- package/src/services/news-viz.mjs +489 -0
- package/src/services/predator-prey.mjs +157 -24
- package/src/surfaces/web/chat-browser-entry.mjs +69 -3
- package/src/surfaces/web/memory-ask-browser.bundle.js +155 -155
- package/src/surfaces/web/mudiii-browser-entry.mjs +35 -0
- package/src/surfaces/web/news-browser-entry.mjs +384 -0
- package/src/surfaces/web/turn-session.mjs +13 -9
|
@@ -19,6 +19,10 @@ import {
|
|
|
19
19
|
import { findActionPath } from "../../domain/planning.mjs";
|
|
20
20
|
import { DEFAULT_GAME_CONFIG } from "../../domain/game-config.mjs";
|
|
21
21
|
import { parseMudEditorText, planMudEditorSync, gridWorldEditorState } from "../../services/mud-editor.mjs";
|
|
22
|
+
import {
|
|
23
|
+
parseAgentEditorText, planAgentEditorSync, renderAgentEditorText, renderAgentClassText,
|
|
24
|
+
} from "../../services/agent-editor.mjs";
|
|
25
|
+
import { agentTraitsOf } from "../../domain/agent-traits.mjs";
|
|
22
26
|
import { pillsForMudiii } from "../../services/mudiii-turn.mjs";
|
|
23
27
|
import { relatedForTerm } from "../../domain/skos-view.mjs";
|
|
24
28
|
import { classAncestorChain } from "../../domain/sprite-map.mjs";
|
|
@@ -305,6 +309,29 @@ export async function createMudiiiSession(
|
|
|
305
309
|
return engPlaceFood(memoryDir, { layout, ...opts });
|
|
306
310
|
}
|
|
307
311
|
|
|
312
|
+
/** The actor card's own store sync — agent-editor.mjs's closed table,
|
|
313
|
+
* disjoint from `applyEdit`'s world table. `subject` is whichever id the
|
|
314
|
+
* card is scoped to when this is called: an instance id on the "this
|
|
315
|
+
* goblin" tab, the class name itself on the "all goblins" tab — either
|
|
316
|
+
* way `planAgentEditorSync` only ever reads and writes rows whose own
|
|
317
|
+
* subject is that one id, so an actor edit can reach no instance, no
|
|
318
|
+
* class and no placement it was not asked to touch. Never calls
|
|
319
|
+
* `recast`: a trait is not where anything stands. */
|
|
320
|
+
async function applyAgentEdit(subject, text) {
|
|
321
|
+
const rows = readFactRows(await loadMemory(memoryDir));
|
|
322
|
+
const { triples, unrecognized } = parseAgentEditorText(text);
|
|
323
|
+
const { toAppend, toRemoveIds } = planAgentEditorSync(rows, subject, triples);
|
|
324
|
+
if (toAppend.length) {
|
|
325
|
+
await appendFacts(memoryDir, toAppend.map((f) => ({
|
|
326
|
+
subject: f.subject, predicate: f.predicate, object: f.object, provenance: `actor-edit:${subject}`,
|
|
327
|
+
})));
|
|
328
|
+
}
|
|
329
|
+
const removed = unrecognized.length === 0 && toRemoveIds.length
|
|
330
|
+
? (await removeFacts(memoryDir, toRemoveIds)).removed.length
|
|
331
|
+
: 0;
|
|
332
|
+
return { unrecognized, added: toAppend.length, removed };
|
|
333
|
+
}
|
|
334
|
+
|
|
308
335
|
return {
|
|
309
336
|
memoryDir,
|
|
310
337
|
codeGraph,
|
|
@@ -317,6 +344,7 @@ export async function createMudiiiSession(
|
|
|
317
344
|
board,
|
|
318
345
|
snapshot,
|
|
319
346
|
applyEdit,
|
|
347
|
+
applyAgentEdit,
|
|
320
348
|
placeFood,
|
|
321
349
|
};
|
|
322
350
|
}
|
|
@@ -340,5 +368,12 @@ publishTmctSurface({
|
|
|
340
368
|
// cursor: the lateral SKOS neighbourhood and the vertical is-a chain.
|
|
341
369
|
relatedForTerm, classAncestorChain,
|
|
342
370
|
routeBetweenCells,
|
|
371
|
+
// What the page's scene boot reads to resolve each agent's stated
|
|
372
|
+
// display name and model off the rows, class chain included.
|
|
373
|
+
agentTraitsOf,
|
|
374
|
+
// The actor card's own render half — agent-editor.mjs leans on
|
|
375
|
+
// agent-traits.mjs's class-chain walk, so (like agentTraitsOf) it
|
|
376
|
+
// reaches the page through this bag rather than a `.toString()` splice.
|
|
377
|
+
renderAgentEditorText, renderAgentClassText,
|
|
343
378
|
},
|
|
344
379
|
});
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// news-browser-entry.mjs — the esbuild entry for news.html's engine
|
|
2
|
+
// (public/news-browser.bundle.js, built by scripts/build-news-bundle.mjs).
|
|
3
|
+
//
|
|
4
|
+
// news.html is the scheduled-ingestion demo: one in-memory Backend-B store,
|
|
5
|
+
// seeded from chat-seed.json exactly as chat.html and research.html are,
|
|
6
|
+
// that then grows through the news capability (src/services/news.mjs) —
|
|
7
|
+
// polling contemporary sources, ranking what does not ground, walking
|
|
8
|
+
// knowledge-base sources to close the gap, and building the fact-churn feed —
|
|
9
|
+
// all over the SAME library contract the CLI's `tmct news` verb runs.
|
|
10
|
+
//
|
|
11
|
+
// The one rule every method below honours: NOTHING here calls a fetcher
|
|
12
|
+
// before `start()` (or a returning visit's own `start()` replay) is called.
|
|
13
|
+
// `poll()`/`enrich()` are consent-gated the same way; `addSource()` performs
|
|
14
|
+
// its own one-off preflight fetch because pasting a URL and pressing "add" is
|
|
15
|
+
// itself the explicit action authorising that one request; `replayFixture()`
|
|
16
|
+
// never touches the network at all — it re-runs the exact ingest pipeline
|
|
17
|
+
// over an already-downloaded fixture body.
|
|
18
|
+
//
|
|
19
|
+
// The start-consent PREFERENCE (which localStorage key, and whether to persist
|
|
20
|
+
// at all) is a page concern, not this session's — the same split
|
|
21
|
+
// chat-page-viz.mjs's own WIKI_MODE_KEY draws between the page's own storage
|
|
22
|
+
// and chat-browser-entry.mjs's pure session. `prefs` here defaults to a real
|
|
23
|
+
// localStorage-backed store when one exists (so a caller doing nothing extra
|
|
24
|
+
// still gets persistence), and is fully injectable for tests, which never
|
|
25
|
+
// touch a real browser storage API.
|
|
26
|
+
//
|
|
27
|
+
// Gitignored, Pages-demo-site-only output — scripts/build-demo-site.mjs will
|
|
28
|
+
// build it fresh on every deploy once news.html joins DEMO_PAGES (a later
|
|
29
|
+
// round), never committed, the same posture every sibling *-browser-entry.mjs
|
|
30
|
+
// documents for its own output.
|
|
31
|
+
|
|
32
|
+
import { createInMemoryStore, applySeedPayload, loadMemory, readFactRows, appendFacts, removeFacts, normFactTerm, normFactPredicate } from "../../adapters/memory/core.mjs";
|
|
33
|
+
import { factIdFor } from "../../domain/hash.mjs";
|
|
34
|
+
import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
|
|
35
|
+
import { ingestText } from "../../services/extract-facts.mjs";
|
|
36
|
+
import {
|
|
37
|
+
resolveNewsConfig, createNewsState, pollNewsSources, enrichTopTerms, buildFeed,
|
|
38
|
+
ingestUploadedFactRows, isVocabGroundedTerm,
|
|
39
|
+
} from "../../services/news.mjs";
|
|
40
|
+
import { rankedTerms, ledgerFromPayload, bumpTerms, ledgerPayload } from "../../domain/term-ledger.mjs";
|
|
41
|
+
import {
|
|
42
|
+
newsSourceRecords, normalizeNewsSourceIds, createNewsFetcher, preflightNewsUrl, registerNewsSource,
|
|
43
|
+
} from "../../adapters/corpus/news-sources.mjs";
|
|
44
|
+
import { detectFeedFormat, parseFeed, normalizeFeedItems, stripMarkup } from "../../domain/feed-normalize.mjs";
|
|
45
|
+
import { DEFAULT_MIN_INTERVAL_MS } from "../../adapters/corpus/courtesy.mjs";
|
|
46
|
+
import { getResearchProvider } from "../../adapters/corpus/wikipedia-live.mjs";
|
|
47
|
+
import { registerWinkModel } from "../../adapters/wink-model.mjs";
|
|
48
|
+
import { openPersistedStore } from "./idb-persist.mjs";
|
|
49
|
+
import { publishTmctSurface } from "./tmct-surface.mjs";
|
|
50
|
+
|
|
51
|
+
/** The localStorage key the shipped page persists start-consent under —
|
|
52
|
+
* exported so the page's own inline script and a test can both name it
|
|
53
|
+
* without retyping the string. */
|
|
54
|
+
export const NEWS_START_PREF_KEY = "tmct.news.started";
|
|
55
|
+
|
|
56
|
+
function localStoragePrefStore() {
|
|
57
|
+
return {
|
|
58
|
+
get(key) { try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; } },
|
|
59
|
+
set(key, value) { try { globalThis.localStorage?.setItem(key, value); } catch { /* private mode — this visit still works */ } },
|
|
60
|
+
remove(key) { try { globalThis.localStorage?.removeItem(key); } catch { /* already gone */ } },
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** An in-memory stand-in for localStorage, used when no real one exists
|
|
65
|
+
* (every Node test, and any browser context with storage denied). */
|
|
66
|
+
function memoryPrefStore() {
|
|
67
|
+
const map = new Map();
|
|
68
|
+
return {
|
|
69
|
+
get: (key) => (map.has(key) ? map.get(key) : null),
|
|
70
|
+
set: (key, value) => { map.set(key, value); },
|
|
71
|
+
remove: (key) => { map.delete(key); },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function resolveNowMs() {
|
|
76
|
+
return Date.now();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isoNow() {
|
|
80
|
+
return new Date().toISOString();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const POLL_FLOOR_MINUTES = 5;
|
|
84
|
+
|
|
85
|
+
function clampPollMinutesLocal(n) {
|
|
86
|
+
const v = Number(n);
|
|
87
|
+
if (!Number.isFinite(v)) return POLL_FLOOR_MINUTES;
|
|
88
|
+
const floored = Math.max(0, Math.floor(v));
|
|
89
|
+
return floored === 0 ? 0 : Math.max(POLL_FLOOR_MINUTES, floored);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The wikimedia-feed body shape (`{ news: [...] }` or `{ mostread: {
|
|
93
|
+
* articles: [...] } }`) turned into the same raw-item shape
|
|
94
|
+
* createNewsFetcher's own network path builds — the pure half of that
|
|
95
|
+
* adapter's private fetchWikimediaFeed, restated here because a fixture
|
|
96
|
+
* replay never calls the network wrapper that owns it. Kept intentionally
|
|
97
|
+
* small: only the mapping a fixture-replay demo button needs, never the
|
|
98
|
+
* courtesy-gated fetch itself. */
|
|
99
|
+
function wikimediaFixtureRawItems(body) {
|
|
100
|
+
const articles = Array.isArray(body?.news)
|
|
101
|
+
? body.news.flatMap((story) => (Array.isArray(story?.links) ? story.links : []))
|
|
102
|
+
: Array.isArray(body?.mostread?.articles)
|
|
103
|
+
? body.mostread.articles
|
|
104
|
+
: [];
|
|
105
|
+
return articles.map((a) => ({
|
|
106
|
+
guid: a?.wikibase_item || a?.normalizedtitle || a?.title || "",
|
|
107
|
+
title: stripMarkup(a?.normalizedtitle || a?.displaytitle || a?.title || ""),
|
|
108
|
+
url: a?.content_urls?.desktop?.page || "",
|
|
109
|
+
summary: stripMarkup(a?.extract || ""),
|
|
110
|
+
publishedAt: "",
|
|
111
|
+
}));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** A fixture body's raw items, for whichever wire shape the demo buttons
|
|
115
|
+
* ship: `format` names it explicitly so this never has to guess. */
|
|
116
|
+
function fixtureRawItems(format, body) {
|
|
117
|
+
if (format === "wikimedia-feed") return wikimediaFixtureRawItems(body);
|
|
118
|
+
return parseFeed(body, { format });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The graph-growing session over the real news capability (news.mjs), pure
|
|
123
|
+
* except for the fetches `start()`/`poll()`/`enrich()`/`addSource()`
|
|
124
|
+
* themselves trigger — every one of them consent-gated, `addSource()` by its
|
|
125
|
+
* own one-off preflight rather than the poll cycle's consent.
|
|
126
|
+
*
|
|
127
|
+
* Returns `{ memoryDir, phase, consented, metrics, nextPollAt, config,
|
|
128
|
+
* requestLog, health, start, poll, enrich, buildFeed, rank, addSource,
|
|
129
|
+
* setInterval, ingestText, ingestFile, replayFixture, revokeConsent,
|
|
130
|
+
* destroy }`.
|
|
131
|
+
*/
|
|
132
|
+
export function createNewsSession({
|
|
133
|
+
seedPayload = null, vocabSeeded = false, fetchImpl = null, now = isoNow,
|
|
134
|
+
prefs = null, prefKey = NEWS_START_PREF_KEY,
|
|
135
|
+
} = {}) {
|
|
136
|
+
const memoryDir = createInMemoryStore();
|
|
137
|
+
applySeedPayload(memoryDir, seedPayload);
|
|
138
|
+
|
|
139
|
+
const store = { loadMemory, readFactRows, appendFacts, removeFacts };
|
|
140
|
+
const cache = { rows: null };
|
|
141
|
+
let lexicon = loadLexicon();
|
|
142
|
+
let config = resolveNewsConfig();
|
|
143
|
+
const state = createNewsState();
|
|
144
|
+
const doFetch = fetchImpl || ((...args) => globalThis.fetch(...args));
|
|
145
|
+
|
|
146
|
+
const prefStore = prefs || (typeof globalThis !== "undefined" && globalThis.localStorage ? localStoragePrefStore() : memoryPrefStore());
|
|
147
|
+
let consented = prefStore.get(prefKey) === "on";
|
|
148
|
+
|
|
149
|
+
let phase = "seeded"; // the page-level "seeding" state (S0) precedes this session existing at all
|
|
150
|
+
let timer = null;
|
|
151
|
+
const bootMs = resolveNowMs();
|
|
152
|
+
const metrics = { timeToFirstArticleMs: null, timeToFirstCompletePollMs: null };
|
|
153
|
+
let nextPollAt = "";
|
|
154
|
+
|
|
155
|
+
const validators = new Map();
|
|
156
|
+
const fetchersById = new Map();
|
|
157
|
+
function rebuildFetchers() {
|
|
158
|
+
fetchersById.clear();
|
|
159
|
+
for (const id of normalizeNewsSourceIds(config.sources)) {
|
|
160
|
+
const record = newsSourceRecords().find((r) => r.id === id);
|
|
161
|
+
if (!record) continue;
|
|
162
|
+
fetchersById.set(id, createNewsFetcher(record, { fetchImpl: doFetch, validators, now }));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
rebuildFetchers();
|
|
166
|
+
|
|
167
|
+
const providers = {
|
|
168
|
+
newsFetchers: fetchersById,
|
|
169
|
+
getResearchProvider: ({ source } = {}) => getResearchProvider({ source }),
|
|
170
|
+
preflightNewsUrl: (url) => preflightNewsUrl(url, { fetchImpl: doFetch }),
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
function ctx() {
|
|
174
|
+
return { memoryDir, store, cache, lexicon, config, state, providers, now };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function clearTimer() {
|
|
178
|
+
if (timer !== null) { clearTimeout(timer); timer = null; }
|
|
179
|
+
nextPollAt = "";
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function armTimer() {
|
|
183
|
+
clearTimer();
|
|
184
|
+
if (!consented || !config.pollMinutes) return;
|
|
185
|
+
const delayMs = config.pollMinutes * 60000;
|
|
186
|
+
nextPollAt = new Date(resolveNowMs() + delayMs).toISOString();
|
|
187
|
+
timer = setTimeout(() => { runPollCycle().then(runEnrichCycle).catch(() => {}); }, delayMs);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function noteFirstArticle() {
|
|
191
|
+
if (metrics.timeToFirstArticleMs !== null) return;
|
|
192
|
+
const feed = await buildFeed(ctx());
|
|
193
|
+
if (feed.items.length) metrics.timeToFirstArticleMs = resolveNowMs() - bootMs;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function runPollCycle() {
|
|
197
|
+
phase = "polling";
|
|
198
|
+
const result = await pollNewsSources(ctx());
|
|
199
|
+
if (metrics.timeToFirstCompletePollMs === null) metrics.timeToFirstCompletePollMs = resolveNowMs() - bootMs;
|
|
200
|
+
phase = "grounding";
|
|
201
|
+
await noteFirstArticle();
|
|
202
|
+
return result;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function runEnrichCycle() {
|
|
206
|
+
phase = "enriching";
|
|
207
|
+
const result = await enrichTopTerms(ctx());
|
|
208
|
+
phase = "idle";
|
|
209
|
+
armTimer();
|
|
210
|
+
return result;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
memoryDir,
|
|
215
|
+
get phase() { return phase; },
|
|
216
|
+
get consented() { return consented; },
|
|
217
|
+
get metrics() { return { ...metrics }; },
|
|
218
|
+
get nextPollAt() { return nextPollAt; },
|
|
219
|
+
get config() { return { ...config }; },
|
|
220
|
+
get requestLog() { return state.requestLog; },
|
|
221
|
+
get health() { return state.health; },
|
|
222
|
+
|
|
223
|
+
/** First run: records the start-consent preference. Every run (first or
|
|
224
|
+
* a returning visit's own replay): one poll cycle, then one enrich
|
|
225
|
+
* cycle, then the timer arms for the next one — "poll on load" for a
|
|
226
|
+
* returning visit is exactly this same call. */
|
|
227
|
+
async start() {
|
|
228
|
+
consented = true;
|
|
229
|
+
prefStore.set(prefKey, "on");
|
|
230
|
+
const pollResult = await runPollCycle();
|
|
231
|
+
const enrichResult = await runEnrichCycle();
|
|
232
|
+
return { poll: pollResult, enrich: enrichResult };
|
|
233
|
+
},
|
|
234
|
+
|
|
235
|
+
/** A manual "poll now" — still consent-gated: never fires before
|
|
236
|
+
* start() has run at least once this session. */
|
|
237
|
+
async poll() {
|
|
238
|
+
if (!consented) return { fetched: 0, newItems: 0, failures: 0, evicted: 0, facts: 0, derived: 0, sources: [] };
|
|
239
|
+
return runPollCycle();
|
|
240
|
+
},
|
|
241
|
+
|
|
242
|
+
/** A manual "enrich now" — same consent gate as poll(). */
|
|
243
|
+
async enrich() {
|
|
244
|
+
if (!consented) return { enriched: [], missed: [], facts: 0, derived: 0 };
|
|
245
|
+
return runEnrichCycle();
|
|
246
|
+
},
|
|
247
|
+
|
|
248
|
+
async buildFeed() { return buildFeed(ctx()); },
|
|
249
|
+
|
|
250
|
+
/** The fact rows behind a set of ids — a feed item's own `factIds`,
|
|
251
|
+
* expanded so the page's `<details>` fact list can show each one as a
|
|
252
|
+
* sentence and, nested under it, the raw triple record. */
|
|
253
|
+
async factRows(ids) {
|
|
254
|
+
const wanted = new Set(ids || []);
|
|
255
|
+
if (!wanted.size) return [];
|
|
256
|
+
const memory = await store.loadMemory(memoryDir);
|
|
257
|
+
return store.readFactRows(memory).filter((r) => wanted.has(r.id));
|
|
258
|
+
},
|
|
259
|
+
|
|
260
|
+
async rank({ limit = 20 } = {}) {
|
|
261
|
+
const nowVal = typeof now === "function" ? now() : now;
|
|
262
|
+
const ledger = ledgerFromPayload(state.ledger);
|
|
263
|
+
return rankedTerms(ledger, { limit, now: nowVal, ttlMs: config.negativeCacheTtlHours * 3600000 });
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
/** Add-by-URL: its own one-off preflight fetch, independent of the poll
|
|
267
|
+
* cycle's start()-gated consent — pasting a URL and pressing "add" IS
|
|
268
|
+
* the explicit action authorising that one request. */
|
|
269
|
+
async addSource(url) {
|
|
270
|
+
const result = await preflightNewsUrl(url, { fetchImpl: doFetch });
|
|
271
|
+
if (!result.ok) return { ok: false, reason: result.reason };
|
|
272
|
+
const id = `custom:${normFactTerm(url)}`;
|
|
273
|
+
registerNewsSource({
|
|
274
|
+
id, name: url, kind: "contemporary", format: result.format, url, homepage: url,
|
|
275
|
+
licence: "unknown", browserVerified: "", minIntervalMs: DEFAULT_MIN_INTERVAL_MS, enabledByDefault: false,
|
|
276
|
+
});
|
|
277
|
+
config.sources = normalizeNewsSourceIds([...config.sources, id]);
|
|
278
|
+
rebuildFetchers();
|
|
279
|
+
return { ok: true, id, format: result.format };
|
|
280
|
+
},
|
|
281
|
+
|
|
282
|
+
/** Re-arms the poll timer at `minutes`, clamped to the same floor the
|
|
283
|
+
* service config enforces (0 disarms). */
|
|
284
|
+
setInterval(minutes) {
|
|
285
|
+
config.pollMinutes = clampPollMinutesLocal(minutes);
|
|
286
|
+
armTimer();
|
|
287
|
+
return config.pollMinutes;
|
|
288
|
+
},
|
|
289
|
+
|
|
290
|
+
/** The teach panel's free-text path: prose ingested under this upload's
|
|
291
|
+
* own teach tag, the same tier a typed teach turn earns. */
|
|
292
|
+
async ingestText(text, { fileLabel = "free-text" } = {}) {
|
|
293
|
+
const nowVal = typeof now === "function" ? now() : now;
|
|
294
|
+
const sourceTag = `teach:upload:${fileLabel}@${nowVal}`;
|
|
295
|
+
const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon });
|
|
296
|
+
cache.rows = null;
|
|
297
|
+
return { facts: result.extracted.length + result.optimistic.length, sentences: result.sentences };
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
/** One uploaded file, routed by its own kind: `.txt`/`.md` prose through
|
|
301
|
+
* the same free-text path as ingestText; `.json` (a lexicon-core-shaped
|
|
302
|
+
* extra vocabulary) widens this session's own lexicon so later
|
|
303
|
+
* grounding can resolve terms it could not before; `.jsonl` (fact rows)
|
|
304
|
+
* through ingestUploadedFactRows's validate-and-downgrade before they
|
|
305
|
+
* land, so an uploaded row can never claim trust it did not earn. */
|
|
306
|
+
async ingestFile({ name, text, kind } = {}) {
|
|
307
|
+
const nowVal = typeof now === "function" ? now() : now;
|
|
308
|
+
const resolvedKind = kind || (/\.jsonl$/i.test(name || "") ? "jsonl" : /\.json$/i.test(name || "") ? "json" : "prose");
|
|
309
|
+
if (resolvedKind === "prose") {
|
|
310
|
+
return this.ingestText(text, { fileLabel: name || "upload" });
|
|
311
|
+
}
|
|
312
|
+
if (resolvedKind === "json") {
|
|
313
|
+
let extra;
|
|
314
|
+
try { extra = JSON.parse(text); } catch { return { facts: 0, vocabAdded: 0, error: "not valid JSON" }; }
|
|
315
|
+
lexicon = loadLexicon(extra);
|
|
316
|
+
return { facts: 0, vocabAdded: (extra?.nouns ? Object.keys(extra.nouns).length : 0), error: null };
|
|
317
|
+
}
|
|
318
|
+
// jsonl: one fact row per non-empty line.
|
|
319
|
+
const rows = [];
|
|
320
|
+
for (const line of String(text || "").split("\n")) {
|
|
321
|
+
const trimmed = line.trim();
|
|
322
|
+
if (!trimmed) continue;
|
|
323
|
+
try { rows.push(JSON.parse(trimmed)); } catch { /* an unparseable line is skipped, never thrown */ }
|
|
324
|
+
}
|
|
325
|
+
const downgraded = ingestUploadedFactRows(rows, { fileLabel: name || "upload", now: nowVal })
|
|
326
|
+
.filter((r) => r.subject && r.predicate && r.object);
|
|
327
|
+
if (downgraded.length) { await appendFacts(memoryDir, downgraded); cache.rows = null; }
|
|
328
|
+
return { facts: downgraded.length, vocabAdded: 0, error: null };
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
/** Replays a committed fixture's raw wire body through the exact live
|
|
332
|
+
* parse -> ingest pipeline, under `news-fixture:<sourceId>@<itemId>`
|
|
333
|
+
* provenance (the corpus-tier demo path) rather than `news:` — never a
|
|
334
|
+
* network call, so it works with the network fully blocked. */
|
|
335
|
+
async replayFixture(sourceId, { format, body } = {}) {
|
|
336
|
+
const nowVal = typeof now === "function" ? now() : now;
|
|
337
|
+
const raw = fixtureRawItems(format, body);
|
|
338
|
+
const items = normalizeFeedItems(sourceId, raw, { now: nowVal });
|
|
339
|
+
let factsTotal = 0;
|
|
340
|
+
for (const snapshot of items) {
|
|
341
|
+
const text = [snapshot.title, snapshot.summary].filter(Boolean).join(". ");
|
|
342
|
+
const sourceTag = `news-fixture:${sourceId}@${snapshot.id}`;
|
|
343
|
+
const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon });
|
|
344
|
+
const allFacts = [...result.extracted, ...result.optimistic];
|
|
345
|
+
snapshot.factIds = allFacts.map((f) => factIdFor(normFactTerm(f.subject), normFactPredicate(f.predicate), normFactTerm(f.object)));
|
|
346
|
+
factsTotal += allFacts.length;
|
|
347
|
+
|
|
348
|
+
const vocabGroundedByTerm = new Map();
|
|
349
|
+
for (const term of result.ungroundedCounts.keys()) vocabGroundedByTerm.set(term, isVocabGroundedTerm(lexicon, term));
|
|
350
|
+
const ledger = ledgerFromPayload(state.ledger);
|
|
351
|
+
bumpTerms(ledger, result.ungroundedCounts, snapshot.id, nowVal, vocabGroundedByTerm);
|
|
352
|
+
state.ledger = ledgerPayload(ledger);
|
|
353
|
+
}
|
|
354
|
+
if (factsTotal) cache.rows = null;
|
|
355
|
+
const existingIds = new Set(state.items.map((s) => s.id));
|
|
356
|
+
state.items = [...state.items, ...items.filter((s) => !existingIds.has(s.id))];
|
|
357
|
+
await noteFirstArticle();
|
|
358
|
+
return { items: items.length, facts: factsTotal };
|
|
359
|
+
},
|
|
360
|
+
|
|
361
|
+
/** Clears the start-consent preference and stops the timer — the next
|
|
362
|
+
* load of this page reads back as first-visit, exactly as if start()
|
|
363
|
+
* had never been pressed. */
|
|
364
|
+
revokeConsent() {
|
|
365
|
+
consented = false;
|
|
366
|
+
prefStore.remove(prefKey);
|
|
367
|
+
clearTimer();
|
|
368
|
+
phase = "seeded";
|
|
369
|
+
},
|
|
370
|
+
|
|
371
|
+
/** Stops the poll timer without touching consent — a test's own
|
|
372
|
+
* teardown, and a page's own unload hook. */
|
|
373
|
+
destroy() { clearTimer(); },
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
publishTmctSurface({
|
|
378
|
+
open: createNewsSession,
|
|
379
|
+
page: {
|
|
380
|
+
NEWS_START_PREF_KEY,
|
|
381
|
+
registerWinkModel, openPersistedStore, normFactTerm,
|
|
382
|
+
newsSourceRecords, detectFeedFormat,
|
|
383
|
+
},
|
|
384
|
+
});
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// entry.mjs, ledger-browser-entry.mjs, adventure-browser-entry.mjs, spider-
|
|
4
4
|
// fly-browser-entry.mjs, plan-browser-entry.mjs, research-browser-entry.mjs,
|
|
5
5
|
// mud-browser-entry.mjs, sprites-browser-entry.mjs): a closure over
|
|
6
|
-
// focus/last/planState/researchState, a `try { runTurn(...) } catch` that
|
|
6
|
+
// focus/last/planState/researchState/newsState, a `try { runTurn(...) } catch` that
|
|
7
7
|
// turns a throw into a safe answer instead of ending the session (the page
|
|
8
8
|
// has no other chance to show that turn's reply), the post-call state
|
|
9
9
|
// capture, and a return shape covering every field one caller or another
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
// The nine differ in what they hand `runTurn` beyond the common core
|
|
20
20
|
// (`synthesisBudget`, `gameConfig`, `researchConfig`,
|
|
21
21
|
// `actingSubject`, a per-character `sessionId`...) and in what they do with a
|
|
22
|
-
// turn's result besides the standard focus/last/planState/researchState fold
|
|
22
|
+
// turn's result besides the standard focus/last/planState/researchState/newsState fold
|
|
23
23
|
// (sync an externally-held plan holder, grow a visited-rooms set, bump a
|
|
24
24
|
// per-character turn tally). `buildExtraOptions`/`captureExtraState` below
|
|
25
25
|
// are exactly those two seams — everything else is common enough to live
|
|
@@ -40,7 +40,7 @@ function turnErrorFallback(message) {
|
|
|
40
40
|
* `createTurnSession({ memoryDir, graph, lexicon, sessionId, vocabHint,
|
|
41
41
|
* buildExtraOptions, captureExtraState })` — a live turn-dispatch session
|
|
42
42
|
* over the real engine (`runTurn`), threading focus/last/planState/
|
|
43
|
-
* researchState across calls the way every browser chat dock does.
|
|
43
|
+
* researchState/newsState across calls the way every browser chat dock does.
|
|
44
44
|
*
|
|
45
45
|
* `vocabHint` is the session-lifetime hint every caller computes once at
|
|
46
46
|
* creation (a fixed string, or `vocabExampleHint(vocabSeeded)`'s result) —
|
|
@@ -51,19 +51,19 @@ function turnErrorFallback(message) {
|
|
|
51
51
|
* (`synthesisBudget`, `gameConfig`, `researchConfig`,
|
|
52
52
|
* a per-character `actingSubject`/`sessionId`, or a `planState` read from an
|
|
53
53
|
* external holder instead of this closure's own). `state` is
|
|
54
|
-
* `{ focus, last, planState, researchState }` as this turn is about to run;
|
|
54
|
+
* `{ focus, last, planState, researchState, newsState }` as this turn is about to run;
|
|
55
55
|
* `callArgs` is whatever extra argument `turn(line, callArgs)` was given
|
|
56
56
|
* (plan-browser-entry.mjs's own per-call `{ maxDepth }` override, for one).
|
|
57
57
|
*
|
|
58
58
|
* `captureExtraState(result, state, callArgs)` (optional, may be async) runs
|
|
59
59
|
* once after a SUCCESSFUL turn, with `state` already folded forward
|
|
60
|
-
* (focus/last/planState/researchState updated) — the caller's own chance to
|
|
60
|
+
* (focus/last/planState/researchState/newsState updated) — the caller's own chance to
|
|
61
61
|
* do further bookkeeping (sync an external plan holder, reload memory to
|
|
62
62
|
* grow a visited-rooms set, bump a turn tally). Never runs on a throw: none
|
|
63
63
|
* of the nine originals touch their own state when `runTurn` itself failed.
|
|
64
64
|
*
|
|
65
65
|
* Returns `{ memoryDir, sessionId, graph, turn, focus, last, planState,
|
|
66
|
-
* setPlanState, researchState, setResearchState }`. `graph` is the one this
|
|
66
|
+
* setPlanState, researchState, setResearchState, newsState, setNewsState }`. `graph` is the one this
|
|
67
67
|
* session was built over, exposed so a caller can put a question to the same
|
|
68
68
|
* graph its turns run against (engine-surface.mjs's `graphAsk`) without
|
|
69
69
|
* holding a second reference to it. `turn(line, callArgs)`
|
|
@@ -87,15 +87,16 @@ export function createTurnSession({
|
|
|
87
87
|
let last = null;
|
|
88
88
|
let planState = null;
|
|
89
89
|
let researchState = null;
|
|
90
|
+
let newsState = null;
|
|
90
91
|
|
|
91
92
|
async function turn(line, callArgs) {
|
|
92
|
-
const before = { focus, last, planState, researchState };
|
|
93
|
+
const before = { focus, last, planState, researchState, newsState };
|
|
93
94
|
const extra = buildExtraOptions(before, callArgs) || {};
|
|
94
95
|
let result;
|
|
95
96
|
try {
|
|
96
97
|
result = await runTurn(line, {
|
|
97
98
|
config: null, source: null, graph, focus, last, memoryDir, sessionId,
|
|
98
|
-
env: {}, lexicon, vocabHint, planState, researchState, uiContext: "browser",
|
|
99
|
+
env: {}, lexicon, vocabHint, planState, researchState, newsState, uiContext: "browser",
|
|
99
100
|
...extra,
|
|
100
101
|
});
|
|
101
102
|
} catch (e) {
|
|
@@ -106,7 +107,8 @@ export function createTurnSession({
|
|
|
106
107
|
last = result.last;
|
|
107
108
|
if ("planState" in result) planState = result.planState;
|
|
108
109
|
if ("researchState" in result) researchState = result.researchState;
|
|
109
|
-
|
|
110
|
+
if ("newsState" in result) newsState = result.newsState;
|
|
111
|
+
await captureExtraState(result, { focus, last, planState, researchState, newsState }, callArgs);
|
|
110
112
|
return {
|
|
111
113
|
answer: result.answer,
|
|
112
114
|
end: Boolean(result.end),
|
|
@@ -126,6 +128,8 @@ export function createTurnSession({
|
|
|
126
128
|
setPlanState(next) { planState = next; },
|
|
127
129
|
get researchState() { return researchState; },
|
|
128
130
|
setResearchState(next) { researchState = next; },
|
|
131
|
+
get newsState() { return newsState; },
|
|
132
|
+
setNewsState(next) { newsState = next; },
|
|
129
133
|
turn,
|
|
130
134
|
};
|
|
131
135
|
}
|