dsh-world 0.7.5 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +541 -446
- package/CONTRIBUTING.md +174 -163
- package/INSTALL.md +314 -314
- package/NOTES.md +98 -5
- package/README.md +332 -258
- package/client/index.js +1126 -986
- package/lib/compaction.d.ts +7 -1
- package/lib/compaction.js +8 -3
- package/lib/console/routes.d.ts +11 -3
- package/lib/console/routes.js +12 -7
- package/lib/console/snapshot.d.ts +2 -0
- package/lib/console/snapshot.js +1 -0
- package/lib/ecosystem/computer/browser/browser.d.ts +34 -0
- package/lib/ecosystem/computer/browser/browser.js +101 -0
- package/lib/ecosystem/computer/browser/cdp.d.ts +22 -0
- package/lib/ecosystem/computer/browser/cdp.js +91 -0
- package/lib/ecosystem/computer/browser/edge.d.ts +15 -0
- package/lib/ecosystem/computer/browser/edge.js +80 -0
- package/lib/ecosystem/computer/browser/page.d.ts +41 -0
- package/lib/ecosystem/computer/browser/page.js +140 -0
- package/lib/ecosystem/computer/browser/pageLib.d.ts +7 -0
- package/lib/ecosystem/computer/browser/pageLib.js +106 -0
- package/lib/ecosystem/computer/desktop/desktop.d.ts +91 -0
- package/lib/ecosystem/computer/desktop/desktop.js +322 -0
- package/lib/ecosystem/computer/desktop/driver.d.ts +34 -0
- package/lib/ecosystem/computer/desktop/driver.js +197 -0
- package/lib/ecosystem/computer/desktop/processes.d.ts +5 -0
- package/lib/ecosystem/computer/desktop/processes.js +15 -0
- package/lib/ecosystem/computer/desktop/recording.d.ts +77 -0
- package/lib/ecosystem/computer/desktop/recording.js +187 -0
- package/lib/ecosystem/computer/desktop/screen.d.ts +33 -0
- package/lib/ecosystem/computer/desktop/screen.js +182 -0
- package/lib/ecosystem/computer/desktop/turns.d.ts +58 -0
- package/lib/ecosystem/computer/desktop/turns.js +94 -0
- package/lib/ecosystem/computer/desktop/watching.d.ts +25 -0
- package/lib/ecosystem/computer/desktop/watching.js +81 -0
- package/lib/ecosystem/computer/inbox/inbox.d.ts +32 -0
- package/lib/ecosystem/computer/inbox/inbox.js +142 -0
- package/lib/ecosystem/computer/index.d.ts +82 -0
- package/lib/ecosystem/computer/index.js +133 -0
- package/lib/ecosystem/computer/procedures/alarm.d.ts +13 -0
- package/lib/ecosystem/computer/procedures/alarm.js +46 -0
- package/lib/ecosystem/computer/procedures/archive.d.ts +32 -0
- package/lib/ecosystem/computer/procedures/archive.js +68 -0
- package/lib/ecosystem/computer/procedures/catalog.d.ts +7 -0
- package/lib/ecosystem/computer/procedures/catalog.js +75 -0
- package/lib/ecosystem/computer/procedures/format.d.ts +167 -0
- package/lib/ecosystem/computer/procedures/format.js +332 -0
- package/lib/ecosystem/computer/procedures/library.d.ts +53 -0
- package/lib/ecosystem/computer/procedures/library.js +178 -0
- package/lib/ecosystem/computer/procedures/run.d.ts +80 -0
- package/lib/ecosystem/computer/procedures/run.js +245 -0
- package/lib/ecosystem/computer/tools.d.ts +21 -0
- package/lib/ecosystem/computer/tools.js +197 -0
- package/lib/ecosystem/qq-native/images.d.ts +8 -1
- package/lib/ecosystem/qq-native/images.js +34 -15
- package/lib/ecosystem/qq-native/index.js +5 -5
- package/lib/ecosystem/shared/turn.d.ts +3 -0
- package/lib/ecosystem/shared/turn.js +13 -3
- package/lib/ecosystem/wechat/home.d.ts +1 -0
- package/lib/ecosystem/wechat/home.js +9 -3
- package/lib/ecosystem/wechat/images.js +3 -5
- package/lib/ecosystem/wechat/index.d.ts +6 -0
- package/lib/ecosystem/wechat/index.js +3 -1
- package/lib/ecosystem/wechat/presence.d.ts +5 -1
- package/lib/ecosystem/wechat/presence.js +22 -13
- package/lib/ecosystem/wechat/reading.d.ts +1 -1
- package/lib/ecosystem/wechat/reading.js +2 -2
- package/lib/elsewhere.d.ts +34 -0
- package/lib/elsewhere.js +40 -0
- package/lib/history.d.ts +5 -0
- package/lib/history.js +7 -1
- package/lib/hostContract.d.ts +6 -0
- package/lib/images.d.ts +30 -0
- package/lib/images.js +101 -0
- package/lib/index.d.ts +4 -0
- package/lib/index.js +98 -6
- package/lib/life/photoTools.js +4 -15
- package/lib/life/runtime.d.ts +12 -2
- package/lib/life/runtime.js +93 -12
- package/lib/life/toolRegistry.d.ts +9 -3
- package/lib/life/toolRegistry.js +46 -27
- package/lib/life/turnCost.d.ts +16 -0
- package/lib/life/turnCost.js +44 -0
- package/lib/life/types.d.ts +17 -0
- package/lib/memoryTools.d.ts +4 -2
- package/lib/memoryTools.js +25 -5
- package/lib/mood.d.ts +5 -1
- package/lib/mood.js +25 -8
- package/lib/promptSection.d.ts +3 -0
- package/lib/promptSection.js +29 -42
- package/lib/runtime.js +44 -17
- package/lib/sessionNews.d.ts +17 -0
- package/lib/sessionNews.js +55 -0
- package/lib/store.d.ts +6 -0
- package/lib/store.js +17 -3
- package/lib/types.d.ts +4 -0
- package/lib/worldAdd.d.ts +9 -0
- package/lib/worldAdd.js +39 -0
- package/lib/worldPrompt.d.ts +3 -2
- package/lib/worldPrompt.js +3 -2
- package/lib/worldRoutes.d.ts +5 -2
- package/lib/worldRoutes.js +29 -4
- package/lib/worldSwitch.d.ts +8 -2
- package/lib/worldSwitch.js +11 -5
- package/package.json +132 -129
- package/src/ecosystem/README.md +2 -1
- package/src/ecosystem/computer/NOTICE.md +27 -0
- package/src/ecosystem/computer/README.md +244 -0
- package/src/ecosystem/computer/desktop/win32.ps1 +858 -0
- package/src/ecosystem/wechat/windows/README.md +4 -2
- package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
- package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
- package/templates/world-prompt-memory.md +10 -10
- package/templates/world-prompt.md +65 -65
package/lib/life/runtime.js
CHANGED
|
@@ -17,6 +17,7 @@ import { closedDiaryRefusal } from "./diary.js";
|
|
|
17
17
|
import { createHome } from "./home.js";
|
|
18
18
|
import { createJournal } from "./journal.js";
|
|
19
19
|
import { stepCost } from "./pricing.js";
|
|
20
|
+
import { addStep, openTurn, turnTrigger } from "./turnCost.js";
|
|
20
21
|
import { exampleTime, readAlarmMessages } from "./messages.js";
|
|
21
22
|
import { createToolRegistry } from "./toolRegistry.js";
|
|
22
23
|
import { alarmDescriptions, lifeTools } from "./tools.js";
|
|
@@ -24,6 +25,7 @@ import { photoTools } from "./photoTools.js";
|
|
|
24
25
|
/** How long a word may sit in her home without its turn starting a step before the console says so. */
|
|
25
26
|
const STALL_MINUTES = 5;
|
|
26
27
|
const withValue = (key, value) => (value === undefined ? {} : { [key]: value });
|
|
28
|
+
const ALARM_FACTS_LIMIT_MS = 90_000;
|
|
27
29
|
/**
|
|
28
30
|
* Her life line: one pending alarm, kept in life.json and delivered into her home with `agent.steer`, the
|
|
29
31
|
* tools she sets it with, the home itself, a new home's greeting and the evening look back. The parts live in
|
|
@@ -324,6 +326,26 @@ export function createLifeRuntime(deps) {
|
|
|
324
326
|
diaryDir: options.diaryDir, selfFile: options.selfFile,
|
|
325
327
|
}, timeZone, wake(), alarmMessages(), templateValues()), () => deps.afterReview?.());
|
|
326
328
|
}
|
|
329
|
+
/** The optional facts line never holds up her alarm: a failure or a wait past the limit is a fault and the alarm goes without it. */
|
|
330
|
+
async function alarmFacts() {
|
|
331
|
+
if (!deps.alarmContext)
|
|
332
|
+
return undefined;
|
|
333
|
+
let handle;
|
|
334
|
+
const limit = new Promise((_, reject) => { handle = timers.set(() => reject(new Error('等了太久')), ALARM_FACTS_LIMIT_MS); });
|
|
335
|
+
try {
|
|
336
|
+
const facts = await Promise.race([Promise.resolve().then(() => deps.alarmContext(clock())), limit]);
|
|
337
|
+
faults.clear('alarm-facts');
|
|
338
|
+
return facts;
|
|
339
|
+
}
|
|
340
|
+
catch (error) {
|
|
341
|
+
ctx.logger.error(error);
|
|
342
|
+
faults.set('alarm-facts', `闹钟附加的信息没取到:${errorText(error)}`);
|
|
343
|
+
return undefined;
|
|
344
|
+
}
|
|
345
|
+
finally {
|
|
346
|
+
timers.clear(handle);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
327
349
|
async function send(alarm) {
|
|
328
350
|
try {
|
|
329
351
|
// Resolve (or rebuild) the home first: a rebuilt home must still see this alarm as pending.
|
|
@@ -334,11 +356,18 @@ export function createLifeRuntime(deps) {
|
|
|
334
356
|
timer.arm();
|
|
335
357
|
return;
|
|
336
358
|
}
|
|
359
|
+
// Gathered before the alarm leaves the store, so a stop or a new alarm meanwhile keeps this one pending.
|
|
360
|
+
const context = await alarmFacts();
|
|
361
|
+
if (stopped)
|
|
362
|
+
return;
|
|
363
|
+
if (state.alarm !== alarm || agent.id !== state.homeSessionId) {
|
|
364
|
+
timer.arm();
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
337
367
|
// Cleared before steering, so a turn that ends quickly already sees "no alarm" and gets the fallback.
|
|
338
368
|
delete state.alarm;
|
|
339
369
|
const now = clock();
|
|
340
370
|
const text = wakeText(alarm, now, timeZone, wake(), alarmMessages(), { ...templateValues(), did: alarm.source === 'fallback' ? '' : didSince(alarm, now) });
|
|
341
|
-
const context = deps.alarmContext?.(now);
|
|
342
371
|
const message = lifeMessage(context ? `${text}\n\n${context}` : text);
|
|
343
372
|
expect(agent, message, '闹钟', alarm.at, alarm.source, { alarm }, now);
|
|
344
373
|
await say(agent, message);
|
|
@@ -378,12 +407,38 @@ export function createLifeRuntime(deps) {
|
|
|
378
407
|
const text = earlyStopText(alarm, now, timeZone, alarmMessages(), templateValues());
|
|
379
408
|
void home.open().then(agent => stopped ? undefined : say(agent, text)).catch(error => { earlyStop.ownTurnFailed(); ctx.logger.error(error); });
|
|
380
409
|
}
|
|
381
|
-
// What her home spends: each model step priced as it lands
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
const day = formatLocalTime(
|
|
385
|
-
|
|
386
|
-
|
|
410
|
+
// What her home spends: each model step priced as it lands, and added to the turn it is part of; past the daily
|
|
411
|
+
// budget she is told once that day.
|
|
412
|
+
const today = () => {
|
|
413
|
+
const day = formatLocalTime(clock(), timeZone).slice(0, 10);
|
|
414
|
+
return state.spend?.day === day ? state.spend : (state.spend = { day, yuan: 0 });
|
|
415
|
+
};
|
|
416
|
+
/** The turn under way, as the console lists it; opened by turn/start, closed by turn/end. */
|
|
417
|
+
let turn;
|
|
418
|
+
function turnEvent(event) {
|
|
419
|
+
if (event.type === 'turn/start') {
|
|
420
|
+
turn = openTurn(today(), clock());
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
if (event.type === 'user/message' && turn && !turn.trigger) {
|
|
424
|
+
const trigger = turnTrigger(event.data);
|
|
425
|
+
if (trigger)
|
|
426
|
+
turn.trigger = trigger;
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (event.type === 'turn/end' && turn) {
|
|
430
|
+
turn.ended = true;
|
|
431
|
+
turn = undefined;
|
|
432
|
+
record(() => store.write(state));
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
function spent(usage, model, tools) {
|
|
436
|
+
const spend = today();
|
|
437
|
+
const yuan = stepCost(usage, model, clock());
|
|
438
|
+
spend.yuan += yuan;
|
|
439
|
+
// A step with no turn seen opening (the plugin started mid-turn) still belongs somewhere on the list.
|
|
440
|
+
turn ??= openTurn(spend, clock());
|
|
441
|
+
addStep(turn, { yuan, hit: usage.cacheReadTokens ?? 0, miss: usage.inputTokens, out: usage.outputTokens, tools });
|
|
387
442
|
const budget = deps.dailyBudget?.();
|
|
388
443
|
const remind = budget !== undefined && spend.yuan >= budget && !spend.reminded;
|
|
389
444
|
if (remind)
|
|
@@ -391,16 +446,38 @@ export function createLifeRuntime(deps) {
|
|
|
391
446
|
record(() => store.write(state));
|
|
392
447
|
if (!remind)
|
|
393
448
|
return;
|
|
394
|
-
|
|
449
|
+
notice(budgetText(spend.yuan, budget, alarmMessages(), templateValues()));
|
|
450
|
+
}
|
|
451
|
+
/** A word for her now: into the running turn at its next step, or a turn of its own that is not asked about. */
|
|
452
|
+
function notice(text) {
|
|
395
453
|
void home.open().then(agent => {
|
|
396
454
|
if (stopped)
|
|
397
455
|
return;
|
|
398
|
-
// Into the running turn at its next step, or a turn of its own that is not asked about.
|
|
399
456
|
if (agent.status !== 'running')
|
|
400
457
|
earlyStop.startsOwnTurn();
|
|
401
458
|
return say(agent, text);
|
|
402
459
|
}).catch(error => { earlyStop.ownTurnFailed(); ctx.logger.error(error); });
|
|
403
460
|
}
|
|
461
|
+
/**
|
|
462
|
+
* A word of the plugin's own for a home that is free: false while she is in a turn or another word is on its way,
|
|
463
|
+
* so the caller keeps it and asks again. Its turn is never asked about as an early stop.
|
|
464
|
+
*/
|
|
465
|
+
async function tell(text) {
|
|
466
|
+
if (stopped)
|
|
467
|
+
return false;
|
|
468
|
+
const agent = await home.open();
|
|
469
|
+
if (stopped || agent.status === 'running' || state.delivering)
|
|
470
|
+
return false;
|
|
471
|
+
earlyStop.startsOwnTurn();
|
|
472
|
+
try {
|
|
473
|
+
await say(agent, text);
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
catch (error) {
|
|
477
|
+
earlyStop.ownTurnFailed();
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
}
|
|
404
481
|
// Her tools and her home.
|
|
405
482
|
const notifier = {
|
|
406
483
|
...(deps.notifier.toast ? { toast: (title, body) => faults.track('toast', '系统通知没送到', () => deps.notifier.toast(title, body)) } : {}),
|
|
@@ -408,6 +485,7 @@ export function createLifeRuntime(deps) {
|
|
|
408
485
|
};
|
|
409
486
|
const tools = createToolRegistry({
|
|
410
487
|
faults, logger: ctx.logger,
|
|
488
|
+
...(deps.homeTools ? { extras: deps.homeTools } : {}),
|
|
411
489
|
inWorld: agent => !stopped && includes(agent.session),
|
|
412
490
|
isHome: agent => agent.id === state.homeSessionId,
|
|
413
491
|
guard: ({ name, arguments: args, agent }) => {
|
|
@@ -458,10 +536,13 @@ export function createLifeRuntime(deps) {
|
|
|
458
536
|
if (session.id !== state.homeSessionId)
|
|
459
537
|
return;
|
|
460
538
|
journal.home(session, event);
|
|
539
|
+
turnEvent(event);
|
|
461
540
|
if (event.type === 'assistant/message' && event.data.usage)
|
|
462
|
-
spent(event.data.usage, event.data.message.source.model);
|
|
463
|
-
if (event.type === 'user/message' && event.data.source.kind === 'user')
|
|
541
|
+
spent(event.data.usage, event.data.message.source.model, event.data.message.content.flatMap(block => block.type === 'tool-call' ? [block.name] : []));
|
|
542
|
+
if (event.type === 'user/message' && event.data.source.kind === 'user') {
|
|
464
543
|
earlyStop.partnerSpoke();
|
|
544
|
+
deps.partnerSpoke?.();
|
|
545
|
+
}
|
|
465
546
|
// Before the fallback below, so a word whose turn never ran goes back first.
|
|
466
547
|
const pending = state.delivering;
|
|
467
548
|
if (pending?.sessionId === session.id) {
|
|
@@ -527,7 +608,7 @@ export function createLifeRuntime(deps) {
|
|
|
527
608
|
tools.clear();
|
|
528
609
|
}
|
|
529
610
|
return {
|
|
530
|
-
start, stop, planNext, checkAlarm, cancelAlarm, deliver, reschedule,
|
|
611
|
+
start, stop, planNext, checkAlarm, cancelAlarm, deliver, reschedule, tell, notice,
|
|
531
612
|
snapshot: () => ({ homeSessionId: state.homeSessionId, alarm: state.alarm, review: state.review, spend: state.spend, faults: faults.list() }),
|
|
532
613
|
/** Resolves once no alarm delivery is in flight (its durability flush can outlast the turn it starts). */
|
|
533
614
|
settled: async () => { while (delivery)
|
|
@@ -3,8 +3,10 @@ import { type Faults } from '../faults.ts';
|
|
|
3
3
|
import type { ToolDefinition, ToolGuard } from '@deepseek-ai/dsh-tools';
|
|
4
4
|
/**
|
|
5
5
|
* The alarm tools are held by every world session (she can set her alarm anywhere; it rings at home), with `guard`
|
|
6
|
-
* checking each of its tool calls; reach_out only by the current home.
|
|
7
|
-
*
|
|
6
|
+
* checking each of its tool calls; reach_out only by the current home. `extras` are more home-only tools whose set
|
|
7
|
+
* changes at run time (her own tools): they are registered again whenever their revision moves. A registration that
|
|
8
|
+
* fails (a name clash) is a fault and never breaks agent creation; it registers all of a group or none. Each tool
|
|
9
|
+
* refuses to run once its session leaves her world.
|
|
8
10
|
*/
|
|
9
11
|
export declare function createToolRegistry(deps: {
|
|
10
12
|
faults: Faults;
|
|
@@ -15,13 +17,17 @@ export declare function createToolRegistry(deps: {
|
|
|
15
17
|
isHome(agent: Agent): boolean;
|
|
16
18
|
inWorld(agent: Agent): boolean;
|
|
17
19
|
guard?: ToolGuard;
|
|
20
|
+
extras?: {
|
|
21
|
+
tools(agent: Agent): readonly ToolDefinition[];
|
|
22
|
+
revision(): string;
|
|
23
|
+
};
|
|
18
24
|
}): {
|
|
19
25
|
/** Registers what the agent is missing; true when its tool list changed. */
|
|
20
26
|
attach(agent: Agent): boolean;
|
|
21
27
|
forget: (agent: Agent) => void;
|
|
22
28
|
/** Takes every tool away from an agent that left her world; true when it had any. */
|
|
23
29
|
detach(agent: Agent): boolean;
|
|
24
|
-
/** A rebuilt home takes reach_out from the old one. */
|
|
30
|
+
/** A rebuilt home takes reach_out and her own tools from the old one. */
|
|
25
31
|
releaseOldHomes(): void;
|
|
26
32
|
clear(): void;
|
|
27
33
|
};
|
package/lib/life/toolRegistry.js
CHANGED
|
@@ -13,17 +13,20 @@ function undo(list) {
|
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
15
|
* The alarm tools are held by every world session (she can set her alarm anywhere; it rings at home), with `guard`
|
|
16
|
-
* checking each of its tool calls; reach_out only by the current home.
|
|
17
|
-
*
|
|
16
|
+
* checking each of its tool calls; reach_out only by the current home. `extras` are more home-only tools whose set
|
|
17
|
+
* changes at run time (her own tools): they are registered again whenever their revision moves. A registration that
|
|
18
|
+
* fails (a name clash) is a fault and never breaks agent creation; it registers all of a group or none. Each tool
|
|
19
|
+
* refuses to run once its session leaves her world.
|
|
18
20
|
*/
|
|
19
21
|
export function createToolRegistry(deps) {
|
|
20
22
|
const alarm = new Map();
|
|
21
23
|
const home = new Map();
|
|
24
|
+
const extras = new Map();
|
|
22
25
|
function register(agent, tools, names) {
|
|
23
26
|
const done = [];
|
|
24
27
|
try {
|
|
25
28
|
for (const tool of tools)
|
|
26
|
-
if (names.includes(tool.name))
|
|
29
|
+
if (!names || names.includes(tool.name))
|
|
27
30
|
done.push(registerScopedTool(agent, tool, () => deps.inWorld(agent)));
|
|
28
31
|
}
|
|
29
32
|
catch (error) {
|
|
@@ -32,32 +35,42 @@ export function createToolRegistry(deps) {
|
|
|
32
35
|
}
|
|
33
36
|
return done;
|
|
34
37
|
}
|
|
35
|
-
function
|
|
38
|
+
function dropExtras(agent) { const entry = extras.get(agent); if (entry)
|
|
39
|
+
undo(entry.done); extras.delete(agent); }
|
|
40
|
+
function forget(agent) { alarm.delete(agent); home.delete(agent); extras.delete(agent); deps.faults.clear(`attach:${agent.id}`); }
|
|
36
41
|
return {
|
|
37
42
|
/** Registers what the agent is missing; true when its tool list changed. */
|
|
38
43
|
attach(agent) {
|
|
39
|
-
const needsAlarm = !alarm.get(agent)?.length, needsHome = deps.isHome(agent) && !home.get(agent)?.length;
|
|
40
|
-
if (!needsAlarm && !needsHome)
|
|
41
|
-
return false;
|
|
42
44
|
let changed = false;
|
|
43
45
|
try {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
46
|
+
const isHome = deps.isHome(agent);
|
|
47
|
+
const needsAlarm = !alarm.get(agent)?.length, needsHome = isHome && !home.get(agent)?.length;
|
|
48
|
+
if (needsAlarm || needsHome) {
|
|
49
|
+
const tools = deps.tools(agent);
|
|
50
|
+
if (needsAlarm) {
|
|
51
|
+
const done = register(agent, tools, ALARM_TOOLS);
|
|
52
|
+
// The world sessions' own policy comes and goes with their alarm tools.
|
|
53
|
+
try {
|
|
54
|
+
if (deps.guard)
|
|
55
|
+
done.push(agent.ctx.tools.guard(execution => deps.inWorld(agent) ? deps.guard(execution) : undefined));
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
undo(done);
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
alarm.set(agent, done);
|
|
62
|
+
changed = true;
|
|
51
63
|
}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
64
|
+
if (needsHome) {
|
|
65
|
+
home.set(agent, register(agent, tools, HOME_TOOLS));
|
|
66
|
+
changed = true;
|
|
55
67
|
}
|
|
56
|
-
alarm.set(agent, done);
|
|
57
|
-
changed = true;
|
|
58
68
|
}
|
|
59
|
-
|
|
60
|
-
|
|
69
|
+
// After the fixed groups, so a failing extras source never keeps them away.
|
|
70
|
+
const revision = isHome ? deps.extras?.revision() : undefined;
|
|
71
|
+
if (revision !== undefined && extras.get(agent)?.revision !== revision) {
|
|
72
|
+
dropExtras(agent);
|
|
73
|
+
extras.set(agent, { revision, done: register(agent, deps.extras.tools(agent)) });
|
|
61
74
|
changed = true;
|
|
62
75
|
}
|
|
63
76
|
deps.faults.clear(`attach:${agent.id}`);
|
|
@@ -71,7 +84,7 @@ export function createToolRegistry(deps) {
|
|
|
71
84
|
forget,
|
|
72
85
|
/** Takes every tool away from an agent that left her world; true when it had any. */
|
|
73
86
|
detach(agent) {
|
|
74
|
-
const lists = [alarm.get(agent), home.get(agent)];
|
|
87
|
+
const lists = [alarm.get(agent), home.get(agent), extras.get(agent)?.done];
|
|
75
88
|
const changed = lists.some(list => list?.length);
|
|
76
89
|
for (const list of lists)
|
|
77
90
|
if (list)
|
|
@@ -79,15 +92,21 @@ export function createToolRegistry(deps) {
|
|
|
79
92
|
forget(agent);
|
|
80
93
|
return changed;
|
|
81
94
|
},
|
|
82
|
-
/** A rebuilt home takes reach_out from the old one. */
|
|
83
|
-
releaseOldHomes() {
|
|
84
|
-
|
|
85
|
-
|
|
95
|
+
/** A rebuilt home takes reach_out and her own tools from the old one. */
|
|
96
|
+
releaseOldHomes() {
|
|
97
|
+
for (const [agent, list] of home)
|
|
98
|
+
if (!deps.isHome(agent))
|
|
99
|
+
undo(list);
|
|
100
|
+
for (const agent of [...extras.keys()])
|
|
101
|
+
if (!deps.isHome(agent))
|
|
102
|
+
dropExtras(agent);
|
|
103
|
+
},
|
|
86
104
|
clear() {
|
|
87
|
-
for (const list of [...home.values(), ...alarm.values()])
|
|
105
|
+
for (const list of [...home.values(), ...alarm.values(), ...[...extras.values()].map(entry => entry.done)])
|
|
88
106
|
undo(list);
|
|
89
107
|
home.clear();
|
|
90
108
|
alarm.clear();
|
|
109
|
+
extras.clear();
|
|
91
110
|
},
|
|
92
111
|
};
|
|
93
112
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { UserMessage } from '@deepseek-ai/dsh-llm';
|
|
2
|
+
import type { Spend, SpendTurn } from './types.ts';
|
|
3
|
+
/** The latest turns the console lists under today's spend. */
|
|
4
|
+
export declare const TURNS_KEPT = 8;
|
|
5
|
+
/** What a message says started the turn it opens, or undefined when it only travels with the words that did. */
|
|
6
|
+
export declare function turnTrigger(message: UserMessage): string | undefined;
|
|
7
|
+
/** A turn that just opened, at the end of the day's list; older ones fall off past TURNS_KEPT. */
|
|
8
|
+
export declare function openTurn(spend: Spend, at: Date): SpendTurn;
|
|
9
|
+
/** One model step of the turn under way: its cost, its tokens and the tools it called. */
|
|
10
|
+
export declare function addStep(turn: SpendTurn, step: {
|
|
11
|
+
yuan: number;
|
|
12
|
+
hit: number;
|
|
13
|
+
miss: number;
|
|
14
|
+
out: number;
|
|
15
|
+
tools: readonly string[];
|
|
16
|
+
}): void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { injectedSources } from "../compaction.js";
|
|
2
|
+
/** The latest turns the console lists under today's spend. */
|
|
3
|
+
export const TURNS_KEPT = 8;
|
|
4
|
+
const SNIPPET = 24;
|
|
5
|
+
/** What the harness and the plugin put around a turn: never what started it. */
|
|
6
|
+
const AROUND = new Set([...injectedSources, 'runtime-context', 'skill-catalog', 'dsh-world-channel-context', 'dsh-world-wechat-outgoing']);
|
|
7
|
+
const CHANNELS = { wechat: '微信', qq: 'QQ' };
|
|
8
|
+
const snippet = (message) => {
|
|
9
|
+
const text = message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join(' ')
|
|
10
|
+
// A channel's words open with who and where (`identityPrefix`), her own with 【我的时间】: neither says what the turn is about.
|
|
11
|
+
.replace(/^【[^】]*】\s*/, '').replace(/\s+/g, ' ').trim();
|
|
12
|
+
return text.length > SNIPPET ? `${text.slice(0, SNIPPET)}…` : text;
|
|
13
|
+
};
|
|
14
|
+
/** What a message says started the turn it opens, or undefined when it only travels with the words that did. */
|
|
15
|
+
export function turnTrigger(message) {
|
|
16
|
+
const { source } = message;
|
|
17
|
+
if (AROUND.has(source.kind))
|
|
18
|
+
return undefined;
|
|
19
|
+
if (source.kind === 'user') {
|
|
20
|
+
const channel = source.identity?.channel;
|
|
21
|
+
return `${channel ? CHANNELS[channel] ?? channel : 'DSH'}:${snippet(message)}`;
|
|
22
|
+
}
|
|
23
|
+
if (source.kind === 'dsh-world-life')
|
|
24
|
+
return `她的时间:${snippet(message)}`;
|
|
25
|
+
if (source.kind === 'compact-checkpoint')
|
|
26
|
+
return '压缩后接着做';
|
|
27
|
+
return source.kind;
|
|
28
|
+
}
|
|
29
|
+
/** A turn that just opened, at the end of the day's list; older ones fall off past TURNS_KEPT. */
|
|
30
|
+
export function openTurn(spend, at) {
|
|
31
|
+
const turn = { at: at.toISOString(), trigger: '', steps: 0, yuan: 0, hit: 0, miss: 0, out: 0, tools: {}, ended: false };
|
|
32
|
+
spend.turns = [...spend.turns ?? [], turn].slice(-TURNS_KEPT);
|
|
33
|
+
return turn;
|
|
34
|
+
}
|
|
35
|
+
/** One model step of the turn under way: its cost, its tokens and the tools it called. */
|
|
36
|
+
export function addStep(turn, step) {
|
|
37
|
+
turn.steps++;
|
|
38
|
+
turn.yuan += step.yuan;
|
|
39
|
+
turn.hit += step.hit;
|
|
40
|
+
turn.miss += step.miss;
|
|
41
|
+
turn.out += step.out;
|
|
42
|
+
for (const tool of step.tools)
|
|
43
|
+
turn.tools[tool] = (turn.tools[tool] ?? 0) + 1;
|
|
44
|
+
}
|
package/lib/life/types.d.ts
CHANGED
|
@@ -18,10 +18,27 @@ export interface Greeting {
|
|
|
18
18
|
kind: 'arrival' | 'return';
|
|
19
19
|
}
|
|
20
20
|
/** What her home spent on the local `day`, in CNY, and whether she was told she went past her budget. */
|
|
21
|
+
/**
|
|
22
|
+
* One turn of her home, for the console: when it opened and what started it, its steps, what they cost, their tokens
|
|
23
|
+
* (cache hit, miss, output) and the tools called, by count. `ended` is false while it is still going.
|
|
24
|
+
*/
|
|
25
|
+
export interface SpendTurn {
|
|
26
|
+
at: string;
|
|
27
|
+
trigger: string;
|
|
28
|
+
steps: number;
|
|
29
|
+
yuan: number;
|
|
30
|
+
hit: number;
|
|
31
|
+
miss: number;
|
|
32
|
+
out: number;
|
|
33
|
+
tools: Record<string, number>;
|
|
34
|
+
ended: boolean;
|
|
35
|
+
}
|
|
36
|
+
/** `turns` holds the latest few of the day, newest last; a life.json from before it has none. */
|
|
21
37
|
export interface Spend {
|
|
22
38
|
day: string;
|
|
23
39
|
yuan: number;
|
|
24
40
|
reminded?: true;
|
|
41
|
+
turns?: SpendTurn[];
|
|
25
42
|
}
|
|
26
43
|
/**
|
|
27
44
|
* A word steered into her home whose turn has not been seen to start a step yet. It is written before the steer,
|
package/lib/memoryTools.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
2
|
+
import type { AttachmentStore } from '@deepseek-ai/dsh-attachment';
|
|
2
3
|
import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
|
|
3
4
|
import { type Faults } from './faults.ts';
|
|
4
5
|
import type { MemoryService } from './memory.ts';
|
|
@@ -9,13 +10,14 @@ import type { MemoryService } from './memory.ts';
|
|
|
9
10
|
*/
|
|
10
11
|
/** What a tool call returns is resent on every later turn of the loop, so it is kept short: fewer hits, shorter excerpts, no bookkeeping fields. */
|
|
11
12
|
export declare const TOOL_FIND_LIMIT = 8, TOOL_EXCERPT_CHARS = 200, TOOL_READ_LIMIT = 2000;
|
|
12
|
-
|
|
13
|
+
/** `looked`: she paged the newest lines of one chat source (no query, newest first, first page), so it is caught up. */
|
|
14
|
+
export declare function memoryTools(service: MemoryService, inside: () => boolean, looked?: (sourceId: string) => void, images?: () => AttachmentStore | undefined): ToolDefinition[];
|
|
13
15
|
/**
|
|
14
16
|
* Gives world sessions their tools (long-term memory, her mood), whatever the life line does: a session has them
|
|
15
17
|
* while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
|
|
16
18
|
*/
|
|
17
19
|
export declare function createWorldToolRegistry(deps: {
|
|
18
|
-
tools(inside: () => boolean): ToolDefinition[];
|
|
20
|
+
tools(inside: () => boolean, agent: Agent): ToolDefinition[];
|
|
19
21
|
inWorld(agent: Agent): boolean;
|
|
20
22
|
faults: Faults;
|
|
21
23
|
logger: {
|
package/lib/memoryTools.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
2
2
|
import { errorText } from "./faults.js";
|
|
3
|
+
import { imagesMessage, shortenArchivedImages, shownImage, storedImage } from "./images.js";
|
|
3
4
|
import { OutsideWorldError, registerScopedTool } from "./worldScope.js";
|
|
4
5
|
const output = { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: value }] };
|
|
5
6
|
/**
|
|
@@ -15,13 +16,14 @@ function compactFind(page) {
|
|
|
15
16
|
return {
|
|
16
17
|
items: page.items.map(item => ({
|
|
17
18
|
ref: item.ref, time: item.time, kind: item.kind, ...(item.kind === 'conversation' ? {} : { title: item.title }),
|
|
18
|
-
...(who(item.origin) ? { who: who(item.origin) } : {}), ...(item.current ? {} : { old: true }), text: clip(item.excerpt, TOOL_EXCERPT_CHARS),
|
|
19
|
+
...(who(item.origin) ? { who: who(item.origin) } : {}), ...(item.current ? {} : { old: true }), text: clip(shortenArchivedImages(item.excerpt), TOOL_EXCERPT_CHARS),
|
|
19
20
|
})),
|
|
20
21
|
...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
|
|
21
22
|
...(page.coverage.state === 'ready' ? {} : { coverage: page.coverage }),
|
|
22
23
|
};
|
|
23
24
|
}
|
|
24
|
-
|
|
25
|
+
/** `looked`: she paged the newest lines of one chat source (no query, newest first, first page), so it is caught up. */
|
|
26
|
+
export function memoryTools(service, inside, looked, images) {
|
|
25
27
|
const checked = async (work) => {
|
|
26
28
|
if (!inside())
|
|
27
29
|
throw new OutsideWorldError();
|
|
@@ -39,7 +41,13 @@ export function memoryTools(service, inside) {
|
|
|
39
41
|
linkedTo: { type: 'string' }, order: { type: 'string' }, limit: { type: 'integer' }, cursor: { type: 'string' },
|
|
40
42
|
},
|
|
41
43
|
output,
|
|
42
|
-
execute: async (input) =>
|
|
44
|
+
execute: async (input) => {
|
|
45
|
+
const found = compactFind(await checked(() => service.find({ limit: TOOL_FIND_LIMIT, ...input })));
|
|
46
|
+
const { sourceId, query, cursor, order } = input;
|
|
47
|
+
if (typeof sourceId === 'string' && sourceId.startsWith('chat:') && !query && !cursor && (order ?? 'newest') === 'newest')
|
|
48
|
+
looked?.(sourceId);
|
|
49
|
+
return JSON.stringify(found);
|
|
50
|
+
},
|
|
43
51
|
}),
|
|
44
52
|
defineTool({
|
|
45
53
|
name: 'memory_read',
|
|
@@ -48,7 +56,19 @@ export function memoryTools(service, inside) {
|
|
|
48
56
|
output,
|
|
49
57
|
execute: async (input) => {
|
|
50
58
|
const found = await checked(() => service.read({ limit: TOOL_READ_LIMIT, ...input }));
|
|
51
|
-
return JSON.stringify({ ref: found.ref, kind: found.kind, title: found.title, time: found.time, ...(who(found.origin) ? { who: who(found.origin) } : {}), ...(found.turnId ? { turnId: found.turnId } : {}), content: found.content, offset: found.offset, ...(found.nextOffset === undefined ? {} : { nextOffset: found.nextOffset }), totalChars: found.totalChars });
|
|
59
|
+
return JSON.stringify({ ref: found.ref, kind: found.kind, title: found.title, time: found.time, ...(who(found.origin) ? { who: who(found.origin) } : {}), ...(found.turnId ? { turnId: found.turnId } : {}), content: shortenArchivedImages(found.content), offset: found.offset, ...(found.nextOffset === undefined ? {} : { nextOffset: found.nextOffset }), totalChars: found.totalChars });
|
|
60
|
+
},
|
|
61
|
+
}),
|
|
62
|
+
// A picture in memory is one line naming the stored object; the line itself is what brings it back, so nothing is looked up.
|
|
63
|
+
defineTool({
|
|
64
|
+
name: 'memory_image',
|
|
65
|
+
description: '再看一眼记忆里的一张图片。记忆里的图片是一整段 [图片 sha256:… image/jpeg 宽×高 多少字节],把那一整段从 [ 到 ] 原样填进 image。图片会附在下一条消息里。',
|
|
66
|
+
parameters: { image: { type: 'string', required: true } },
|
|
67
|
+
output,
|
|
68
|
+
execute: async ({ image }, context) => {
|
|
69
|
+
const ref = await checked(() => storedImage(images?.(), image, context.signal));
|
|
70
|
+
context.deferContext(imagesMessage(shownImage('这是记忆里的那张图片。', ref)));
|
|
71
|
+
return '图片已附在下一条消息里。';
|
|
52
72
|
},
|
|
53
73
|
}),
|
|
54
74
|
];
|
|
@@ -79,7 +99,7 @@ export function createWorldToolRegistry(deps) {
|
|
|
79
99
|
return false;
|
|
80
100
|
const done = [];
|
|
81
101
|
try {
|
|
82
|
-
for (const tool of deps.tools(() => deps.inWorld(agent)))
|
|
102
|
+
for (const tool of deps.tools(() => deps.inWorld(agent), agent))
|
|
83
103
|
done.push(registerScopedTool(agent, tool, () => deps.inWorld(agent)));
|
|
84
104
|
registered.set(agent, done);
|
|
85
105
|
deps.faults.clear(key(agent));
|
package/lib/mood.d.ts
CHANGED
|
@@ -38,7 +38,11 @@ export declare function moodValues(mood: Extract<Mood, {
|
|
|
38
38
|
kind: 'mood';
|
|
39
39
|
}>): MoodValue[];
|
|
40
40
|
/** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
|
|
41
|
-
|
|
41
|
+
/** When she last changed the file, or undefined when it is gone since it was read. */
|
|
42
|
+
export declare function moodUpdatedAt(path: string): number | undefined;
|
|
43
|
+
/** How long her mood has stood, so she can tell an old one from a fresh one; the plugin never ages the values themselves. */
|
|
44
|
+
export declare function moodAge(updatedAt: number, now: number): string;
|
|
45
|
+
export declare function moodText(mood: Mood, age?: string): string | undefined;
|
|
42
46
|
export type MoodView = {
|
|
43
47
|
kind: 'none';
|
|
44
48
|
} | {
|
package/lib/mood.js
CHANGED
|
@@ -67,12 +67,33 @@ export function moodValues(mood) {
|
|
|
67
67
|
}
|
|
68
68
|
const outsideNote = (names) => `(${names.join('、')} 不在固定的心情里,没有算进去;换成最接近的那个,细的写进小事)`;
|
|
69
69
|
/** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
|
|
70
|
-
|
|
70
|
+
/** When she last changed the file, or undefined when it is gone since it was read. */
|
|
71
|
+
export function moodUpdatedAt(path) {
|
|
72
|
+
try {
|
|
73
|
+
return statSync(path).mtimeMs;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** How long her mood has stood, so she can tell an old one from a fresh one; the plugin never ages the values themselves. */
|
|
80
|
+
export function moodAge(updatedAt, now) {
|
|
81
|
+
const minutes = Math.floor(Math.max(0, now - updatedAt) / 60_000);
|
|
82
|
+
if (minutes < 1)
|
|
83
|
+
return '刚改过';
|
|
84
|
+
if (minutes < 60)
|
|
85
|
+
return `最后改于 ${minutes} 分钟前`;
|
|
86
|
+
const hours = Math.floor(minutes / 60), days = Math.floor(hours / 24);
|
|
87
|
+
if (!days)
|
|
88
|
+
return `最后改于 ${hours} 小时前`;
|
|
89
|
+
return `最后改于 ${days} 天${hours % 24 ? ` ${hours % 24} 小时` : ''}前`;
|
|
90
|
+
}
|
|
91
|
+
export function moodText(mood, age) {
|
|
71
92
|
if (mood.kind === 'none')
|
|
72
93
|
return undefined;
|
|
73
94
|
if (mood.kind === 'failed')
|
|
74
95
|
return '【我的心情值】mood.md 读不出来,之前那条不再算数;可以用 set_mood 重新记。';
|
|
75
|
-
const lines = [`【我的心情值】${moodValues(mood).map(value => `${value.name} ${value.value}`).join(' · ')}
|
|
96
|
+
const lines = [`【我的心情值】${moodValues(mood).map(value => `${value.name} ${value.value}`).join(' · ')}(以最新一条为准,${age ? `${age},` : ''}用 set_mood 改)`];
|
|
76
97
|
if (mood.trivia.length)
|
|
77
98
|
lines.push(`旁边:${mood.trivia.join(';')}${mood.cut ? '……后面还有' : ''}`);
|
|
78
99
|
if (mood.outside.length)
|
|
@@ -86,10 +107,6 @@ export function moodView(path) {
|
|
|
86
107
|
const mood = readMood(path);
|
|
87
108
|
if (mood.kind !== 'mood')
|
|
88
109
|
return mood;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
updatedAt = statSync(path).mtime.toISOString();
|
|
92
|
-
}
|
|
93
|
-
catch { /* removed since it was read; the values still stand */ }
|
|
94
|
-
return { kind: 'mood', values: moodValues(mood), trivia: mood.trivia, cut: mood.cut, unread: mood.unread, outside: mood.outside, updatedAt };
|
|
110
|
+
const changed = moodUpdatedAt(path);
|
|
111
|
+
return { kind: 'mood', values: moodValues(mood), trivia: mood.trivia, cut: mood.cut, unread: mood.unread, outside: mood.outside, updatedAt: changed === undefined ? null : new Date(changed).toISOString() };
|
|
95
112
|
}
|
package/lib/promptSection.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface WorldPromptSource {
|
|
|
18
18
|
inWorkspace?(sessionId: string): boolean;
|
|
19
19
|
/** Long-term memory; its two tools are registered on world sessions. */
|
|
20
20
|
memory?: import('./memory.ts').MemoryService;
|
|
21
|
+
/** News from where she is not, told to her world sessions. */
|
|
22
|
+
elsewhere?: import('./elsewhere.ts').Elsewhere;
|
|
21
23
|
}
|
|
22
24
|
/** Replace the system prompt only for this world's preset and workspace. */
|
|
23
25
|
export declare function createPromptSections(config: WorldConfig, world: WorldPromptSource, token: symbol, deps: {
|
|
@@ -29,6 +31,7 @@ export declare function createPromptSections(config: WorldConfig, world: WorldPr
|
|
|
29
31
|
active(session: Session): boolean;
|
|
30
32
|
/** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
|
|
31
33
|
takeRestart(session: Session): boolean;
|
|
34
|
+
/** Her files are read again at the next assembly; one that already ran keeps what it read. */
|
|
32
35
|
refresh(session: Session): void;
|
|
33
36
|
forget: (agent: Agent) => void;
|
|
34
37
|
clear(): void;
|