dsh-dot-life 0.23.2 → 0.23.3
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.en.md +71 -44
- package/README.md +115 -64
- package/docs/DESIGN.md +42 -0
- package/docs/DOT-PAGE.md +9 -0
- package/docs/SETTINGS.md +4 -0
- package/docs/prompts.md +1 -1
- package/docs/qq.md +2 -0
- package/package.json +1 -1
- package/scripts/prompts.mjs +3 -3
- package/src/dot/core.js +138 -17
- package/src/interlude/core.js +116 -44
- package/src/llm-gate.js +58 -4
- package/src/memory/memory.js +23 -5
- package/src/page/api.js +10 -1
- package/src/page/page.js +29 -2
- package/src/prompts/dot.owner-words.txt +1 -0
- package/src/prompts/dot.owner-words.unsent.txt +3 -0
- package/src/prompts/interlude.round.not-kept.txt +1 -0
- package/src/prompts/interlude.round.refresh.txt +1 -1
- package/src/prompts/interlude.round.txt +3 -2
- package/src/qq/qq.js +97 -15
- package/src/reset.js +129 -0
- package/src/settings-schema.js +3 -0
package/src/interlude/core.js
CHANGED
|
@@ -23,8 +23,9 @@ import { homedir } from 'node:os';
|
|
|
23
23
|
import { join, relative, isAbsolute } from 'node:path';
|
|
24
24
|
import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
25
25
|
import { sectionOf, setValues } from '../settings.js';
|
|
26
|
-
import { background, installLlmGate } from '../llm-gate.js';
|
|
26
|
+
import { background, installLlmGate, workEffort } from '../llm-gate.js';
|
|
27
27
|
import { prompt, table } from '../prompts.js';
|
|
28
|
+
import { runPendingReset } from '../reset.js';
|
|
28
29
|
import { describeNow, stamp } from '../clock.js';
|
|
29
30
|
import { createDoings, tokensOf } from './doings.js';
|
|
30
31
|
import { createGrowth, growthTool } from './growth.js';
|
|
@@ -265,8 +266,37 @@ export const localStamp = (ts) => { const d = new Date(ts); const p = (n) => Str
|
|
|
265
266
|
|
|
266
267
|
const PHASES = { 'follow-up': 'interlude.round.phase.follow-up', intent: 'interlude.round.phase.intent', advance: 'interlude.round.phase.advance' };
|
|
267
268
|
|
|
269
|
+
// ── what she really did on her devices, and the narrator's account of it ──
|
|
270
|
+
// The narrator may give her any life the Canon allows, but her phone and computer are real: what she did on
|
|
271
|
+
// them is only what the host saw happen. A rule in the prompt alone did not hold (11-17: with no device activity
|
|
272
|
+
// at all, a round wrote that she had logged into QQ on her new phone, and that went back into her conversation
|
|
273
|
+
// as fact). So the round is given the record as data, with ids, and has to name the record behind everything it
|
|
274
|
+
// says she did on a device; the host checks the ids, and a round that cites none it was given is not kept.
|
|
275
|
+
/**
|
|
276
|
+
* The record for one round: acts since the last round in which a phone / computer tool ran (pending.jsonl:
|
|
277
|
+
* `tools`, `on`), and errands that came back done. `[]` says she touched neither device.
|
|
278
|
+
*/
|
|
279
|
+
export function deviceFacts(items = [], returned = []) {
|
|
280
|
+
const facts = [];
|
|
281
|
+
const add = (f) => facts.push({ id: `d${facts.length + 1}`, ...f });
|
|
282
|
+
for (const i of items) if (Number(i?.tools) > 0 && i.on) add({ at: localStamp(i.ts), on: i.on, did: clip(i.quiet ? `${i.user || '看了一眼'}(没有要理的)` : [i.user, i.assistant].filter(Boolean).join(' → '), 300) });
|
|
283
|
+
for (const r of returned) if (r?.status === 'done') add({ at: r.doneAt ?? r.startedAt ?? null, did: clip([r.wanted, r.report].filter(Boolean).join(' → '), 300) });
|
|
284
|
+
return facts;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Check a round's account against the record. `claims`: parsed.onDevices ([{ what, basis }], or null when the
|
|
288
|
+
* reply did not carry the field); `ids`: every id it was given (deviceFacts and webContext).
|
|
289
|
+
* Returns { ok, unbacked: [what…], missing } — missing: the field was not there, so nothing can be checked.
|
|
290
|
+
*/
|
|
291
|
+
export function checkDeviceClaims(claims, ids = []) {
|
|
292
|
+
if (!Array.isArray(claims)) return { ok: false, unbacked: [], missing: true };
|
|
293
|
+
const known = new Set(ids);
|
|
294
|
+
const unbacked = claims.filter((c) => !known.has(c.basis)).map((c) => c.what);
|
|
295
|
+
return { ok: !unbacked.length, unbacked, missing: false };
|
|
296
|
+
}
|
|
297
|
+
|
|
268
298
|
/** The round's prompt: interlude.round.txt with this round's variants filled in. `entries` are recentScript items with owner labels. */
|
|
269
|
-
export function buildPrompt({ phase, identity, state, script, digest, cursor, now, intent, speak, model = '', style = '', entries = [], lastHalfHour = [], browser = 'disabled', webContext = [], play = false, playApps = [], playActions = [], stickers = -1, memories = [], herLife = [], returned = [], doings = null, trying = false, upcoming = [] }) {
|
|
299
|
+
export function buildPrompt({ phase, identity, state, script, digest, cursor, now, intent, speak, model = '', style = '', entries = [], lastHalfHour = [], browser = 'disabled', webContext = [], play = false, playApps = [], playActions = [], stickers = -1, memories = [], herLife = [], returned = [], doings = null, trying = false, upcoming = [], facts = [], rejected = null }) {
|
|
270
300
|
const playing = Boolean(play && playApps.length);
|
|
271
301
|
const system = prompt('interlude.round', {
|
|
272
302
|
canon: identity ? prompt('interlude.round.canon', { identity: identity.trim() }) : '',
|
|
@@ -298,10 +328,13 @@ export function buildPrompt({ phase, identity, state, script, digest, cursor, no
|
|
|
298
328
|
],
|
|
299
329
|
// What she really did in the last half hour, already woven into earlier rounds: where she is now follows from it.
|
|
300
330
|
lastHalfHour,
|
|
331
|
+
// Everything she did on her phone and computer in this interval, as the host saw it (deviceFacts()). Always
|
|
332
|
+
// present: an empty list is the fact that she touched neither.
|
|
333
|
+
deviceFacts: facts,
|
|
301
334
|
dueIntents: intent ? [{ kind: intent.kind, text: intent.text, at: describeNow(new Date(intent.at)) }] : [],
|
|
302
335
|
// What she has already set for later (intents.json, minus the one that is due now): she should not set it again.
|
|
303
336
|
upcomingPlans: upcoming,
|
|
304
|
-
webContext,
|
|
337
|
+
webContext: webContext.map((w, i) => ({ id: `w${i + 1}`, ...w })),
|
|
305
338
|
// What she knows to be true (dsh-dot/memory): established past, like recentScript.
|
|
306
339
|
memories,
|
|
307
340
|
// Her own notes (dsh-dot/memory's self bank): what she does these days and what she has learned.
|
|
@@ -311,7 +344,9 @@ export function buildPrompt({ phase, identity, state, script, digest, cursor, no
|
|
|
311
344
|
// What she did on her own lately, what each cost, and what he said about it (doings.js).
|
|
312
345
|
...(doings ? { yourDoings: doings } : {}),
|
|
313
346
|
currentEvent: { type: 'none' },
|
|
314
|
-
|
|
347
|
+
// The draft before this one was not kept (see round()): what it claimed without a record, to be written without.
|
|
348
|
+
...(rejected ? { notKept: { why: prompt('interlude.round.not-kept'), claimedWithoutRecord: rejected } } : {}),
|
|
349
|
+
output: 'one `interval` tool call: script, continuity, onDevices, intents, browserIntents, playIntents, tries, reflect, contact',
|
|
315
350
|
};
|
|
316
351
|
void digest;
|
|
317
352
|
return { system, user: JSON.stringify(payload, null, 1), tools: [intervalTool({ play: playing, playApps, playActions, speak, trying })] };
|
|
@@ -330,6 +365,7 @@ export function intervalTool({ play = false, playApps = [], playActions = [], sp
|
|
|
330
365
|
properties: {
|
|
331
366
|
script: { ...str, description: 'The passage for this interval, Chinese prose, third person.' },
|
|
332
367
|
continuity: { type: 'object', properties: { current: str, recent: strs, salient: strs }, required: ['current', 'recent', 'salient'] },
|
|
368
|
+
onDevices: { type: 'array', description: 'Everything script and continuity say she did, saw or changed on her phone or computer in this interval, each with the id of the deviceFacts / webContext entry it rests on. [] when they say nothing of the kind.', items: { type: 'object', properties: { what: str, basis: { ...str, description: 'an id from deviceFacts (d1…) or webContext (w1…)' } }, required: ['what', 'basis'] } },
|
|
333
369
|
intents: { type: 'array', items: { type: 'object', properties: { at: { ...str, description: 'ISO-8601, strictly after now' }, kind: { type: 'string', enum: ['reminder', 'reply', 'contact'] }, text: str, willingness }, required: ['at', 'kind', 'text'] } },
|
|
334
370
|
browserIntents: { type: 'array', items: { type: 'object', properties: { mode: { type: 'string', enum: ['search', 'visit'] }, query: str, url: str, purpose: str }, required: ['mode'] } },
|
|
335
371
|
playIntents: play
|
|
@@ -343,7 +379,7 @@ export function intervalTool({ play = false, playApps = [], playActions = [], sp
|
|
|
343
379
|
? { anyOf: [{ type: 'null' }, { type: 'object', properties: { content: str, willingness, reason: str }, required: ['content'] }] }
|
|
344
380
|
: { type: 'null' },
|
|
345
381
|
},
|
|
346
|
-
required: ['script', 'continuity', 'intents', 'browserIntents', 'playIntents', 'contact'],
|
|
382
|
+
required: ['script', 'continuity', 'onDevices', 'intents', 'browserIntents', 'playIntents', 'contact'],
|
|
347
383
|
},
|
|
348
384
|
};
|
|
349
385
|
}
|
|
@@ -376,6 +412,8 @@ export function parseReply(text, now = Date.now()) {
|
|
|
376
412
|
salient: [].concat(cont.salient ?? cont.threads ?? []).map(str).filter(Boolean).slice(0, 5),
|
|
377
413
|
},
|
|
378
414
|
intents, contact,
|
|
415
|
+
// null: the reply did not carry the field (an older shape, prose only) — nothing to check it by.
|
|
416
|
+
onDevices: Array.isArray(o.onDevices) ? o.onDevices.map((x) => ({ what: str(x?.what), basis: str(x?.basis) })).filter((x) => x.what || x.basis).slice(0, 20) : null,
|
|
379
417
|
browserIntents: [].concat(o.browserIntents ?? []).map((b) => ({
|
|
380
418
|
mode: b?.mode === 'visit' ? 'visit' : 'search', query: str(b?.query), url: str(b?.url), purpose: str(b?.purpose),
|
|
381
419
|
})).filter((b) => (b.mode === 'visit' ? /^https?:\/\//.test(b.url) : b.query)).slice(0, 1),
|
|
@@ -500,6 +538,7 @@ export async function fetchPreset(hub, code, fetchImpl = globalThis.fetch) {
|
|
|
500
538
|
|
|
501
539
|
export function apply(ctx, config = {}) {
|
|
502
540
|
const logger = ctx.logger('dsh-interlude');
|
|
541
|
+
runPendingReset({ logger }); // a reset scheduled on the dot page: before any state is read (src/reset.js)
|
|
503
542
|
const cfg = { ...defaults, ...setValues(config), ...sectionOf('interlude', (m) => logger.warn(m)) };
|
|
504
543
|
if (cfg.enabled === false) { logger.info('off (dsh-dot.json: interlude.enabled = false)'); return; }
|
|
505
544
|
const home = cfg.home || join(homedir(), 'dot');
|
|
@@ -791,41 +830,74 @@ export function apply(ctx, config = {}) {
|
|
|
791
830
|
const onPhone = await (ctx.get('dshPhone')?.apps?.() ?? []);
|
|
792
831
|
const playApps = Object.keys(cfg.playApps).filter((label) => onPhone.includes(cfg.playApps[label]));
|
|
793
832
|
const view = doings.view({ rounds: roundCost(), apps: playApps, price: cfg.price });
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
833
|
+
// What she really did on her devices since the last round, and every id the narrator may cite (deviceFacts above).
|
|
834
|
+
const facts = deviceFacts(items, back);
|
|
835
|
+
const web = readWebContext();
|
|
836
|
+
const ids = [...facts.map((f) => f.id), ...web.map((_, i) => `w${i + 1}`)];
|
|
837
|
+
const effort = await workEffort(ctx, sel); // her narrator thinks at llm.workEffort, not at whatever the chat was last set to
|
|
838
|
+
const spent = [];
|
|
839
|
+
const logCall = (line) => { try { appendFileSync(files.calls, `${JSON.stringify({ ts: new Date().toISOString(), ...line })}\n`); } catch (error) { void error; } };
|
|
840
|
+
/** One draft of the round: the call, and the second call that fills the fields when the first wrote prose only. */
|
|
841
|
+
const draft = async (rejected) => {
|
|
842
|
+
const { system, user, tools } = buildPrompt({
|
|
843
|
+
phase, identity: clip(identity, 6000), state, script: readScript(files.script, cfg.scriptEntriesInPrompt).join('\n'),
|
|
844
|
+
digest: text, cursor: meta.cursor, now, intent, speak: cfg.speak, model: sel.model, style: canon?.storyDefaults?.style ?? '', entries,
|
|
845
|
+
lastHalfHour: lastHalfHour.map((a) => ({ at: localStamp(a.ts), on: a.on, did: a.did })),
|
|
846
|
+
browser: browsingOpen() ? 'deferred' : 'disabled', webContext: web,
|
|
847
|
+
play: cfg.play && Boolean(ctx.get('dshPhone')?.isReady), playApps, playActions: cfg.playActions, stickers: ctx.get('dshQq')?.connected ? ctx.get('dshQq').stickerCount?.() ?? -1 : -1,
|
|
848
|
+
memories: mem?.forInterlude?.() ?? [], herLife: mem?.herLife?.() ?? [], returned: back,
|
|
849
|
+
doings: view, trying: tryOpen(), facts, rejected,
|
|
850
|
+
upcoming: intents.filter((i) => i.id !== intent?.id).map((i) => ({ at: describeNow(new Date(i.at)), kind: i.kind, text: i.text })),
|
|
851
|
+
});
|
|
852
|
+
const options = background({ provider: sel.provider, model: sel.model, ...(effort ? { reasoningEffort: effort } : {}), system, tools, maxTokens: cfg.maxTokens,
|
|
853
|
+
messages: [createUserMessage({ content: [{ type: 'text', text: user }], source: { kind: 'dsh-interlude' } })] });
|
|
854
|
+
const r1 = await collectReply(ctx.llm.stream(options));
|
|
855
|
+
spent.push(usageOf(r1.usage));
|
|
856
|
+
// The `interval` tool call carries the fields; a bare JSON reply is accepted too.
|
|
857
|
+
const reply = r1.args || r1.text;
|
|
858
|
+
let parsed = parseReply(reply, now);
|
|
859
|
+
const script = parsed?.script || r1.text.trim();
|
|
860
|
+
if (!script) throw new Error('empty script');
|
|
861
|
+
// Prose without the fields (the model wrote the passage as text, or was cut off): a second
|
|
862
|
+
// call over the script just written fills every other field — the post-commit continuity
|
|
863
|
+
// refresh, widened so nothing the round should have produced is lost.
|
|
864
|
+
if (!parsed?.state) {
|
|
865
|
+
const r2 = await collectReply(ctx.llm.stream(background({
|
|
866
|
+
...options, maxTokens: 2000,
|
|
867
|
+
system: prompt('interlude.round.refresh'),
|
|
868
|
+
messages: [createUserMessage({ content: [{ type: 'text', text: JSON.stringify({ interval: { nowLocal: describeNow(now) }, previousContinuity: state ?? null, deviceFacts: facts, webContext: web.map((w, i) => ({ id: `w${i + 1}`, query: w.query, url: w.url })), script }, null, 1) }], source: { kind: 'dsh-interlude' } })],
|
|
869
|
+
}))).catch((error) => { logger.warn(`continuity refresh failed: ${error.message}`); return { text: '', args: '', usage: null }; });
|
|
870
|
+
spent.push(usageOf(r2.usage));
|
|
871
|
+
const refresh = r2.args || r2.text;
|
|
872
|
+
const p2 = parseReply(refresh.includes('"script"') ? refresh : `{"script":"x",${refresh.replace(/^[^{]*\{/, '')}`, now);
|
|
873
|
+
logCall({ phase: `${phase}:refresh`, usage: usageOf(r2.usage), reply: clip(refresh, 1500) });
|
|
874
|
+
if (p2?.state) parsed = { ...p2, script, intents: p2.intents?.length ? p2.intents : parsed?.intents ?? [], contact: p2.contact ?? parsed?.contact ?? null };
|
|
875
|
+
audit('continuity-refresh', { phase, recovered: Boolean(p2?.state) });
|
|
876
|
+
}
|
|
877
|
+
return { parsed, script, reply, usage: usageOf(r1.usage), viaTool: Boolean(r1.args) };
|
|
878
|
+
};
|
|
879
|
+
const addTokens = () => { for (const u of spent.splice(0)) if (u) { meta.dayTokensIn = (meta.dayTokensIn ?? 0) + u.in + u.cached; meta.dayTokensCached = (meta.dayTokensCached ?? 0) + u.cached; meta.dayTokensOut = (meta.dayTokensOut ?? 0) + u.out; } };
|
|
880
|
+
let d = await draft(null);
|
|
881
|
+
// Her devices are real: everything the draft says she did on them must name the record it rests on. The first
|
|
882
|
+
// draft that does not is written once more, told what had no record; a second one is not kept at all — no
|
|
883
|
+
// script, no continuity, nothing handed on — and the acts wait for the next round. (A seed opens an empty
|
|
884
|
+
// script with her past, before there was a record: not checked.)
|
|
885
|
+
let check = phase === 'seed' ? { ok: true, unbacked: [], missing: false } : checkDeviceClaims(d.parsed?.onDevices ?? null, ids);
|
|
886
|
+
logCall({ phase, acts: items.length, model: `${sel.provider}/${sel.model}`, effort: effort ?? 'default', usage: d.usage, viaTool: d.viaTool, deviceFacts: facts.length, ...(check.ok ? {} : { notKept: check.missing ? 'no onDevices' : check.unbacked }), reply: clip(d.reply, 2000) });
|
|
887
|
+
if (!check.ok) {
|
|
888
|
+
audit('round-unbacked', { phase, attempt: 1, deviceFacts: facts.length, ...(check.missing ? { missing: true } : { unbacked: check.unbacked.map((w) => clip(w, 80)).slice(0, 5) }) });
|
|
889
|
+
d = await draft(check.missing ? ['(上一稿没有填 onDevices)'] : check.unbacked);
|
|
890
|
+
check = checkDeviceClaims(d.parsed?.onDevices ?? null, ids);
|
|
891
|
+
logCall({ phase: `${phase}:again`, effort: effort ?? 'default', usage: d.usage, viaTool: d.viaTool, deviceFacts: facts.length, ...(check.ok ? {} : { notKept: check.missing ? 'no onDevices' : check.unbacked }), reply: clip(d.reply, 2000) });
|
|
892
|
+
if (!check.ok) {
|
|
893
|
+
meta.dayRounds++; addTokens(); saveMeta();
|
|
894
|
+
pausedUntil = Date.now() + Math.min(60, 5 * 2 ** fails++) * 60_000; // like a failed round: not again at once
|
|
895
|
+
logger.warn(`interlude ${phase}: not kept — it says she did things on her devices that there is no record of (${check.missing ? 'no onDevices' : check.unbacked.join(' / ').slice(0, 120)})`);
|
|
896
|
+
audit('round-rejected', { phase, deviceFacts: facts.length, ...(check.missing ? { missing: true } : { unbacked: check.unbacked.map((w) => clip(w, 80)).slice(0, 5) }) });
|
|
897
|
+
return { rejected: check.missing ? ['no onDevices'] : check.unbacked };
|
|
898
|
+
}
|
|
828
899
|
}
|
|
900
|
+
const { parsed, script, reply } = d;
|
|
829
901
|
if (phase === 'seed') {
|
|
830
902
|
// "[MM-DD HH:MM] ..." segments become dated entries; anything untagged keeps the current time.
|
|
831
903
|
const segs = script.split(/\n(?=\[\d{1,2}-\d{1,2} \d{1,2}:\d{2}\])/).map((t) => t.trim()).filter(Boolean);
|
|
@@ -861,13 +933,12 @@ export function apply(ctx, config = {}) {
|
|
|
861
933
|
intents = intents.slice(-20);
|
|
862
934
|
saveIntents();
|
|
863
935
|
}
|
|
864
|
-
try { appendFileSync(files.calls, `${JSON.stringify({ ts: new Date(now).toISOString(), phase, acts: items.length, model: `${sel.provider}/${sel.model}`, usage: spent[0], viaTool: Boolean(r1.args), reply: clip(reply, 2000) })}\n`); } catch (error) { void error; }
|
|
865
936
|
writeFileSync(files.pending, '');
|
|
866
937
|
meta.cursor = now; meta.count++; meta.dayRounds++;
|
|
867
938
|
meta.returned = (meta.returned ?? []).filter((r) => !back.includes(r)); // digested; what came back meanwhile waits for the next round
|
|
868
939
|
meta.recentActs = [...lastHalfHour, ...items.map((i) => ({ ts: i.ts, on: i.on, did: clip([i.user, i.assistant].filter(Boolean).join(' → '), 160) }))];
|
|
869
940
|
// The ledger: tokens this round, added to today's count (/interlude shows it).
|
|
870
|
-
|
|
941
|
+
addTokens();
|
|
871
942
|
if (phase === 'advance') meta.lastAdvance = now;
|
|
872
943
|
saveMeta();
|
|
873
944
|
// Deferred browsing: the character's browserIntent runs now through dsh's web service;
|
|
@@ -1009,11 +1080,12 @@ export function apply(ctx, config = {}) {
|
|
|
1009
1080
|
const sel = ctx.agentDefaultModel.currentSelection();
|
|
1010
1081
|
const system = prompt('interlude.growth.system', { name: canon?.storyDefaults?.characterName ?? 'dot', maxChars: cfg.portraitMaxChars, change: `${Math.round(cfg.portraitMaxChange * 100)}%` });
|
|
1011
1082
|
const messages = [createUserMessage({ content: [{ type: 'text', text: JSON.stringify(input, null, 1) }], source: { kind: 'dsh-interlude' } })];
|
|
1083
|
+
const effort = await workEffort(ctx, sel);
|
|
1012
1084
|
const call = async (msgs) => {
|
|
1013
|
-
const r = await collectReply(ctx.llm.stream(background({ provider: sel.provider, model: sel.model, ...(
|
|
1085
|
+
const r = await collectReply(ctx.llm.stream(background({ provider: sel.provider, model: sel.model, ...(effort ? { reasoningEffort: effort } : {}), system, tools: [growthTool()], maxTokens: cfg.maxTokens, messages: msgs })));
|
|
1014
1086
|
const u = usageOf(r.usage);
|
|
1015
1087
|
if (u) { meta.dayTokensIn = (meta.dayTokensIn ?? 0) + u.in + u.cached; meta.dayTokensCached = (meta.dayTokensCached ?? 0) + u.cached; meta.dayTokensOut = (meta.dayTokensOut ?? 0) + u.out; saveMeta(); }
|
|
1016
|
-
try { appendFileSync(files.calls, `${JSON.stringify({ ts: new Date().toISOString(), phase: 'growth', usage: u, reply: clip(r.args || r.text, 3000) })}\n`); } catch (error) { void error; }
|
|
1088
|
+
try { appendFileSync(files.calls, `${JSON.stringify({ ts: new Date().toISOString(), phase: 'growth', effort: effort ?? 'default', usage: u, reply: clip(r.args || r.text, 3000) })}\n`); } catch (error) { void error; }
|
|
1017
1089
|
try { return JSON.parse(r.args || r.text.slice(r.text.indexOf('{'), r.text.lastIndexOf('}') + 1)); } catch (error) { void error; return null; }
|
|
1018
1090
|
};
|
|
1019
1091
|
let out = await call(messages);
|
|
@@ -1340,7 +1412,7 @@ export function apply(ctx, config = {}) {
|
|
|
1340
1412
|
result = `\n${canonText() || '(no canon: /interlude preset <share code>, or set config.canon)'}`;
|
|
1341
1413
|
} else if (arg === 'now' || arg === 'advance' || arg === 'seed') {
|
|
1342
1414
|
const r = await round(arg === 'now' ? 'follow-up' : arg);
|
|
1343
|
-
result = r.ok ? `\nran: ${clip(r.script, 200)}${r.contact ? `\ncontact: ${r.contact.text} (${r.said ? 'sent' : 'held'})` : ''}` : `\nnot run: ${r.skipped ?? r.error}`;
|
|
1415
|
+
result = r.ok ? `\nran: ${clip(r.script, 200)}${r.contact ? `\ncontact: ${r.contact.text} (${r.said ? 'sent' : 'held'})` : ''}` : `\nnot run: ${r.rejected ? `not kept — it says she did things on her devices there is no record of: ${r.rejected.join(' / ')}` : r.skipped ?? r.error}`;
|
|
1344
1416
|
}
|
|
1345
1417
|
const { items } = digest();
|
|
1346
1418
|
rollDay();
|
package/src/llm-gate.js
CHANGED
|
@@ -56,6 +56,7 @@ export const defaults = {
|
|
|
56
56
|
maxBackgroundWaitSeconds: 180, // a background request never waits longer; capped at MAX_WAIT_CAP_SECONDS
|
|
57
57
|
holdRetries: true, // hold dsh's fast retry of a rate-limited request until the window has room
|
|
58
58
|
retryHoldMaxSeconds: 30, // …but never longer than this
|
|
59
|
+
workEffort: 'high', // reasoning effort of her background work (see workEffort() below); '' = whatever dsh's model selector says
|
|
59
60
|
};
|
|
60
61
|
// Why 20: one background request every 3 s at most. The measured burst (one "like a post" act) was
|
|
61
62
|
// dozens of requests in under a minute; 20 leaves most of a typical entry-tier RPM limit (tens per
|
|
@@ -89,9 +90,61 @@ function normalize(c = {}) {
|
|
|
89
90
|
maxWaitMs: Math.min(MAX_WAIT_CAP_SECONDS, num(c.maxBackgroundWaitSeconds, defaults.maxBackgroundWaitSeconds)) * 1000,
|
|
90
91
|
holdRetries: c.holdRetries === undefined ? defaults.holdRetries : c.holdRetries !== false,
|
|
91
92
|
retryHoldMaxMs: num(c.retryHoldMaxSeconds, defaults.retryHoldMaxSeconds) * 1000,
|
|
93
|
+
workEffort: typeof c.workEffort === 'string' ? c.workEffort.trim() : defaults.workEffort,
|
|
92
94
|
};
|
|
93
95
|
}
|
|
94
96
|
|
|
97
|
+
// ── the reasoning effort of her background work ──
|
|
98
|
+
// dsh has one model selector: changing the effort in any conversation also becomes the default every
|
|
99
|
+
// hand-built request read (currentSelection). Turning thinking off for a chat that should sound like a
|
|
100
|
+
// person therefore turned it off for the interlude's narrator, memory consolidation, the growth review
|
|
101
|
+
// and her errands as well — the work where it matters. So background work has its own setting
|
|
102
|
+
// (`llm.workEffort`), and the selector is left to mean what he set it for: the conversation in front of him.
|
|
103
|
+
//
|
|
104
|
+
// hand-built requests (interlude round and growth, memory, howto reflection): the caller asks here;
|
|
105
|
+
// her errand sessions: dot answers the host's `agent/request` waterfall with it (dot/core.js);
|
|
106
|
+
// QQ group scoring (one digit out): always 'off';
|
|
107
|
+
// her conversation, and everything that is not ours: untouched.
|
|
108
|
+
//
|
|
109
|
+
// An effort the model does not offer is never sent (the host rejects the request before any provider
|
|
110
|
+
// I/O): the host is asked once per model, and when it says no — or cannot be asked — the selector's
|
|
111
|
+
// own value is used, as before.
|
|
112
|
+
const effortOk = new Map(); // provider \0 model \0 effort → true | false
|
|
113
|
+
/**
|
|
114
|
+
* The effort for one background request on `route` ({ provider, model, reasoningEffort? }: the selection
|
|
115
|
+
* or request config it would otherwise use). `want` overrides the setting (scoring passes 'off').
|
|
116
|
+
* Returns the effort to send, or undefined for "do not set one".
|
|
117
|
+
*/
|
|
118
|
+
export async function workEffort(ctx, route, want) { return (await effortFor(ctx, route, want)).effort; }
|
|
119
|
+
/**
|
|
120
|
+
* The same, with the reason: { effort, why } — why: 'set' (the setting is used), 'same' (the selector already says
|
|
121
|
+
* it), 'follow' (llm.workEffort is ''), 'unsupported' (the model does not offer it), 'cannot-ask' (no llm service,
|
|
122
|
+
* or it has neither query), 'ask-failed: <code>' (the host could not answer now), 'error: …'. For the activity log.
|
|
123
|
+
*/
|
|
124
|
+
export async function effortFor(ctx, route, want) {
|
|
125
|
+
const follow = route?.reasoningEffort || undefined;
|
|
126
|
+
try {
|
|
127
|
+
const wanted = want ?? (gateFor(ctx)?.config ?? normalize(sectionOf('llm'))).workEffort;
|
|
128
|
+
if (!wanted || !route?.provider || !route?.model) return { effort: follow, why: 'follow' };
|
|
129
|
+
if (wanted === follow) return { effort: follow, why: 'same' };
|
|
130
|
+
const key = `${route.provider}\0${route.model}\0${wanted}`;
|
|
131
|
+
if (!effortOk.has(key)) {
|
|
132
|
+
// A component that did not inject `llm` (dot) may not read ctx.llm at all: each way is tried on its own.
|
|
133
|
+
let llm;
|
|
134
|
+
try { llm = ctx?.get?.('llm'); } catch { /* next */ }
|
|
135
|
+
if (!llm) { try { llm = ctx?.llm; } catch { /* none */ } }
|
|
136
|
+
const ask = typeof llm?.resolveCallConfig === 'function' ? (c) => llm.resolveCallConfig(c) : typeof llm?.prepareCall === 'function' ? (c) => llm.prepareCall(c) : null;
|
|
137
|
+
if (!ask) return { effort: follow, why: llm ? 'cannot-ask: llm has neither resolveCallConfig nor prepareCall' : 'cannot-ask: no llm service' }; // not cached, it may come later
|
|
138
|
+
try { await ask({ provider: route.provider, model: route.model, reasoningEffort: wanted }); effortOk.set(key, true); } catch (err) {
|
|
139
|
+
if (err?.code !== 'UNSUPPORTED_REASONING_EFFORT') return { effort: follow, why: `ask-failed: ${err?.code ?? err?.message ?? err}` }; // no adapter yet, offline…: ask again next time
|
|
140
|
+
effortOk.set(key, false);
|
|
141
|
+
try { ctx?.logger?.('dsh-dot/llm-gate')?.info?.(`${route.provider}/${route.model} has no reasoning effort "${wanted}" (llm.workEffort); background work follows the model selector`); } catch { /* ignore */ }
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return effortOk.get(key) ? { effort: wanted, why: 'set' } : { effort: follow, why: 'unsupported' };
|
|
145
|
+
} catch (err) { return { effort: follow, why: `error: ${err?.message ?? err}` }; }
|
|
146
|
+
}
|
|
147
|
+
|
|
95
148
|
/**
|
|
96
149
|
* The gate's logic, clock-injectable. `config`: the `llm` settings section; `now`/`setTimer`/
|
|
97
150
|
* `clearTimer`/`random` for tests; `logger` ({ info, debug }); `audit(event, data)`.
|
|
@@ -111,7 +164,7 @@ export function createGate({ config = {}, now = Date.now, setTimer = setTimeout,
|
|
|
111
164
|
const P = (name) => {
|
|
112
165
|
let p = providers.get(name);
|
|
113
166
|
if (!p) {
|
|
114
|
-
p = { name, starts: [], bgStarts: [], fg: new Map(), fgLastEnd: -Infinity, lastBgStart: -Infinity, cap: cfg.backgroundRpm, raiseAt: Infinity, hits: 0, lastHitAt: -Infinity, lastAnyHitAt: -Infinity, coolingUntil: 0, coolTimer: null, queue: [], timer: null, timerAt: Infinity, delayed: 0, rateLimited: 0, heldRetries: 0 };
|
|
167
|
+
p = { name, starts: [], bgStarts: [], fg: new Map(), fgLastEnd: -Infinity, lastBgStart: -Infinity, cap: cfg.backgroundRpm, raiseAt: Infinity, hits: 0, lastHitAt: -Infinity, lastAnyHitAt: -Infinity, coolingUntil: 0, coolTimer: null, queue: [], timer: null, effort: {}, timerAt: Infinity, delayed: 0, rateLimited: 0, heldRetries: 0 };
|
|
115
168
|
providers.set(name, p);
|
|
116
169
|
}
|
|
117
170
|
return p;
|
|
@@ -228,6 +281,7 @@ export function createGate({ config = {}, now = Date.now, setTimer = setTimeout,
|
|
|
228
281
|
const p = P(String(options?.provider ?? '?'));
|
|
229
282
|
refresh(p, t);
|
|
230
283
|
const rec = { p, cls: classify(options), session: options?.sessionId ? String(options.sessionId) : '', started: false, signal: options?.signal };
|
|
284
|
+
p.effort[rec.cls] = options?.reasoningEffort ? String(options.reasoningEffort) : 'default'; // what was really sent: shown on /dot
|
|
231
285
|
// An already aborted request is not counted: the adapter ends it at once without a provider call.
|
|
232
286
|
if (rec.signal?.aborted) return { rec, wait: null };
|
|
233
287
|
if (rec.cls === 'foreground') {
|
|
@@ -331,10 +385,10 @@ export function createGate({ config = {}, now = Date.now, setTimer = setTimeout,
|
|
|
331
385
|
status() {
|
|
332
386
|
const t = now();
|
|
333
387
|
return {
|
|
334
|
-
pacing, backgroundRpm: cfg.backgroundRpm, quietSeconds: cfg.quietMs / 1000, maxWaitSeconds: cfg.maxWaitMs / 1000, holdRetries: cfg.holdRetries,
|
|
388
|
+
workEffort: cfg.workEffort, pacing, backgroundRpm: cfg.backgroundRpm, quietSeconds: cfg.quietMs / 1000, maxWaitSeconds: cfg.maxWaitMs / 1000, holdRetries: cfg.holdRetries,
|
|
335
389
|
providers: [...providers.values()].map((p) => {
|
|
336
390
|
try { refresh(p, t); } catch { /* status only */ }
|
|
337
|
-
return { provider: p.name, lastMinute: p.starts.length, backgroundLastMinute: p.bgStarts.length, cap: p.cap, coolingUntil: p.coolingUntil || null, waiting: p.queue.length, foregroundInFlight: p.fg.size, delayed: p.delayed, rateLimited: p.rateLimited, heldRetries: p.heldRetries };
|
|
391
|
+
return { provider: p.name, effort: { ...p.effort }, lastMinute: p.starts.length, backgroundLastMinute: p.bgStarts.length, cap: p.cap, coolingUntil: p.coolingUntil || null, waiting: p.queue.length, foregroundInFlight: p.fg.size, delayed: p.delayed, rateLimited: p.rateLimited, heldRetries: p.heldRetries };
|
|
338
392
|
}),
|
|
339
393
|
};
|
|
340
394
|
},
|
|
@@ -354,7 +408,7 @@ export function createGate({ config = {}, now = Date.now, setTimer = setTimeout,
|
|
|
354
408
|
export function statusLine(st) {
|
|
355
409
|
if (!st) return 'model requests: gate not installed';
|
|
356
410
|
const head = st.pacing ? `background ≤${st.backgroundRpm}/min, waits ${st.quietSeconds} s after yours, ≤${st.maxWaitSeconds} s` : 'pacing off (llm.backgroundRpm 0)';
|
|
357
|
-
const per = st.providers.map((p) => `${p.provider} ${p.lastMinute}/min (bg cap ${p.cap}${p.coolingUntil ? `, cooling until ${new Date(p.coolingUntil).toTimeString().slice(0, 8)}` : ''}${p.waiting ? `, ${p.waiting} waiting` : ''}, ${p.delayed} delayed, ${p.rateLimited}×429${p.heldRetries ? `, ${p.heldRetries} retries held` : ''})`);
|
|
411
|
+
const per = st.providers.map((p) => `${p.provider} ${p.lastMinute}/min (bg cap ${p.cap}${p.coolingUntil ? `, cooling until ${new Date(p.coolingUntil).toTimeString().slice(0, 8)}` : ''}${p.waiting ? `, ${p.waiting} waiting` : ''}, ${p.delayed} delayed, ${p.rateLimited}×429${p.heldRetries ? `, ${p.heldRetries} retries held` : ''}${p.effort?.foreground || p.effort?.background ? `; thinking: chat ${p.effort.foreground ?? '—'}, background ${p.effort.background ?? '—'}` : ''})`);
|
|
358
412
|
return `model requests: ${per.join(' · ') || 'none yet'} — ${head}`;
|
|
359
413
|
}
|
|
360
414
|
|
package/src/memory/memory.js
CHANGED
|
@@ -28,8 +28,9 @@ import { createRecall } from './recall.js';
|
|
|
28
28
|
import { annotate } from './when.js';
|
|
29
29
|
import { dayMark, unstamp } from '../clock.js';
|
|
30
30
|
import { sectionOf, setValues } from '../settings.js';
|
|
31
|
-
import { background, installLlmGate } from '../llm-gate.js';
|
|
31
|
+
import { background, installLlmGate, workEffort } from '../llm-gate.js';
|
|
32
32
|
import { configure as configurePrompts, prompt, table } from '../prompts.js';
|
|
33
|
+
import { NO_BACKFILL, runPendingReset } from '../reset.js';
|
|
33
34
|
|
|
34
35
|
export const name = 'dot-memory';
|
|
35
36
|
export const inject = ['llm', 'agentDefaultModel'];
|
|
@@ -191,7 +192,15 @@ export function applyExtraction(memory, out, { limits = DEFAULT_LIMITS, now = Da
|
|
|
191
192
|
* memory the conversation that happened before memory was installed.
|
|
192
193
|
*/
|
|
193
194
|
/** His words as he typed them: without the line dot adds when they were steered into a running turn. */
|
|
194
|
-
export const ownerSaid = (text) => {
|
|
195
|
+
export const ownerSaid = (text) => {
|
|
196
|
+
// …and without the note about lines of hers that did not reach him (dot.owner-words.unsent), which comes last.
|
|
197
|
+
const head = `\n${prompt('dot.owner-words.unsent', { lines: '\u0000' }).split('\u0000')[0]}`;
|
|
198
|
+
// (A template someone rewrote to start with the lines themselves leaves no head to recognise: then nothing is cut.)
|
|
199
|
+
const i = head.trim().length >= 4 ? text.indexOf(head) : -1;
|
|
200
|
+
const t = i >= 0 ? text.slice(0, i) : text;
|
|
201
|
+
const busy = `\n${prompt('dot.owner-words.busy')}`;
|
|
202
|
+
return t.endsWith(busy) ? t.slice(0, -busy.length) : t;
|
|
203
|
+
};
|
|
195
204
|
|
|
196
205
|
/** An image she sent, as her transcript writes it — the ref itself, so the line can be sent again as it reads: `[表情包 sticker:<id>]`, else `[图 <ref>]` (phone:screen, phone:latest, a URL, face:<n>, a path). */
|
|
197
206
|
export const sentImage = (ref) => { const r = String(ref ?? '').trim(); return /^sticker:/i.test(r) ? `[表情包 ${r}]` : `[图 ${r}]`; };
|
|
@@ -256,6 +265,7 @@ export function renderHandoff(tail, gen) {
|
|
|
256
265
|
|
|
257
266
|
export function apply(ctx, config = {}) {
|
|
258
267
|
const logger = ctx.logger('dsh-dot/memory');
|
|
268
|
+
runPendingReset({ logger }); // a reset scheduled on the dot page: before any state is read (src/reset.js)
|
|
259
269
|
const user = sectionOf('memory', (m) => logger.warn(m));
|
|
260
270
|
const cfg = { ...defaults, ...setValues(config), ...user };
|
|
261
271
|
cfg.limits = { ...DEFAULT_LIMITS, ...(config.limits ?? {}), ...(user.limits ?? {}) };
|
|
@@ -367,6 +377,8 @@ export function apply(ctx, config = {}) {
|
|
|
367
377
|
if (backfilling) return backfilling;
|
|
368
378
|
backfilling = (async () => {
|
|
369
379
|
if (lines.length || memory.consolidations || memory.backfilled) return 0;
|
|
380
|
+
// A reset left this note: her memory was emptied on purpose, the old conversation is not read back in (src/reset.js).
|
|
381
|
+
if (existsSync(join(home, 'memory', NO_BACKFILL))) return 0;
|
|
370
382
|
const id = dot()?.session?.();
|
|
371
383
|
const sq = ctx.get('sessionQuery');
|
|
372
384
|
if (!id || typeof sq?.readSession !== 'function') { backfilling = null; return 0; }
|
|
@@ -417,7 +429,9 @@ export function apply(ctx, config = {}) {
|
|
|
417
429
|
const said = unstamp(contentText(event.data?.content ?? event.data?.message?.content));
|
|
418
430
|
const text = src.kind === 'user' ? ownerSaid(said) : said;
|
|
419
431
|
if (src.kind === 'user') record({ who: 'owner', session: id, text });
|
|
420
|
-
|
|
432
|
+
// A turn of his QQ words: its answer is recorded by what reached him (api.herSaid, from dot), not at turn end.
|
|
433
|
+
if (src.kind === 'user' && String(src.rpcId ?? '').startsWith('qq-')) { t.fromQq = true; turns.set(id, t); }
|
|
434
|
+
else if (src.kind === 'schedule') { record({ who: 'schedule', session: id, text }); t.scheduled = true; turns.set(id, t); }
|
|
421
435
|
else if (src.kind === 'dsh-dot' && src.form === 'phone-notification') record({ who: 'phone', session: id, text: text.split('\n(')[0] });
|
|
422
436
|
else if (src.kind === 'dsh-dot' && src.form === 'errand-note') record({ who: 'note', session: id, text: text.split('\n(')[0] });
|
|
423
437
|
// What woke her is the query; the result is in front of her before the model is called.
|
|
@@ -451,7 +465,8 @@ export function apply(ctx, config = {}) {
|
|
|
451
465
|
case 'turn/end': {
|
|
452
466
|
turns.delete(id);
|
|
453
467
|
// Her final words count as said only when they were not a QQ turn (desktop / IM bot replies).
|
|
454
|
-
|
|
468
|
+
// dot reports what reached him for a turn of his QQ words (not for a scheduled turn he spoke into: that one is answered through im.send).
|
|
469
|
+
if (!t.sentViaQq && !(t.fromQq && !t.scheduled && dot()?.reportsSaid) && t.last && !isSilent(t.last)) record({ who: 'her', session: id, text: t.last });
|
|
455
470
|
recall.clear(id); recall.turnEnded();
|
|
456
471
|
void afterTurn(id);
|
|
457
472
|
return;
|
|
@@ -469,7 +484,8 @@ export function apply(ctx, config = {}) {
|
|
|
469
484
|
let usage = null;
|
|
470
485
|
try {
|
|
471
486
|
let finish = null;
|
|
472
|
-
|
|
487
|
+
const effort = await workEffort(ctx, sel);
|
|
488
|
+
for await (const chunk of ctx.llm.stream(background({ provider: sel.provider, model: sel.model, ...(effort ? { reasoningEffort: effort } : {}), maxTokens: cfg.maxTokens, messages: [createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'dsh-dot-memory' } })] }))) {
|
|
473
489
|
if (chunk.type === 'text-delta') raw += chunk.text;
|
|
474
490
|
if (chunk.type === 'usage') usage = chunk.usage ?? null;
|
|
475
491
|
if (chunk.type === 'finish') finish = chunk.reason;
|
|
@@ -713,6 +729,8 @@ export function apply(ctx, config = {}) {
|
|
|
713
729
|
|
|
714
730
|
// ── the service: dot touches people from real events and shows their cards when they wake her ──
|
|
715
731
|
const api = {
|
|
732
|
+
/** What she said that reached him, as dot delivered it (a QQ turn's answer: the bubbles that went out). */
|
|
733
|
+
herSaid({ session, text, at }) { if (String(text ?? '').trim()) record({ ...(at ? { at } : {}), who: 'her', session, text: String(text) }); },
|
|
716
734
|
/** A real event with someone, from any channel: { handles, platform, name, tier, kind }. Returns the person. */
|
|
717
735
|
touch(e) { const p = touchPerson(memory, e); if (p) save(); return p; },
|
|
718
736
|
/** Who is this ({ handles, platform, name }), without recording anything. */
|
package/src/page/api.js
CHANGED
|
@@ -13,6 +13,7 @@ import { gateFor } from '../llm-gate.js';
|
|
|
13
13
|
import { doctorFor, FIXES } from '../doctor.js';
|
|
14
14
|
import { bundle, summary, versions } from './diag.js';
|
|
15
15
|
import { PAGE_PATH, pageHtml } from './page.js';
|
|
16
|
+
import { RESET_LEVELS, cancelReset, lastReset, pendingReset, resetsDir, scheduleReset } from '../reset.js';
|
|
16
17
|
|
|
17
18
|
export const API_PATH = '/dsh-dot/api';
|
|
18
19
|
const require = createRequire(import.meta.url);
|
|
@@ -51,6 +52,14 @@ const ACTIONS = {
|
|
|
51
52
|
await need(phone, '手机').rebuild({ gb: body?.gb ? Number(body.gb) : undefined });
|
|
52
53
|
return '旧手机已删除,正在新建并开机(几分钟)';
|
|
53
54
|
},
|
|
55
|
+
'reset': async ({ dot }, body) => {
|
|
56
|
+
const level = RESET_LEVELS.find((l) => l.id === String(body?.level ?? ''));
|
|
57
|
+
if (!level) throw new Error('没有这个重置等级');
|
|
58
|
+
if (String(body?.confirm ?? '').trim() !== 'dot') throw new Error('先在框里输入 dot');
|
|
59
|
+
scheduleReset(level.id, dot?.home);
|
|
60
|
+
return `已安排「${level.name}」:重启 DeepSeek Harness 后生效。旧数据会挪进 ${resetsDir()}/时间,人设不动`;
|
|
61
|
+
},
|
|
62
|
+
'reset-cancel': async () => (cancelReset() ? '已取消安排的重置' : '没有安排中的重置'),
|
|
54
63
|
'phone-cleanup': async ({ phone }) => { const b = need(phone, '手机').cleanup(); return `清掉了 ${Math.round(b / 1048576)} MB 下载缓存`; },
|
|
55
64
|
'qq-owner': async ({ qq }, body) => { need(qq, 'QQ').setOwner(String(body?.number ?? '')); return '已设置你的 QQ 号'; },
|
|
56
65
|
'qq-account': async ({ qq }, body) => { need(qq, 'QQ').setAccount(String(body?.number ?? '')); return '已设置她的 QQ 号'; },
|
|
@@ -116,7 +125,7 @@ export function createApi(ctx, logger) {
|
|
|
116
125
|
try {
|
|
117
126
|
if (route === 'GET /status') { const su = setupSteps(ctx); return json(res, 200, { status: statusOf(ctx), fileError: fileError() || null, setup: { done: su.done, dismissed: su.dismissed }, version: pluginVersion }); }
|
|
118
127
|
// components: which sections' components are on (gate exposes no service and is never listed: the page treats an unlisted section as on)
|
|
119
|
-
if (route === 'GET /settings') { const s = services(ctx); return json(res, 200, { entries: describe(readAll()), fileError: fileError() || null, components: Object.fromEntries(Object.keys(s).map((k) => [k, Boolean(s[k])])) }); }
|
|
128
|
+
if (route === 'GET /settings') { const s = services(ctx); return json(res, 200, { entries: describe(readAll()), fileError: fileError() || null, components: Object.fromEntries(Object.keys(s).map((k) => [k, Boolean(s[k])])), reset: { levels: RESET_LEVELS, pending: pendingReset(), last: lastReset() } }); }
|
|
120
129
|
if (route === 'PUT /settings') {
|
|
121
130
|
const body = await readJson(req);
|
|
122
131
|
const patch = validatePatch(body.patch);
|
package/src/page/page.js
CHANGED
|
@@ -47,6 +47,8 @@ textarea{width:100%;box-sizing:border-box;min-height:160px;font:12px/1.5 ui-mono
|
|
|
47
47
|
<section id="tab-status" hidden><div id="statusCards" class="mute">加载中…</div></section>
|
|
48
48
|
<section id="tab-settings"><div id="groups" class="mute">加载中…</div>
|
|
49
49
|
<details class="card" style="margin-top:12px"><summary style="cursor:pointer;color:var(--bad)">危险区</summary>
|
|
50
|
+
<div class="item" style="grid-template-columns:1fr auto"><div><b>重置她</b><div class="mute">把选中范围里的东西挪进备份文件夹(<code>~/.dsh/dsh-dot-resets/时间</code>,在她的 home 之外,她自己读不到),不是删除,挪回去就恢复。人设、设置、手机和电脑里装的东西不动(手机用下面的重建)。重启 DeepSeek Harness 后生效。</div>
|
|
51
|
+
<div class="row" style="margin-top:6px">等级 <select id="rsLevel"></select> · 输入 <b>dot</b> 确认 <input type="text" id="rsConfirm" style="width:70px"></div><div class="mute small" id="rsWhat" style="margin-top:4px"></div><div class="msg" id="rsMsg"></div></div><div><button class="btn" id="rs" style="color:var(--bad);border-color:var(--bad)">重置</button> <button class="btn" id="rsCancel" hidden>取消</button></div></div>
|
|
50
52
|
<div class="item" style="grid-template-columns:1fr auto"><div><b>重建手机</b><div class="mute">删掉现在这台手机,用当前的存储和内存设置新建一台。她装的 App、登录、照片全部没了;已下载的系统不用重下,几分钟就好。</div>
|
|
51
53
|
<div class="row" style="margin-top:6px">新存储 <select id="rbGb"><option value="">不变</option><option>8</option><option>16</option><option>32</option><option>64</option></select> GB · 输入 <b>dot</b> 确认 <input type="text" id="rbConfirm" style="width:70px"></div><div class="msg" id="rbMsg"></div></div><div><button class="btn" id="rb" style="color:var(--bad);border-color:var(--bad)">重建手机</button></div></div>
|
|
52
54
|
<div class="item" style="grid-template-columns:1fr auto"><div><b>清理手机下载缓存</b><div class="mute">安装时下载的压缩包。手机已装好的话可以删。</div><div class="msg" id="clMsg"></div></div><div><button class="btn" id="cl">清理</button></div></div>
|
|
@@ -175,6 +177,7 @@ async function loadSettings() {
|
|
|
175
177
|
const j = await api('GET', '/settings');
|
|
176
178
|
entries = j.entries; components = j.components; changes = {};
|
|
177
179
|
showFileErr(j.fileError);
|
|
180
|
+
renderReset(j.reset);
|
|
178
181
|
renderSettings();
|
|
179
182
|
$('save').disabled = $('revert').disabled = true;
|
|
180
183
|
}
|
|
@@ -198,8 +201,8 @@ $('save').onclick = async () => {
|
|
|
198
201
|
} catch (e) { $('saveMsg').className = 'msg err'; $('saveMsg').textContent = e.message; }
|
|
199
202
|
};
|
|
200
203
|
async function act(name, msgEl, body) {
|
|
201
|
-
try { const j = await api('POST', '/action/' + name, body); msgEl.className = 'msg ok'; msgEl.textContent = j.message; setTimeout(loadStatus, 800); }
|
|
202
|
-
catch (e) { msgEl.className = 'msg err'; msgEl.textContent = e.message; }
|
|
204
|
+
try { const j = await api('POST', '/action/' + name, body); msgEl.className = 'msg ok'; msgEl.textContent = j.message; setTimeout(loadStatus, 800); return true; }
|
|
205
|
+
catch (e) { msgEl.className = 'msg err'; msgEl.textContent = e.message; return false; }
|
|
203
206
|
}
|
|
204
207
|
|
|
205
208
|
// ---- doctor
|
|
@@ -251,6 +254,30 @@ $('sum').onclick = async () => {
|
|
|
251
254
|
};
|
|
252
255
|
|
|
253
256
|
// ---- danger zone
|
|
257
|
+
let resetLevels = [];
|
|
258
|
+
function resetWhat() {
|
|
259
|
+
const i = resetLevels.findIndex((l) => l.id === $('rsLevel').value);
|
|
260
|
+
$('rsWhat').innerHTML = resetLevels.slice(0, i + 1).map((l) => '· ' + esc(l.what)).join('<br>');
|
|
261
|
+
}
|
|
262
|
+
function renderReset(r) {
|
|
263
|
+
if (!r) return;
|
|
264
|
+
if (!resetLevels.length) {
|
|
265
|
+
resetLevels = r.levels || [];
|
|
266
|
+
$('rsLevel').innerHTML = resetLevels.map((l) => '<option value="' + esc(l.id) + '"' + (l.id === 'fresh' ? ' selected' : '') + '>' + esc(l.name) + '</option>').join('');
|
|
267
|
+
$('rsLevel').onchange = resetWhat;
|
|
268
|
+
resetWhat();
|
|
269
|
+
}
|
|
270
|
+
const name = (id) => (resetLevels.find((l) => l.id === id) || {}).name || id;
|
|
271
|
+
$('rsCancel').hidden = !r.pending;
|
|
272
|
+
if (r.pending) { $('rsMsg').className = 'msg ok'; $('rsMsg').textContent = '已安排「' + name(r.pending.level) + '」,重启 DeepSeek Harness 后生效'; }
|
|
273
|
+
else if (r.last) { $('rsMsg').className = r.last.error ? 'msg err' : 'msg'; $('rsMsg').textContent = '上次重置:' + name(r.last.level) + ' · ' + String(r.last.at).slice(0, 16).replace('T', ' ') + ' UTC · 旧数据在 ' + r.last.backup + (r.last.error ? ' · 出错:' + r.last.error + (r.last.rolledBack ? '(已全部放回原位)' : '(没能全部放回,见备份文件夹)') : ''); }
|
|
274
|
+
}
|
|
275
|
+
$('rs').onclick = async () => {
|
|
276
|
+
if ($('rsConfirm').value.trim() !== 'dot') { $('rsMsg').className = 'msg err'; $('rsMsg').textContent = '先在框里输入 dot'; return; }
|
|
277
|
+
if (!confirm('确定重置?重启 DeepSeek Harness 后,所选范围里的东西她都不再有(旧数据在备份文件夹里,可以挪回来)。')) return;
|
|
278
|
+
if (await act('reset', $('rsMsg'), { level: $('rsLevel').value, confirm: $('rsConfirm').value })) { $('rsCancel').hidden = false; $('rsConfirm').value = ''; }
|
|
279
|
+
};
|
|
280
|
+
$('rsCancel').onclick = async () => { if (await act('reset-cancel', $('rsMsg'))) $('rsCancel').hidden = true; };
|
|
254
281
|
$('rb').onclick = async () => {
|
|
255
282
|
if ($('rbConfirm').value.trim() !== 'dot') { $('rbMsg').className = 'msg err'; $('rbMsg').textContent = '先在框里输入 dot'; return; }
|
|
256
283
|
if (!confirm('确定删掉现在这台手机并新建?她手机里的一切都会没有。')) return;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
上一稿没有留下。claimedWithoutRecord 里这几件事,上一稿写成她已经在手机或电脑上做了,可 deviceFacts 里没有对应的记录——它们没有发生。把这一段重新写一遍,里面不要有这些事;她要是惦记着、打算去做,就写成惦记和打算,真要做的写进 tries、playIntents 或 browserIntents。
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
剧本已经写好了,现在补上其余字段:调用一次 `interval` 工具,script 设为 "-"。continuity 重写一份她的近况,{"continuity":{"current":"...","recent":["..."],"salient":["..."]}}——current 是她此刻在哪、在做什么、什么心情,recent 是这几天发生过、接下来还接得上的事,salient 是隔得更久也不该忘的事;三项都只记剧本里已经发生的,以后要做的事不写在这里。
|
|
2
|
-
同时根据剧本填好:intents(剧本里提到的具体的未来可能,时间用 ISO-8601,严格晚于现在;没有就 [])、browserIntents(她想查的东西;没有就 [])、playIntents(她想在手机上做的一个社交动作;没有就 [])、tries(她想真去试的一件新事;没有就 []),以及 contact(剧本里的 <contact/> 标记表示计划联系用户:将拟发送的原话放进 contact.content,不要把标记当作消息内容;没有标记 → null)。不要改写剧本。
|
|
2
|
+
同时根据剧本填好:onDevices(剧本里凡是说她这段时间在手机或电脑上做了、看了、改了什么的,每件一条 {"what":"...","basis":"..."},basis 填输入里 deviceFacts 或 webContext 对应那条的 id;找不到对应的也照实列出,basis 留空;和他的聊天不算;一件都没有就 [])、intents(剧本里提到的具体的未来可能,时间用 ISO-8601,严格晚于现在;没有就 [])、browserIntents(她想查的东西;没有就 [])、playIntents(她想在手机上做的一个社交动作;没有就 [])、tries(她想真去试的一件新事;没有就 []),以及 contact(剧本里的 <contact/> 标记表示计划联系用户:将拟发送的原话放进 contact.content,不要把标记当作消息内容;没有标记 → null)。不要改写剧本。
|