dsh-world 0.7.6 → 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 -479
- package/CONTRIBUTING.md +174 -174
- package/INSTALL.md +314 -314
- package/NOTES.md +57 -3
- package/README.md +332 -259
- package/client/index.js +1126 -991
- package/lib/compaction.d.ts +1 -0
- package/lib/compaction.js +1 -1
- 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 +3 -0
- package/lib/ecosystem/qq-native/images.js +18 -6
- package/lib/ecosystem/qq-native/index.js +2 -2
- 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 +1 -0
- package/lib/ecosystem/wechat/reading.d.ts +1 -1
- package/lib/ecosystem/wechat/reading.js +2 -2
- package/lib/history.js +2 -1
- package/lib/images.d.ts +30 -0
- package/lib/images.js +101 -0
- package/lib/index.d.ts +4 -0
- package/lib/index.js +90 -5
- 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 +2 -1
- package/lib/memoryTools.js +16 -3
- package/lib/promptSection.d.ts +1 -0
- package/lib/promptSection.js +29 -42
- package/lib/runtime.js +1 -1
- 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';
|
|
@@ -10,7 +11,7 @@ import type { MemoryService } from './memory.ts';
|
|
|
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. */
|
|
13
|
-
export declare function memoryTools(service: MemoryService, inside: () => boolean, looked?: (sourceId: string) => void): ToolDefinition[];
|
|
14
|
+
export declare function memoryTools(service: MemoryService, inside: () => boolean, looked?: (sourceId: string) => void, images?: () => AttachmentStore | undefined): ToolDefinition[];
|
|
14
15
|
/**
|
|
15
16
|
* Gives world sessions their tools (long-term memory, her mood), whatever the life line does: a session has them
|
|
16
17
|
* while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
|
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,14 +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. */
|
|
25
|
-
export function memoryTools(service, inside, looked) {
|
|
26
|
+
export function memoryTools(service, inside, looked, images) {
|
|
26
27
|
const checked = async (work) => {
|
|
27
28
|
if (!inside())
|
|
28
29
|
throw new OutsideWorldError();
|
|
@@ -55,7 +56,19 @@ export function memoryTools(service, inside, looked) {
|
|
|
55
56
|
output,
|
|
56
57
|
execute: async (input) => {
|
|
57
58
|
const found = await checked(() => service.read({ limit: TOOL_READ_LIMIT, ...input }));
|
|
58
|
-
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 '图片已附在下一条消息里。';
|
|
59
72
|
},
|
|
60
73
|
}),
|
|
61
74
|
];
|
package/lib/promptSection.d.ts
CHANGED
|
@@ -31,6 +31,7 @@ export declare function createPromptSections(config: WorldConfig, world: WorldPr
|
|
|
31
31
|
active(session: Session): boolean;
|
|
32
32
|
/** On in-history routes, start a new series to replace the old prompt instead of appending to it. */
|
|
33
33
|
takeRestart(session: Session): boolean;
|
|
34
|
+
/** Her files are read again at the next assembly; one that already ran keeps what it read. */
|
|
34
35
|
refresh(session: Session): void;
|
|
35
36
|
forget: (agent: Agent) => void;
|
|
36
37
|
clear(): void;
|
package/lib/promptSection.js
CHANGED
|
@@ -1,54 +1,39 @@
|
|
|
1
|
-
import { statSync } from 'node:fs';
|
|
2
1
|
import { readPersona, renderPersona } from "./persona.js";
|
|
3
2
|
import { renderSelf } from "./self.js";
|
|
4
3
|
import { belongsToWorld, inWorld } from "./sourceArchive.js";
|
|
5
|
-
import {
|
|
4
|
+
import { readTemplate, renderWorldPrompt } from "./worldPrompt.js";
|
|
6
5
|
import { syncBetweenSteps } from "./worldScope.js";
|
|
7
6
|
// The complete prompt uses DSH's section name, so the request guard reads ownership from the assembly context.
|
|
8
7
|
export const assembledWorlds = new WeakMap();
|
|
9
8
|
const promptSlots = new WeakMap();
|
|
10
|
-
function cachePromptFile(file, read) {
|
|
11
|
-
let cached;
|
|
12
|
-
return force => {
|
|
13
|
-
let version = '';
|
|
14
|
-
try {
|
|
15
|
-
const stat = file ? statSync(file, { throwIfNoEntry: false }) : undefined;
|
|
16
|
-
if (stat)
|
|
17
|
-
version = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`;
|
|
18
|
-
}
|
|
19
|
-
catch {
|
|
20
|
-
cached = undefined;
|
|
21
|
-
return read();
|
|
22
|
-
}
|
|
23
|
-
if (!force && cached?.version === version)
|
|
24
|
-
return cached.value;
|
|
25
|
-
const value = read();
|
|
26
|
-
cached = { version, value };
|
|
27
|
-
return value;
|
|
28
|
-
};
|
|
29
|
-
}
|
|
30
9
|
/** Replace the system prompt only for this world's preset and workspace. */
|
|
31
10
|
export function createPromptSections(config, world, token, deps) {
|
|
32
11
|
const entries = new Map();
|
|
33
12
|
const agents = new WeakMap();
|
|
34
|
-
|
|
35
|
-
persona: world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '',
|
|
36
|
-
names: world.names?.() ?? world.prompt.names,
|
|
37
|
-
}));
|
|
38
|
-
const template = cachePromptFile(world.prompt.file ?? DEFAULT_TEMPLATE_FILE, () => {
|
|
13
|
+
function readSources() {
|
|
39
14
|
const template = readTemplate(world.prompt.file);
|
|
40
15
|
if (template.error)
|
|
41
16
|
deps.logger.warn(`dsh-world: ${template.error}`);
|
|
42
|
-
return
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
17
|
+
return {
|
|
18
|
+
persona: world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '',
|
|
19
|
+
names: world.names?.() ?? world.prompt.names,
|
|
20
|
+
template: template.text,
|
|
21
|
+
...(config.selfFile ? { self: { file: config.selfFile, text: renderSelf(config.selfFile) } } : {}),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Her files are read when the session opens or enters her workspace, and again only when `refresh` asks (after a
|
|
26
|
+
* compaction, a cold session's return, or the console's apply). The prompt sits at the head of every request, so
|
|
27
|
+
* re-reading it on each save would make the provider bill the whole conversation again after every edit she makes.
|
|
28
|
+
*/
|
|
29
|
+
function render(agent, entry) {
|
|
30
|
+
if (!entry.sources || entry.reload) {
|
|
31
|
+
entry.sources = readSources();
|
|
32
|
+
entry.reload = false;
|
|
33
|
+
}
|
|
34
|
+
const { persona, names, template, self } = entry.sources;
|
|
35
|
+
const body = renderWorldPrompt({ ...world.prompt, names }, template, self, world.isHome(agent.id));
|
|
36
|
+
return [persona, body].filter(Boolean).join('\n\n');
|
|
52
37
|
}
|
|
53
38
|
function sync(agent, entry) {
|
|
54
39
|
const active = inWorld(agent.session, config, world.inWorkspace);
|
|
@@ -68,7 +53,7 @@ export function createPromptSections(config, world, token, deps) {
|
|
|
68
53
|
complete: true,
|
|
69
54
|
interpolate: false,
|
|
70
55
|
text: context => {
|
|
71
|
-
const text = render(agent);
|
|
56
|
+
const text = render(agent, entry);
|
|
72
57
|
assembledWorlds.set(context, { worldId: config.worldId, token, text });
|
|
73
58
|
if (text !== entry.text) {
|
|
74
59
|
entry.text = text;
|
|
@@ -83,6 +68,7 @@ export function createPromptSections(config, world, token, deps) {
|
|
|
83
68
|
entry.restart = true;
|
|
84
69
|
promptSlots.delete(agent);
|
|
85
70
|
delete entry.disposePrompt;
|
|
71
|
+
delete entry.sources; // read afresh when the session comes back into her workspace
|
|
86
72
|
};
|
|
87
73
|
entry.disposePrompt = release;
|
|
88
74
|
promptSlots.set(agent, release);
|
|
@@ -102,7 +88,7 @@ export function createPromptSections(config, world, token, deps) {
|
|
|
102
88
|
if (entries.has(agent) || !belongsToWorld(agent.session, config))
|
|
103
89
|
return;
|
|
104
90
|
// The host captures complete sections before assembly listeners and restores them afterwards.
|
|
105
|
-
const entry = { restart: false, disposeSync: syncBetweenSteps(agent.ctx, current => {
|
|
91
|
+
const entry = { reload: false, restart: false, disposeSync: syncBetweenSteps(agent.ctx, current => {
|
|
106
92
|
if (current === agent)
|
|
107
93
|
sync(agent, entry);
|
|
108
94
|
}) };
|
|
@@ -123,11 +109,12 @@ export function createPromptSections(config, world, token, deps) {
|
|
|
123
109
|
entry.restart = false;
|
|
124
110
|
return true;
|
|
125
111
|
},
|
|
112
|
+
/** Her files are read again at the next assembly; one that already ran keeps what it read. */
|
|
126
113
|
refresh(session) {
|
|
127
114
|
const agent = agents.get(session);
|
|
128
|
-
|
|
129
|
-
if (
|
|
130
|
-
|
|
115
|
+
const entry = agent && entries.get(agent);
|
|
116
|
+
if (entry?.disposePrompt)
|
|
117
|
+
entry.reload = true;
|
|
131
118
|
},
|
|
132
119
|
forget,
|
|
133
120
|
clear() {
|
package/lib/runtime.js
CHANGED
|
@@ -199,7 +199,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
199
199
|
const service = world?.memory;
|
|
200
200
|
const sessionNews = world?.elsewhere ? createSessionNews({ store, isHome: id => !!world.isHome(id), partner: () => world.names?.().partner ?? world.prompt.names.partner }) : undefined;
|
|
201
201
|
const worldTools = (inside, agent) => [
|
|
202
|
-
...service ? memoryTools(service, inside, sourceId => sessionNews?.looked(agent.session, sourceId.slice('chat:'.length))) : [],
|
|
202
|
+
...service ? memoryTools(service, inside, sourceId => sessionNews?.looked(agent.session, sourceId.slice('chat:'.length)), () => ctx.get('attachments')) : [],
|
|
203
203
|
...config.moodFile ? moodTools(config.moodFile, inside) : [],
|
|
204
204
|
];
|
|
205
205
|
const tools = service || config.moodFile ? createWorldToolRegistry({ tools: worldTools, inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
|
package/lib/types.d.ts
CHANGED
|
@@ -36,6 +36,10 @@ export interface WorldConfig {
|
|
|
36
36
|
bridge?: boolean;
|
|
37
37
|
/** The independent local WeChat module; the Windows adapter uses `<world>/wechat.json`. */
|
|
38
38
|
wechat?: boolean;
|
|
39
|
+
/** Her own browser and the tools she makes with it (home only); see src/ecosystem/computer/README.md. */
|
|
40
|
+
computer?: boolean;
|
|
41
|
+
/** She also uses the partner's computer, in the background (Windows; needs `computer`); see src/ecosystem/computer/README.md. */
|
|
42
|
+
desktop?: boolean;
|
|
39
43
|
/** QQ straight to OneBot: no qq-bridge process, the plugin owns the sockets, the sessions and the state. */
|
|
40
44
|
qqNative?: {
|
|
41
45
|
enabled?: boolean;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** The loader id of a world added from the console; the first world keeps whatever id its partner gave it. */
|
|
2
|
+
export declare const worldEntryId: (worldId: string) => string;
|
|
3
|
+
/**
|
|
4
|
+
* Adds one more world to the profile's patch file, as the row the README has partners write by hand. The host's
|
|
5
|
+
* config editor can only change rows that are already loaded, so the row is appended as text: every line already
|
|
6
|
+
* there, comments included, stays as it is. The host reads the file when it starts, so the world appears after a
|
|
7
|
+
* restart. Refuses, with the reason, anything it cannot add safely.
|
|
8
|
+
*/
|
|
9
|
+
export declare function addWorldEntry(patchFile: string, worldId: string, companionName: string): void;
|