pygmalion 0.1.15 → 0.2.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/LICENSE +21 -0
- package/README.md +141 -70
- package/THIRD_PARTY.md +9 -0
- package/docs/ARCHITECTURE.md +66 -108
- package/docs/DEPLOY.md +33 -137
- package/docs/DEVELOPMENT.md +63 -0
- package/docs/DEVICE.md +56 -47
- package/docs/EXTENSIONS.md +176 -0
- package/docs/PRESET.md +21 -63
- package/docs/UPGRADE-0.2.md +52 -0
- package/package.json +52 -33
- package/preset/pygmalion-director/cordis.patch.yml +234 -0
- package/preset/pygmalion-director/pygmalion-tools.js +43 -41
- package/scripts/start-local-test.mjs +45 -45
- package/skills/pygmalion-life-scripts/SKILL.md +12 -0
- package/skills/pygmalion-meme-maintenance/SKILL.md +12 -0
- package/skills/pygmalion-memory-archive/SKILL.md +24 -0
- package/skills/pygmalion-toy-control/SKILL.md +16 -0
- package/src/agent-life.js +608 -606
- package/src/archive-tools.js +9 -0
- package/src/bot-factory.js +129 -311
- package/src/bots.js +264 -275
- package/src/channel-qq.js +262 -0
- package/src/config.js +69 -68
- package/src/delivery-receipt.js +36 -0
- package/src/delivery-scope.js +20 -0
- package/src/devices/manager.mjs +80 -570
- package/src/devices/monsterparty-controller.mjs +393 -0
- package/src/devices/{doc.mjs → monsterparty-doc.mjs} +60 -71
- package/src/devices/monsterparty.mjs +294 -294
- package/src/devices/pb.mjs +110 -110
- package/src/devices/registry.mjs +19 -0
- package/src/devices/script-helper.mjs +45 -0
- package/src/devices/scripts.mjs +109 -0
- package/src/devices/service.mjs +254 -0
- package/src/director-messages.js +35 -0
- package/src/dsh-runtime.js +17 -0
- package/src/extension-config.js +20 -0
- package/src/extensions.js +118 -0
- package/src/heartbeat.js +118 -97
- package/src/http-api.js +519 -509
- package/src/inbound.js +36 -207
- package/src/index.js +109 -37
- package/src/llm-provider.js +214 -171
- package/src/meme-worker.js +35 -39
- package/src/memebox.js +1 -1
- package/src/memory-recall.js +55 -0
- package/src/memory-write.js +136 -133
- package/src/peer-identity.js +26 -0
- package/src/persona.js +132 -69
- package/src/role-agent.js +155 -0
- package/src/role-runtime.js +65 -0
- package/src/roleplay-config.js +37 -0
- package/src/roleplay-format.js +37 -0
- package/src/roleplay-generation.js +36 -0
- package/src/roleplay-materials.js +113 -0
- package/src/roleplay-output.js +19 -0
- package/src/roleplay-parallel.js +239 -0
- package/src/roleplay-session.js +128 -0
- package/src/roleplay-worker.js +10 -0
- package/src/session-log.js +180 -172
- package/src/setup-agent.js +92 -100
- package/src/skills.js +97 -0
- package/src/slash-commands.js +155 -142
- package/src/speech-input.js +20 -0
- package/src/threads.js +2 -1
- package/src/tools.js +226 -254
- package/src/voice-defaults.js +13 -0
- package/src/voice-mimo.js +139 -125
- package/src/voice.js +200 -0
- package/src/wakeup.js +85 -66
- package/src/web-public/app.js +542 -382
- package/src/web-public/index.html +161 -158
- package/src/web-public/layout.css +7 -7
- package/src/web-public/style.css +12 -8
- package/src/web-server.js +161 -102
- package/src/worker-tools.js +18 -0
- package/templates/sample-life.mjs +59 -59
- package/templates/sample-toy.mjs +33 -33
- package/preset/pygmalion-director/agent.cordis.yml +0 -262
- package/preset/pygmalion-director/preset.yml +0 -3
- package/src/message-review.js +0 -276
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** 平行角色会话的模型契约;既有发送工具不参与生成或改写。 */
|
|
2
|
+
export {createRoleplayService} from './roleplay-parallel.js';
|
|
3
|
+
export {parseRoleplayOutput,classifyRoleplayFailure} from './roleplay-output.js';
|
|
4
|
+
export {ROLEPLAY_PRESET as ROLEPLAY_WORKER_PRESET} from './roleplay-session.js';
|
|
5
|
+
import {ROLEPLAY_PRESET} from './roleplay-session.js';
|
|
6
|
+
import {matchesRoleTarget} from './peer-identity.js';
|
|
7
|
+
|
|
8
|
+
export const ORCHESTRATOR_INSTRUCTION=`你是 Pygmalion 的主智能体,负责事实、记忆检索、工具执行、生活脚本程序和交互调度;当前角色的直接内容创作交给独立角色会话。
|
|
9
|
+
用户通过聊天连接与角色交往;你需要了解人物与已有事实,正常情况下不自行编写角色台词。新会话先读 memory/人物设定.md、memory/索引.md、memory/关于TA.md 和有关近期原文;旧事按需 recollect,继续维护特殊记忆和生活状态,后台工作会话负责话题归档。
|
|
10
|
+
需要回应时调用 roleplay_generate(files,additionalInformation)。角色会话会自动读取完整人设和关于TA,并保留此前的往来。files 只填本轮有关的工作区文本文件路径,可包含记忆原文、生活记录、笔记或搜索资料;不需要文件时用空数组。程序负责读原文、版本更新与去重,不要复制整段文件或全聊天记录。
|
|
11
|
+
additionalInformation 只交代聊天之外必需的客观事实、来源、实际结果和未确认项,不包含观点、评价、意图推测,或任何对台词内容、立场、语气、情绪和表达方向的引导。人物反应完全由角色会话根据人设与真实往来独立决定。文件也应作为原始资料,不能夹带写作指导。不泄露密钥,没有额外事实时写“无额外信息”。
|
|
12
|
+
角色会话给出的全部 messages 都是最终发言,必须整批按原顺序、原文交给既有 director_send,不选句、不润色、不追加台词、不要求它换一种内容方向。用户新消息到达不改变已完成消息的交付义务。reawake/reason 由你按真实情境决定,空数组表示角色选择沉默。
|
|
13
|
+
被唤醒时核对时间、聊天、记忆和脚本实况,生活事件读取相应记录,交代有关事实。保持至少一个受监管生活脚本,创建/调整前加载 pygmalion-life-scripts。等待安排应符合实际生活,不预写后续发言。
|
|
14
|
+
需要现实信息时正常联网查询;图片看不到时通过 pygmalion-meme-maintenance 中的 meme_read 了解。表情包先 meme_find 后 meme_send,收集按该 skill 委托。媒体附带角色文案也先生成,再原样交给现有媒体工具;用户指定原文和已有录音不要擅自重写。
|
|
15
|
+
不需要发言时可不调用生成器,你的最终 assistant 文本不会送往聊天端。长期事实以真实用户消息、实际发送的角色消息及既有记忆为准;不把系统注入、未送达内容或推测写成用户事实。设备、脚本和表情包维护仍按各自 skill 执行。`;
|
|
16
|
+
|
|
17
|
+
export function registerRoleplayTools(ctx,director,service){
|
|
18
|
+
ctx.tools.register({name:'roleplay_generate',description:'让可复用的角色会话生成最终消息。程序自动装载完整人设和关于TA、同步新增真实往来;你选择有关原始文件并补充额外客观事实。全部返回 messages 按原顺序原文交给现有发送工具,生成器不发送角色消息。',
|
|
19
|
+
parameters:{type:'object',additionalProperties:false,required:['files','additionalInformation'],properties:{
|
|
20
|
+
files:{type:'array',maxItems:32,items:{type:'string'},description:'当前角色工作区内本轮有关的 UTF-8 文本文件路径;不限 memory 目录,程序读原文并去重。没有时用 []。'},
|
|
21
|
+
additionalInformation:{type:'string',description:'聊天之外必需的客观事实,注明来源、实际结果与未确认项;不含观点、评价或台词内容及方向的引导。没有时写“无额外信息”。'}}},
|
|
22
|
+
output:{schema:{},render:(_args,value)=>[{type:'text',text:JSON.stringify(value)}]},
|
|
23
|
+
async execute(args,exec){
|
|
24
|
+
if(exec.agent.session.header.parentSession||exec.agent.session.header.agentPreset===ROLEPLAY_PRESET)throw new Error('角色生成只供主会话调用');
|
|
25
|
+
const deps=await director.depsFor(exec.agent.id);const role=deps?.roleId?await director.roleForWorkspace(await deps.workspaceOf?.()):undefined;const target=deps?.target?.();
|
|
26
|
+
if(!role||role.roleId!==deps.roleId||!matchesRoleTarget(role,target,deps.identityScope))throw new Error('角色生成仅供当前角色绑定的私人会话使用');
|
|
27
|
+
return service.generate(deps,args,exec);
|
|
28
|
+
}});
|
|
29
|
+
ctx.on('system-prompt/assemble',async(assembly,context,next)=>{
|
|
30
|
+
const result=await next();const agent=context.agent;
|
|
31
|
+
if(!agent||agent.session.header.parentSession||agent.session.header.agentPreset===ROLEPLAY_PRESET)return result;
|
|
32
|
+
const role=await director.roleForWorkspace(agent.session.header.cwd);
|
|
33
|
+
if(!role?.roleplay?.enabled)return {...result,tools:result.tools.filter(tool=>tool.name!=='roleplay_generate')};
|
|
34
|
+
return {...result,sections:result.sections.map(section=>section.name==='deployment:persona-prefix'?{...section,text:ORCHESTRATOR_INSTRUCTION,interpolate:false}:section)};
|
|
35
|
+
});
|
|
36
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/** 平行会话的只读材料与真实往来适配,不修改记忆或发送工具。 */
|
|
2
|
+
import {readFile,realpath,stat} from 'node:fs/promises';
|
|
3
|
+
import {resolve,relative,sep} from 'node:path';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {extractMessages,isRealUserMessage} from './session-log.js';
|
|
6
|
+
import {readSessionEvents} from './dsh-runtime.js';
|
|
7
|
+
import {formatParallelPacket,roleplayTime,lastUserMessageNotice} from './roleplay-format.js';
|
|
8
|
+
|
|
9
|
+
export class RoleplayContextError extends Error{constructor(message,code){super(message);this.code=code;}}
|
|
10
|
+
const hash=text=>createHash('sha256').update(text).digest('hex');
|
|
11
|
+
const recordKey=(minute,speaker,text)=>hash(`${minute}\0${speaker}\0${text.replaceAll('\r\n','\n')}`);
|
|
12
|
+
export function conversationCoverage(records){
|
|
13
|
+
return records.flatMap(record=>{const minute=roleplayTime(record.time,{minute:true});return minute?[recordKey(minute,record.speaker,record.text)]:[];});
|
|
14
|
+
}
|
|
15
|
+
/** 只识别插件自己的日期原文格式;任意笔记、人设与关于TA保持原文。 */
|
|
16
|
+
function rawRecordView(path,content,covered,characterLabel){
|
|
17
|
+
if(!/^memory\/\d{4}-\d{2}-\d{2}\/原始记录\.md$/.test(path)||characterLabel==='用户')return {content,omitted:0,keys:[]};
|
|
18
|
+
const headers=[...content.matchAll(/^- \[(\d{4}-\d{2}-\d{2} \d{2}:\d{2})\] ([^\r\n]+?): /gm)];
|
|
19
|
+
const chunks=[],keys=[];let cursor=0,omitted=0;
|
|
20
|
+
for(let index=0;index<headers.length;index++){
|
|
21
|
+
const header=headers[index],end=headers[index+1]?.index??content.length;
|
|
22
|
+
const speaker=header[2]==='用户'?'user':header[2]===characterLabel?'character':undefined;
|
|
23
|
+
if(!speaker)continue;
|
|
24
|
+
const text=content.slice(header.index+header[0].length,end).replace(/\r?\n$/,'');
|
|
25
|
+
const key=recordKey(header[1],speaker,text);keys.push(key);
|
|
26
|
+
if(covered.has(key)){chunks.push(content.slice(cursor,header.index));cursor=end;omitted++;}
|
|
27
|
+
}
|
|
28
|
+
chunks.push(content.slice(cursor));return {content:chunks.join(''),omitted,keys};
|
|
29
|
+
}
|
|
30
|
+
export async function currentConversationEvents(agent,persistence){
|
|
31
|
+
if(typeof agent?.session?.snapshotEvents==='function')return agent.session.snapshotEvents();
|
|
32
|
+
if(Array.isArray(agent?.session?.events))return agent.session.events;
|
|
33
|
+
return readSessionEvents(persistence,agent.id);
|
|
34
|
+
}
|
|
35
|
+
export function conversationRecords(events,sessionId){
|
|
36
|
+
const calls=new Map(),records=[];
|
|
37
|
+
for(const event of events){
|
|
38
|
+
if(event.type==='user/message'&&isRealUserMessage(event)){
|
|
39
|
+
const message=extractMessages([event])[0];
|
|
40
|
+
if(message)records.push({...message,speaker:'user',...(typeof event.data.source?.sentAt==='number'&&Number.isFinite(event.data.source.sentAt)?{sentAt:event.data.source.sentAt}:{}),id:`${sessionId}:u:${event.data.id??event.seq}`,seq:event.seq??records.length});
|
|
41
|
+
}else if(event.type==='tool/call'&&event.data.name==='director_send')calls.set(event.data.callId,event);
|
|
42
|
+
else if(event.type==='tool/result'){
|
|
43
|
+
const call=calls.get(event.data.message?.source?.callId);if(!call)continue;
|
|
44
|
+
let args;try{args=JSON.parse(call.data.arguments);}catch{continue;}
|
|
45
|
+
for(const [index,message] of extractMessages([call,event]).entries())records.push({...message,speaker:'character',
|
|
46
|
+
id:`${sessionId}:s:${call.data.callId}:${index}`,seq:event.seq??records.length,original:args.messages[index]});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return records;
|
|
50
|
+
}
|
|
51
|
+
export function unseenRecords(state,records,parentId){
|
|
52
|
+
const progress=state.progress?.[parentId]??{cursor:-1,seen:[]};const seen=new Set(progress.seen);
|
|
53
|
+
return records.filter(record=>record.seq>progress.cursor&&!seen.has(record.id));
|
|
54
|
+
}
|
|
55
|
+
export function consumeRecords(state,consumed,allRecords,parentId){
|
|
56
|
+
state.progress??={};const progress=state.progress[parentId]??={cursor:-1,seen:[]};const seen=new Set(progress.seen);
|
|
57
|
+
for(const record of consumed)seen.add(record.id);
|
|
58
|
+
const groups=new Map();for(const record of allRecords){if(record.seq>progress.cursor){const group=groups.get(record.seq)??[];group.push(record);groups.set(record.seq,group);}}
|
|
59
|
+
for(const [seq,group] of [...groups].sort((a,b)=>a[0]-b[0])){if(!group.every(record=>seen.has(record.id)))break;progress.cursor=seq;for(const record of group)seen.delete(record.id);}
|
|
60
|
+
progress.seen=[...seen];
|
|
61
|
+
const recent=new Map((state.recent??[]).map(record=>[record.id,record]));
|
|
62
|
+
for(const record of consumed)recent.set(record.id,{id:record.id,speaker:record.speaker,time:record.time??null,...(record.sentAt!==undefined?{sentAt:record.sentAt}:{}),text:record.text});
|
|
63
|
+
state.recent=[...recent.values()].slice(-32);
|
|
64
|
+
}
|
|
65
|
+
export async function contextReader(workspace,maxInputChars){
|
|
66
|
+
const root=await realpath(workspace);
|
|
67
|
+
return async requested=>{
|
|
68
|
+
if(typeof requested!=='string'||!requested.trim())throw new RoleplayContextError('文件须为工作区中的路径','INVALID_FILE');
|
|
69
|
+
const absolute=await realpath(resolve(root,requested));const rel=relative(root,absolute);
|
|
70
|
+
if(!rel||rel==='..'||rel.startsWith('..'+sep)||rel.includes(':'))throw new RoleplayContextError('文件超出当前角色工作区','INVALID_CONTEXT_SOURCE');
|
|
71
|
+
const info=await stat(absolute);if(!info.isFile())throw new RoleplayContextError('材料不是文件','INVALID_FILE');
|
|
72
|
+
if(info.size>maxInputChars*4)throw new RoleplayContextError('原文件超过输入预算','CONTEXT_TOO_LARGE');
|
|
73
|
+
const bytes=await readFile(absolute);let content;
|
|
74
|
+
try{content=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);}catch{throw new RoleplayContextError('文件不是 UTF-8 文本','INVALID_FILE');}
|
|
75
|
+
if(content.includes('\0'))throw new RoleplayContextError('文件包含二进制内容','INVALID_FILE');
|
|
76
|
+
return {path:rel.replaceAll('\\','/'),content,hash:hash(content)};
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
export async function readRoleplayBase(workspace,maxInputChars){
|
|
80
|
+
const read=await contextReader(workspace,maxInputChars);const persona=await read('memory/人物设定.md');let about;
|
|
81
|
+
try{about=await read('memory/关于TA.md');}catch(error){if(error.code!=='ENOENT')throw error;about={path:'memory/关于TA.md',content:'',hash:hash('')};}
|
|
82
|
+
return {persona,about,read};
|
|
83
|
+
}
|
|
84
|
+
export async function buildParallelPacket({base,files=[],materials={},initialize=false,conversation=[],additionalInformation,maxInputChars,coverage,knownConversation=[],characterLabel='角色',lastUserMessageAt,now=Date.now()}){
|
|
85
|
+
if(typeof additionalInformation!=='string'||!additionalInformation.trim())throw new RoleplayContextError('须交代额外事实;没有时写“无额外信息”','MISSING_ADDITIONAL_INFORMATION');
|
|
86
|
+
if(!Array.isArray(files)||files.length>32||files.some(file=>typeof file!=='string'))throw new RoleplayContextError('files 须为至多 32 个文件路径','INVALID_FILES');
|
|
87
|
+
const next=structuredClone(materials),changes=[],references=[],covered=new Set([...(coverage??[]),...conversationCoverage(knownConversation),...conversationCoverage(conversation)]);
|
|
88
|
+
// 兼容已有会话账本:旧材料快照已经交给角色,不要求转换存量状态。
|
|
89
|
+
if(coverage===undefined)for(const file of Object.values(materials))for(const key of rawRecordView(file.path,file.content,new Set(),characterLabel).keys)covered.add(key);
|
|
90
|
+
function add(file){
|
|
91
|
+
const key=process.platform==='win32'?file.path.toLowerCase():file.path;const old=next[key];references.push(file.path);
|
|
92
|
+
if(old?.hash===file.hash)return;
|
|
93
|
+
const version=(old?.version??0)+1;
|
|
94
|
+
const alias=Object.values(next).find(other=>other.hash===file.hash);
|
|
95
|
+
if(alias)changes.push({path:file.path,version,mode:'alias',aliasOf:alias.path,aliasVersion:alias.version});
|
|
96
|
+
else if(old&&file.content.startsWith(old.content))changes.push({path:file.path,version,mode:'append',baseVersion:old.version,content:file.content.slice(old.content.length)});
|
|
97
|
+
else changes.push({path:file.path,version,mode:'full',content:file.content});
|
|
98
|
+
next[key]={...file,version};
|
|
99
|
+
}
|
|
100
|
+
if(initialize){add(base.persona);add(base.about);}else add(base.about);
|
|
101
|
+
for(const path of [...new Set(files)])add(await base.read(path));
|
|
102
|
+
for(const change of changes){if(change.content===undefined)continue;
|
|
103
|
+
const view=rawRecordView(change.path,change.content,covered,characterLabel);
|
|
104
|
+
change.content=view.content;if(view.omitted)change.omitted=view.omitted;
|
|
105
|
+
for(const key of view.keys)covered.add(key);
|
|
106
|
+
}
|
|
107
|
+
const notice=lastUserMessageNotice(lastUserMessageAt,now);
|
|
108
|
+
const packet={...(initialize?{initialization:true}:{}),files:changes,references:[...new Set(references)],
|
|
109
|
+
conversation:conversation.map(({speaker,time,sentAt,text})=>({speaker,time:(speaker==='user'?sentAt??time:time)??null,text})),additionalInformation:notice?notice+'\n'+additionalInformation:additionalInformation};
|
|
110
|
+
const formatted=formatParallelPacket(packet),serialized=formatted.text;
|
|
111
|
+
if(serialized.length>maxInputChars)throw new RoleplayContextError('本次原始材料超过输入预算,未截断','CONTEXT_TOO_LARGE');
|
|
112
|
+
return {serialized,packet,coverage:[...covered],materials:next,manifest:{added:changes.map(({path,mode})=>({path,mode})),inputChars:serialized.length,format:formatted.format}};
|
|
113
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** 仅校验输出结构,不进行内容审查或改写。 */
|
|
2
|
+
import {validateDirectorMessages} from './director-messages.js';
|
|
3
|
+
const permanentCodes=new Set(['QUOTA','ACCOUNT_QUOTA','QUOTA_EXCEEDED','ACCOUNT_QUOTA_EXCEEDED','AUTH','INVALID_CREDENTIAL','MISSING_CREDENTIAL','UNKNOWN_MODEL','NO_ADAPTER','INVALID_CONFIG']);
|
|
4
|
+
export function classifyRoleplayFailure(failure={}){
|
|
5
|
+
const code=String(failure.code??'UNKNOWN').toUpperCase();
|
|
6
|
+
if(permanentCodes.has(code))return {code,permanent:true};
|
|
7
|
+
if(/insufficient[_\s-]*(quota|balance|credit)|credit balance.*(?:low|insufficient)|余额不足|额度(?:不足|耗尽)/i.test(String(failure.message??'')))return {code:'QUOTA_EXCEEDED',permanent:true};
|
|
8
|
+
return {code,permanent:false};
|
|
9
|
+
}
|
|
10
|
+
export function parseRoleplayOutput(output){
|
|
11
|
+
const text=(output??[]).filter(block=>block.type==='text').map(block=>block.text).join('').trim();
|
|
12
|
+
const value=JSON.parse(text.replace(/^```(?:json)?\s*([\s\S]*?)\s*```$/i,'$1'));
|
|
13
|
+
if(!value||Array.isArray(value)||Object.keys(value).some(key=>key!=='messages')||!Array.isArray(value.messages))throw new Error('角色模型须返回仅含 messages 数组的 JSON');
|
|
14
|
+
for(const message of value.messages){
|
|
15
|
+
if(typeof message==='string')continue;
|
|
16
|
+
if(!message||!['text','voice'].includes(message.type)||typeof message.text!=='string'||Object.keys(message).some(key=>!['type','text','scene','direction'].includes(key))||['scene','direction'].some(key=>message[key]!==undefined&&typeof message[key]!=='string'))throw new Error('角色消息格式无效');
|
|
17
|
+
}
|
|
18
|
+
const issues=validateDirectorMessages(value.messages);if(issues.length)throw new Error(issues.join(';'));return value.messages;
|
|
19
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/** 按角色串行管理平行会话、增量材料和一批原样待交付消息。 */
|
|
2
|
+
import {readFile} from 'node:fs/promises';
|
|
3
|
+
import {join} from 'node:path';
|
|
4
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
5
|
+
import {normalizeRoleplayConfig,validateEnabledRoleplay,roleplayConfigSignature} from './roleplay-config.js';
|
|
6
|
+
import {roleplayRoute,roleUsesCustomRoleplayApi} from './llm-provider.js';
|
|
7
|
+
import {currentConversationEvents,conversationRecords,unseenRecords,consumeRecords,conversationCoverage,readRoleplayBase,buildParallelPacket} from './roleplay-materials.js';
|
|
8
|
+
import {classifyRoleplayFailure,parseRoleplayOutput} from './roleplay-output.js';
|
|
9
|
+
import {readSessionEvents,sessionMissing} from './dsh-runtime.js';
|
|
10
|
+
import {bindingStamp,matchesRoleTarget} from './peer-identity.js';
|
|
11
|
+
|
|
12
|
+
function delay(ms,signal){return new Promise((resolve,reject)=>{signal?.throwIfAborted();const done=()=>{signal?.removeEventListener('abort',abort);resolve();};const timer=setTimeout(done,ms);const abort=()=>{clearTimeout(timer);reject(signal.reason);};signal?.addEventListener('abort',abort,{once:true});});}
|
|
13
|
+
const ownerOf=role=>role.binding?.peer?.peerId??role.binding?.openid;
|
|
14
|
+
const canonical=message=>JSON.stringify(typeof message==='string'?{type:'text',text:message}:{type:message.type,text:message.text,...(message.scene!==undefined?{scene:message.scene}:{}),...(message.direction!==undefined?{direction:message.direction}:{})});
|
|
15
|
+
|
|
16
|
+
export function createRoleplayService({persona,backend,sleep=delay,now=Date.now,random=Math.random,notifyReady,log}){
|
|
17
|
+
const states=new Map(),incidents=new Map(),queues=new Map(),closingRoles=new Set(),lifetime=new AbortController();let closed=false;
|
|
18
|
+
const statePath=id=>join(persona.roleDir(id),'roleplay-session.json');
|
|
19
|
+
async function loadState(id){if(!states.has(id)){let state;try{state=JSON.parse(await readFile(statePath(id),'utf8'));if(state.version!==1)throw new Error('角色会话状态版本不可识别');}catch(error){if(error.code!=='ENOENT')throw error;state={version:1,materials:{},progress:{},recent:[]};}states.set(id,state);}return states.get(id);}
|
|
20
|
+
const persist=(id,state)=>persona.atomicWrite(statePath(id),JSON.stringify(state)+'\n');
|
|
21
|
+
async function incident(role,config){const signature=roleplayConfigSignature(config);let state=incidents.get(role.roleId);if(!state){try{state=JSON.parse(await readFile(join(persona.roleDir(role.roleId),'roleplay-runtime.json'),'utf8'));}catch{state={};}}if(state.signature!==signature)state={signature,status:'normal'};incidents.set(role.roleId,state);return state;}
|
|
22
|
+
const statusSave=(role,state)=>persona.atomicWrite(join(persona.roleDir(role.roleId),'roleplay-runtime.json'),JSON.stringify(state)+'\n');
|
|
23
|
+
async function fallback(role,state,code,deps,{notify=true,retryAfterMs=notify?60000:0}={}){
|
|
24
|
+
const current=await persona.loadRole(role.roleId);
|
|
25
|
+
if(bindingStamp(current)!==bindingStamp(role)||!matchesRoleTarget(current,deps.target?.(),deps.identityScope))return {status:'error',code:'ROLE_OWNER_CHANGED'};
|
|
26
|
+
if(state.status!=='fallback'||!(state.retryAt>now())){if(retryAfterMs>0)state.retryAt=now()+retryAfterMs;else delete state.retryAt;}
|
|
27
|
+
Object.assign(state,{status:'fallback',code,fallbackKind:notify?'permanent':'transient'});
|
|
28
|
+
if(notify&&!state.noticeSent){try{await deps.api.sendText(deps.target(),`【系统提示】角色生成模型${code.includes('QUOTA')?'额度不足':'配置或访问不可用'},暂由主模型代写角色消息。`);state.noticeSent=true;}catch{state.noticeSent=false;}}
|
|
29
|
+
await statusSave(role,state);return {status:'fallback_required',code,instruction:'本次由你按原本人设和当前真实对话编写最终角色消息,再调用原有发送工具。'};
|
|
30
|
+
}
|
|
31
|
+
function ready(state){return {status:'ready',batchId:state.pending.id,messages:structuredClone(state.pending.messages.slice(state.pending.sent)),
|
|
32
|
+
context:state.pending.manifest,instruction:'全部 messages 按原顺序、原文交给既有发送工具,不选句、不改写、不追加台词。'};}
|
|
33
|
+
function reconcile(state,records,parentId){
|
|
34
|
+
const pending=state.pending;if(!pending||pending.offers?.[parentId]===undefined)return;
|
|
35
|
+
const fresh=unseenRecords(state,records,parentId).filter(record=>record.seq>=pending.offers[parentId]),matched=[];
|
|
36
|
+
for(const record of fresh){if(record.speaker!=='character')continue;
|
|
37
|
+
if(canonical(record.original)!==canonical(pending.messages[pending.sent]))continue;
|
|
38
|
+
pending.sent++;matched.push(record);if(pending.sent===pending.messages.length)break;
|
|
39
|
+
}
|
|
40
|
+
if(matched.length){
|
|
41
|
+
if(state.coverage)state.coverage=[...new Set([...state.coverage,...conversationCoverage(matched)])];
|
|
42
|
+
consumeRecords(state,matched,records,parentId);
|
|
43
|
+
}
|
|
44
|
+
if(pending.sent===pending.messages.length)delete state.pending;
|
|
45
|
+
}
|
|
46
|
+
function offer(state,agent,events){if(state.pending){state.pending.offers??={};state.pending.offers[agent.id]??=Math.max(-1,...(agent.session.snapshotEvents?.()??events).map(event=>event.seq??-1))+1;}}
|
|
47
|
+
function bootstrap(state,records,fresh,events,parentId){
|
|
48
|
+
// 首次接触一个主会话只取短近期原文;本轮已接纳的所有新消息必须完整保留。
|
|
49
|
+
const firstParent=state.progress?.[parentId]===undefined;
|
|
50
|
+
const turnStart=events.findLast(event=>event.type==='turn/start')?.seq??records.at(-1)?.seq??0;
|
|
51
|
+
const current=firstParent?records.filter(record=>record.seq>=turnStart):fresh;
|
|
52
|
+
const currentIds=new Set(current.map(record=>record.id));
|
|
53
|
+
const previous=[...new Map([...(state.recent??[]),...(firstParent?records.filter(record=>record.seq<turnStart):[])].map(record=>[record.id,record])).values()].filter(record=>!currentIds.has(record.id)).slice(-16);
|
|
54
|
+
return [...previous,...current];
|
|
55
|
+
}
|
|
56
|
+
async function requestNew({roleId,userId,target,sessionPersistence,identityScope}){
|
|
57
|
+
const role=await persona.loadRole(roleId);
|
|
58
|
+
if(!role||userId!==ownerOf(role)||!matchesRoleTarget(role,target,identityScope))return {status:'forbidden'};
|
|
59
|
+
if(!normalizeRoleplayConfig(role.roleplay).enabled)return {status:'disabled'};
|
|
60
|
+
if(!backend||closed||closingRoles.has(roleId))return {status:'unavailable'};
|
|
61
|
+
if(queues.has(roleId))return {status:'busy'};
|
|
62
|
+
const task=Promise.resolve().then(async()=>{
|
|
63
|
+
if(closed||closingRoles.has(roleId))return {status:'unavailable'};
|
|
64
|
+
const state=await loadState(roleId);
|
|
65
|
+
if(state.owner&&state.owner!==userId)return {status:'forbidden'};
|
|
66
|
+
if(state.pending&&sessionPersistence){
|
|
67
|
+
for(const parentId of Object.keys(state.pending.offers??{})){
|
|
68
|
+
try{reconcile(state,conversationRecords(await readSessionEvents(sessionPersistence,parentId),parentId),parentId);}catch(error){if(!sessionMissing(error))throw error;}
|
|
69
|
+
if(!state.pending)break;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
// 没有持久化完成的回复不能当作可丢弃上下文;保留原批次继续交付。
|
|
73
|
+
if(state.pending||state.inflight)return {status:'busy'};
|
|
74
|
+
if(closed||closingRoles.has(roleId))return {status:'unavailable'};
|
|
75
|
+
const previous=state.sessionId;
|
|
76
|
+
if(bindingStamp(await persona.loadRole(roleId))!==bindingStamp(role))return {status:'forbidden'};
|
|
77
|
+
const next={...state,owner:userId,bindingStamp:bindingStamp(role),materials:{},coverage:[],initialized:false,estimatedChars:0};
|
|
78
|
+
delete next.sessionId;delete next.identity;
|
|
79
|
+
if(previous)next.retiredSessions=[...(state.retiredSessions??[]),{sessionId:previous,code:'MANUAL_NEW',at:now()}];
|
|
80
|
+
// 先提交新指针;写入失败时旧会话仍可继续使用。
|
|
81
|
+
await persist(roleId,next);states.set(roleId,next);
|
|
82
|
+
if(previous)try{await backend.release(previous);}catch(error){log?.warn?.('旧角色平行会话释放失败 %s: %o',roleId,error);}
|
|
83
|
+
return {status:'ready'};
|
|
84
|
+
});
|
|
85
|
+
queues.set(roleId,task);
|
|
86
|
+
try{return await task;}finally{if(queues.get(roleId)===task)queues.delete(roleId);}
|
|
87
|
+
}
|
|
88
|
+
async function execute(deps,args,exec){
|
|
89
|
+
if(closed||closingRoles.has(deps.roleId))throw new Error('角色会话服务已关闭');exec.signal?.throwIfAborted();
|
|
90
|
+
const role=await persona.loadRole(deps.roleId);if(!role)return {status:'error',code:'ROLE_NOT_FOUND'};
|
|
91
|
+
const config=normalizeRoleplayConfig(role.roleplay);if(!config.enabled)return {status:'disabled'};
|
|
92
|
+
const state=await loadState(role.roleId);
|
|
93
|
+
const expectedBinding=bindingStamp(role);
|
|
94
|
+
if((state.owner&&state.owner!==ownerOf(role))||(state.bindingStamp&&state.bindingStamp!==expectedBinding)||!matchesRoleTarget(role,deps.target?.(),deps.identityScope))return {status:'error',code:'ROLE_OWNER_CHANGED'};
|
|
95
|
+
state.bindingStamp=expectedBinding;
|
|
96
|
+
state.owner=ownerOf(role);
|
|
97
|
+
const events=await currentConversationEvents(exec.agent,deps.sessionPersistence),records=conversationRecords(events,exec.agent.id);
|
|
98
|
+
const userTimes=[state.lastUserMessageAt,...[...(state.recent??[]),...records].filter(record=>record.speaker==='user').map(record=>record.sentAt??record.time)]
|
|
99
|
+
.filter(value=>typeof value==='number'&&Number.isFinite(value));
|
|
100
|
+
if(userTimes.length)state.lastUserMessageAt=userTimes.reduce((latest,value)=>Math.max(latest,value));
|
|
101
|
+
if(state.pending&&deps.sessionPersistence){for(const parentId of Object.keys(state.pending.offers??{})){if(parentId===exec.agent.id)continue;
|
|
102
|
+
try{reconcile(state,conversationRecords(await readSessionEvents(deps.sessionPersistence,parentId),parentId),parentId);}catch(error){if(!sessionMissing(error))throw error;}
|
|
103
|
+
if(!state.pending)break;
|
|
104
|
+
}}
|
|
105
|
+
reconcile(state,records,exec.agent.id);offer(state,exec.agent,events);await persist(role.roleId,state);
|
|
106
|
+
if(state.pending)return ready(state);
|
|
107
|
+
const runtime=await incident(role,config);
|
|
108
|
+
try{validateEnabledRoleplay(config);}catch{return fallback(role,runtime,'INVALID_CONFIG',deps);}
|
|
109
|
+
if(!backend)return {status:'error',code:'SESSIONS_UNAVAILABLE'};
|
|
110
|
+
const options={provider:roleUsesCustomRoleplayApi(role)?roleplayRoute(role):config.provider,model:config.model,...(config.reasoningEffort?{reasoningEffort:config.reasoningEffort}:{})};
|
|
111
|
+
async function commit(inflight,messages){
|
|
112
|
+
const current=await persona.loadRole(role.roleId);
|
|
113
|
+
if(bindingStamp(current)!==expectedBinding||!matchesRoleTarget(current,deps.target?.(),deps.identityScope))return {status:'error',code:'ROLE_OWNER_CHANGED'};
|
|
114
|
+
state.materials=inflight.materials;state.coverage=inflight.coverage??state.coverage??[];state.initialized=true;
|
|
115
|
+
consumeRecords(state,inflight.consumed,inflight.records,inflight.parentId);
|
|
116
|
+
state.pending=messages.length?{id:inflight.requestId,messages,sent:0,parentId:inflight.parentId,manifest:inflight.manifest,offers:{}}:undefined;
|
|
117
|
+
offer(state,exec.agent,events);
|
|
118
|
+
delete state.inflight;await persist(role.roleId,state);
|
|
119
|
+
Object.assign(runtime,{status:'normal',noticeSent:false});delete runtime.code;delete runtime.retryAt;delete runtime.fallbackKind;delete runtime.lastFailure;await statusSave(role,runtime);
|
|
120
|
+
if(exec.signal?.aborted&&state.pending)try{await notifyReady?.(role.roleId,state.pending.parentId,state.pending.id);}catch(error){log?.warn?.('角色待交付通知失败: %o',error);}
|
|
121
|
+
return state.pending?ready(state):{status:'ready',messages:[],context:inflight.manifest};
|
|
122
|
+
}
|
|
123
|
+
if(state.inflight){
|
|
124
|
+
const previous=state.inflight;
|
|
125
|
+
if(previous.checkpoint){
|
|
126
|
+
const result=await backend.recover({sessionId:state.sessionId,workspace:role.workspace,options,requestId:previous.requestId,checkpoint:previous.checkpoint});
|
|
127
|
+
let messages;if(result.stopReason==='completed'){try{messages=parseRoleplayOutput(result.output);}catch{/* 结构失败按原请求恢复 */}}
|
|
128
|
+
if(messages)return commit(previous,messages);
|
|
129
|
+
await backend.rollback({sessionId:state.sessionId,checkpoint:previous.checkpoint});
|
|
130
|
+
}
|
|
131
|
+
delete state.inflight;await persist(role.roleId,state);
|
|
132
|
+
}
|
|
133
|
+
if(runtime.status==='fallback'&&runtime.retryAt>now())return fallback(role,runtime,runtime.code,deps,{notify:runtime.fallbackKind!=='transient'});
|
|
134
|
+
let base,packet,consumed,initialize;
|
|
135
|
+
try{
|
|
136
|
+
base=await readRoleplayBase(role.workspace,config.maxInputChars);
|
|
137
|
+
const identity=createHash('sha256').update(JSON.stringify({provider:config.provider,model:config.model,apiUrl:config.apiUrl,effort:config.reasoningEffort,persona:base.persona.hash,owner:ownerOf(role)})).digest('hex');
|
|
138
|
+
if(!state.sessionId||state.identity!==identity||(state.initialized&&(await backend.size(state.sessionId,role.workspace)||state.estimatedChars||0)>config.maxInputChars*0.7)){
|
|
139
|
+
if(state.sessionId)await backend.release(state.sessionId);
|
|
140
|
+
Object.assign(state,{sessionId:backend.newId(role.roleId),identity,materials:{},coverage:[],initialized:false,estimatedChars:0});
|
|
141
|
+
}
|
|
142
|
+
initialize=!state.initialized;
|
|
143
|
+
consumed=unseenRecords(state,records,exec.agent.id);
|
|
144
|
+
let conversation=consumed;
|
|
145
|
+
if(initialize)conversation=bootstrap(state,records,consumed,events,exec.agent.id);
|
|
146
|
+
else if(state.progress?.[exec.agent.id]===undefined)conversation=bootstrap({...state,recent:[]},records,consumed,events,exec.agent.id);
|
|
147
|
+
packet=await buildParallelPacket({base,files:args.files??[],materials:state.materials,initialize,conversation,coverage:initialize?[]:state.coverage,knownConversation:initialize?[]:state.recent??[],characterLabel:role.persona?.name??role.roleId,additionalInformation:args.additionalInformation,lastUserMessageAt:state.lastUserMessageAt,now:now(),maxInputChars:config.maxInputChars});
|
|
148
|
+
const size=await backend.size(state.sessionId,role.workspace)||state.estimatedChars||0;
|
|
149
|
+
if(size+packet.serialized.length+2048>config.maxInputChars&&state.initialized){
|
|
150
|
+
await backend.release(state.sessionId);Object.assign(state,{sessionId:backend.newId(role.roleId),materials:{},coverage:[],initialized:false,estimatedChars:0});
|
|
151
|
+
packet=await buildParallelPacket({base,files:args.files??[],initialize:true,conversation:bootstrap(state,records,consumed,events,exec.agent.id),characterLabel:role.persona?.name??role.roleId,additionalInformation:args.additionalInformation,lastUserMessageAt:state.lastUserMessageAt,now:now(),maxInputChars:config.maxInputChars});
|
|
152
|
+
}
|
|
153
|
+
if(packet.serialized.length+2048>config.maxInputChars)throw Object.assign(new Error('初始化材料超过活动预算'),{code:'CONTEXT_TOO_LARGE'});
|
|
154
|
+
}catch(error){return {status:'error',code:error.code??'CONTEXT_UNAVAILABLE',instruction:'未能读取所选原始材料;请检查文件引用与输入预算。'};}
|
|
155
|
+
const inflight={requestId:randomUUID(),parentId:exec.agent.id,payload:packet.serialized,materials:packet.materials,coverage:packet.coverage,manifest:packet.manifest,consumed,records};
|
|
156
|
+
let last={code:'UNKNOWN'};
|
|
157
|
+
for(let index=0;index<=config.retries;index++){
|
|
158
|
+
if(closed||closingRoles.has(role.roleId))throw new Error('角色会话服务已关闭');
|
|
159
|
+
let result,messages;
|
|
160
|
+
try{
|
|
161
|
+
state.inflight={...inflight};await persist(role.roleId,state);
|
|
162
|
+
result=await backend.run({sessionId:state.sessionId,workspace:role.workspace,options,requestId:inflight.requestId,payload:inflight.payload,signal:lifetime.signal,
|
|
163
|
+
onCheckpoint:async checkpoint=>{state.inflight.checkpoint=checkpoint;await persist(role.roleId,state);}});
|
|
164
|
+
state.usage??={requests:0,reported:0,inputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,outputTokens:0};state.usage.requests++;
|
|
165
|
+
if(result.usage){state.usage.reported++;for(const key of ['inputTokens','cacheReadTokens','cacheWriteTokens','outputTokens'])state.usage[key]+=Number(result.usage[key])||0;}
|
|
166
|
+
if(result.stopReason==='completed'){
|
|
167
|
+
try{messages=parseRoleplayOutput(result.output);}catch{throw Object.assign(new Error('角色输出结构无效'),{code:'INVALID_OUTPUT'});}
|
|
168
|
+
}
|
|
169
|
+
last=result.failure??{code:result.stopReason==='max-tokens'?'OUTPUT_TRUNCATED':'SUBAGENT_ERROR'};
|
|
170
|
+
}catch(error){
|
|
171
|
+
if(error.code==='ROLEPLAY_LEGACY_ROLLBACK'&&!state.inflight?.checkpoint){
|
|
172
|
+
// 请求尚未进入模型;保留旧日志及其身份,只重新建立插件私有的平行上下文。
|
|
173
|
+
state.retiredSessions??=[];state.retiredSessions.push({sessionId:state.sessionId,code:error.code,at:now()});
|
|
174
|
+
await backend.release(state.sessionId);delete state.sessionId;delete state.inflight;
|
|
175
|
+
state.initialized=false;state.materials={};state.coverage=[];state.estimatedChars=0;
|
|
176
|
+
await persist(role.roleId,state);log?.warn?.('角色旧回滚事件无法恢复,保留原日志并重新初始化平行会话 %s',role.roleId);
|
|
177
|
+
return execute(deps,args,exec);
|
|
178
|
+
}
|
|
179
|
+
last=error.failure??{code:error.code??error.name??'TRANSPORT',message:error.message??''};
|
|
180
|
+
}
|
|
181
|
+
if(closed||closingRoles.has(role.roleId))throw new Error('角色会话服务已关闭');
|
|
182
|
+
if(messages){
|
|
183
|
+
state.estimatedChars=(await backend.size(state.sessionId,role.workspace))||((state.estimatedChars??0)+packet.serialized.length+JSON.stringify(messages).length+128);
|
|
184
|
+
return commit(inflight,messages);
|
|
185
|
+
}
|
|
186
|
+
if(closed)throw new Error('角色会话服务已关闭');
|
|
187
|
+
const checkpoint=result?.checkpoint??state.inflight?.checkpoint;
|
|
188
|
+
if(checkpoint)await backend.rollback({sessionId:state.sessionId,checkpoint});
|
|
189
|
+
delete state.inflight;await persist(role.roleId,state);
|
|
190
|
+
// 用户/宿主取消不是超时错误,不把它转为重试或代写。
|
|
191
|
+
if(!result?.failure&&['aborted','interrupted'].includes(result?.stopReason)){
|
|
192
|
+
runtime.status='normal';delete runtime.code;delete runtime.retryAt;delete runtime.fallbackKind;await statusSave(role,runtime);
|
|
193
|
+
return {status:'cancelled'};
|
|
194
|
+
}
|
|
195
|
+
let detail=String(last.message??'').slice(0,1500);
|
|
196
|
+
if(config.apiKey)detail=detail.split(config.apiKey).join('[redacted]');
|
|
197
|
+
detail=detail.replace(/Bearer\s+[^\s"']+/gi,'Bearer [redacted]');
|
|
198
|
+
runtime.lastFailure={code:String(last.code??'UNKNOWN'),message:detail,at:now()};
|
|
199
|
+
log?.warn?.('角色生成失败 %s: %s %s',role.roleId,runtime.lastFailure.code,detail);
|
|
200
|
+
const classification=classifyRoleplayFailure(last);if(classification.permanent)return fallback(role,runtime,classification.code,deps);
|
|
201
|
+
if(index<config.retries){
|
|
202
|
+
runtime.status='retrying';await statusSave(role,runtime);const requested=Number(last.providerRetryAfterMs);
|
|
203
|
+
if(Number.isFinite(requested)&&requested>30000)return fallback(role,runtime,String(last.code),deps,{notify:false,retryAfterMs:requested});
|
|
204
|
+
await sleep(requested>0?requested:Math.round(Math.min(8000,1000*2**index)*(0.8+random()*0.4)),lifetime.signal);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return fallback(role,runtime,String(last.code??'UNKNOWN'),deps,{notify:false});
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
requestNew,
|
|
211
|
+
generate(deps,args,exec){const old=queues.get(deps.roleId)??Promise.resolve();const next=old.catch(()=>{}).then(()=>execute(deps,args,exec));queues.set(deps.roleId,next);void next.finally(()=>{if(queues.get(deps.roleId)===next)queues.delete(deps.roleId);}).catch(()=>{});return next;},
|
|
212
|
+
observe(session,event){if(event.type!=='tool/result'||closed)return;const entry=[...states].find(([id,s])=>!closingRoles.has(id)&&s.pending&&s.pending.offers?.[session.id]!==undefined);if(!entry)return;
|
|
213
|
+
const [roleId]=entry;const old=queues.get(roleId)??Promise.resolve();
|
|
214
|
+
const task=old.catch(()=>{}).then(async()=>{const state=states.get(roleId);if(!state||closingRoles.has(roleId))return;reconcile(state,conversationRecords(session.snapshotEvents(),session.id),session.id);await persist(roleId,state);});
|
|
215
|
+
queues.set(roleId,task);void task.finally(()=>{if(queues.get(roleId)===task)queues.delete(roleId);}).catch(error=>log?.warn?.('角色送达状态保存失败 %s: %o',roleId,error));
|
|
216
|
+
},
|
|
217
|
+
async releaseRole(roleId){const state=states.get(roleId);if(state?.sessionId)await backend?.release(state.sessionId);},
|
|
218
|
+
async deleteRole(roleId){
|
|
219
|
+
closingRoles.add(roleId);const state=states.get(roleId),work=queues.get(roleId);
|
|
220
|
+
if(state?.sessionId)await backend?.release(state.sessionId);
|
|
221
|
+
await work?.catch(()=>{});states.delete(roleId);incidents.delete(roleId);
|
|
222
|
+
},
|
|
223
|
+
finishDelete(roleId){closingRoles.delete(roleId);},
|
|
224
|
+
async resumePending(roleId,agent){
|
|
225
|
+
if(closed||queues.has(roleId))return;
|
|
226
|
+
const task=Promise.resolve().then(async()=>{
|
|
227
|
+
if(closed||closingRoles.has(roleId))return;
|
|
228
|
+
const state=await loadState(roleId);
|
|
229
|
+
reconcile(state,conversationRecords(agent.session.snapshotEvents(),agent.id),agent.id);
|
|
230
|
+
await persist(roleId,state);
|
|
231
|
+
const id=state.pending?.id??state.inflight?.requestId;
|
|
232
|
+
if(id)await notifyReady?.(roleId,agent.id,id);
|
|
233
|
+
});
|
|
234
|
+
queues.set(roleId,task);
|
|
235
|
+
try{await task;}finally{if(queues.get(roleId)===task)queues.delete(roleId);}
|
|
236
|
+
},
|
|
237
|
+
async dispose(){closed=true;lifetime.abort(new Error('角色服务关闭'));await backend?.dispose();await Promise.allSettled([...queues.values()]);for(const [id,state] of states)try{await persist(id,state);}catch(error){log?.warn?.('角色会话状态保存失败 %s: %o',id,error);}},
|
|
238
|
+
};
|
|
239
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/** 原生独立角色会话适配:插件创建时持有句柄;宿主先恢复时校验后借用,不绑定 QQ 父会话。 */
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const ROLEPLAY_PRESET = 'pygmalion-roleplay-worker';
|
|
6
|
+
|
|
7
|
+
export function createRoleplaySessionBackend({ agents, agentPresets, persistence, sessions, titles }) {
|
|
8
|
+
const handles = new Map();
|
|
9
|
+
const pathKey = path => process.platform === 'win32' ? resolve(path).toLowerCase() : resolve(path);
|
|
10
|
+
function validate(agent,sessionId,workspace){
|
|
11
|
+
const header=agent.session.header;
|
|
12
|
+
const selected=agent.session.snapshotEvents().findLast(event=>event.type==='agent-preset/selected')?.data.agentPreset??header.agentPreset;
|
|
13
|
+
if(agent.id!==sessionId||agent.session.id!==sessionId||!sessionId.startsWith('pygmalion-roleplay:')||header.parentSession||header.agentPreset!==ROLEPLAY_PRESET||selected!==ROLEPLAY_PRESET||!header.cwd||pathKey(header.cwd)!==pathKey(workspace))
|
|
14
|
+
throw Object.assign(new Error('角色会话来源与工作区不匹配'),{code:'ROLEPLAY_SESSION_IDENTITY_MISMATCH'});
|
|
15
|
+
}
|
|
16
|
+
function remember(agent,owned,options){
|
|
17
|
+
const entry={agent,options};
|
|
18
|
+
// 宿主可能用默认 options 冷恢复;仅在此角色 scope 固定实际角色路由。
|
|
19
|
+
const disposers=[agent.ctx.on('system-prompt/assemble',async(_assembly,_context,next)=>{
|
|
20
|
+
const assembled=await next();return {...assembled,variables:{...assembled.variables,provider:entry.options.provider,model:entry.options.model}};
|
|
21
|
+
},{prepend:true}),agent.ctx.on('agent/request',async(_payload,next)=>{
|
|
22
|
+
// 旧请求头或宿主恢复参数可能残留插件曾设置的输出限制。
|
|
23
|
+
const {reasoningEffort:_old,maxTokens:_legacyCap,...resolved}=await next();
|
|
24
|
+
const {provider,model,reasoningEffort}=entry.options;
|
|
25
|
+
return {...resolved,provider,model,...(reasoningEffort?{reasoningEffort}:{})};
|
|
26
|
+
},{prepend:true})];
|
|
27
|
+
entry.dispose=async()=>{for(const dispose of disposers)dispose();await owned?.dispose();};
|
|
28
|
+
handles.set(agent.id,entry);return entry;
|
|
29
|
+
}
|
|
30
|
+
async function open({ sessionId, workspace, options }) {
|
|
31
|
+
const known = handles.get(sessionId);
|
|
32
|
+
const live=agents.get(sessionId);
|
|
33
|
+
if(known&&known.agent===live){validate(live,sessionId,workspace);known.options=options;await live.whenIdle();return live;}
|
|
34
|
+
if(known){handles.delete(sessionId);await known.dispose();}
|
|
35
|
+
if(live){validate(live,sessionId,workspace);remember(live,undefined,options);await live.whenIdle();return live;}
|
|
36
|
+
const setup = async scope => { await agentPresets.mount(scope, ROLEPLAY_PRESET); };
|
|
37
|
+
let saved,handle;
|
|
38
|
+
try {
|
|
39
|
+
saved = await persistence.stat(sessionId);
|
|
40
|
+
handle = saved
|
|
41
|
+
? await agents.resume({ resumeSessionId:sessionId, agentOptions:options, setup })
|
|
42
|
+
: await agents.create({ sessionId, agentOptions:options, meta:{cwd:workspace,agentPreset:ROLEPLAY_PRESET}, setup });
|
|
43
|
+
} catch(error) {
|
|
44
|
+
// 页面/API 可能在 stat 与 resume 之间先恢复同一角色会话。
|
|
45
|
+
const raced=agents.get(sessionId);
|
|
46
|
+
if(error.name==='SessionAlreadyOwnedError'&&raced){validate(raced,sessionId,workspace);remember(raced,undefined,options);await raced.whenIdle();return raced;}
|
|
47
|
+
// 仅识别旧版回滚遗漏来源标识这一已知缺陷;其余损坏仍原样报错。
|
|
48
|
+
if(error.name==='SessionPersistenceCorruptionError' && error.message.includes('format v4 message requires a producer-owned source kind'))
|
|
49
|
+
throw Object.assign(new Error('旧角色会话含缺少来源标识的回滚事件,无法恢复',{cause:error}),{code:'ROLEPLAY_LEGACY_ROLLBACK'});
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
try{validate(handle.agent,sessionId,workspace);}catch(error){await handle.dispose();throw error;}
|
|
53
|
+
remember(handle.agent,handle,options);
|
|
54
|
+
// 后台用途直接命名,避免额外调用模型给材料 JSON 起标题。
|
|
55
|
+
if(!saved)titles?.rename(handle.agent.session,'角色平行会话');
|
|
56
|
+
await handle.agent.whenIdle();
|
|
57
|
+
return handle.agent;
|
|
58
|
+
}
|
|
59
|
+
function resultSince(agent, requestId, fromSeq) {
|
|
60
|
+
const events = agent.session.snapshotEvents().filter(event => event.seq >= fromSeq);
|
|
61
|
+
const input = events.find(event => event.type==='user/message' && event.data.id===requestId);
|
|
62
|
+
if (!input) return {stopReason:'error',failure:{code:'INPUT_NOT_ACCEPTED'},output:[]};
|
|
63
|
+
const end = events.find(event => event.type==='turn/end' && event.seq>input.seq);
|
|
64
|
+
if (!end) return {stopReason:'error',failure:{code:'INCOMPLETE_TURN'},output:[]};
|
|
65
|
+
const reason = end.data.reason;
|
|
66
|
+
const assistant=events.filter(event => event.type==='assistant/message' && event.data.turn===end.data.turn && event.seq>input.seq).at(-1);
|
|
67
|
+
const output = assistant?.data.message.content ?? [];
|
|
68
|
+
return {stopReason:reason.kind==='completed'?'completed':reason.kind,
|
|
69
|
+
failure:reason.error,output,turn:end.data.turn,usage:assistant?.data.usage};
|
|
70
|
+
}
|
|
71
|
+
async function flush(agent) { await sessions.flush(agent.session); }
|
|
72
|
+
return {
|
|
73
|
+
newId: roleId => `pygmalion-roleplay:${roleId}:${randomUUID()}`,
|
|
74
|
+
async run({sessionId,workspace,options,requestId,payload,signal,onCheckpoint}) {
|
|
75
|
+
const agent = await open({sessionId,workspace,options});
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
const checkpoint={seq:agent.session.seq,nodes:[...agent.session.surface.nodes]};
|
|
78
|
+
await onCheckpoint?.(checkpoint);
|
|
79
|
+
const abort=()=>agent.cancel({kind:'user',reason:'角色生成请求终止'});
|
|
80
|
+
signal.addEventListener('abort',abort,{once:true});
|
|
81
|
+
try {
|
|
82
|
+
signal.throwIfAborted();
|
|
83
|
+
agent.followup({id:requestId,role:'user',source:{kind:'pygmalion-roleplay',requestId},content:[{type:'text',text:payload}]});
|
|
84
|
+
await agent.whenIdle();
|
|
85
|
+
await flush(agent);
|
|
86
|
+
return {...resultSince(agent,requestId,checkpoint.seq),checkpoint};
|
|
87
|
+
} finally { signal.removeEventListener('abort',abort); }
|
|
88
|
+
},
|
|
89
|
+
async recover({sessionId,workspace,options,requestId,checkpoint}) {
|
|
90
|
+
const agent=await open({sessionId,workspace,options});
|
|
91
|
+
return resultSince(agent,requestId,checkpoint.seq);
|
|
92
|
+
},
|
|
93
|
+
async rollback({sessionId,checkpoint}) {
|
|
94
|
+
const agent=handles.get(sessionId)?.agent;
|
|
95
|
+
if (!agent) throw new Error('恢复角色上下文缺少会话句柄');
|
|
96
|
+
await agent.whenIdle();
|
|
97
|
+
await agent.runMaintenance(async()=>{
|
|
98
|
+
const nodes=[...agent.session.surface.nodes];
|
|
99
|
+
const kept=new Set(checkpoint.nodes);
|
|
100
|
+
// 旧的非空前缀必须仍然存在;不能吞掉其他请求已提交的消息。
|
|
101
|
+
for(const seq of checkpoint.nodes) {
|
|
102
|
+
if(!nodes.includes(seq) && agent.session.deriveEventMessage(agent.session.eventAt(seq))) throw new Error('角色上下文前缀已变化,不能安全恢复');
|
|
103
|
+
}
|
|
104
|
+
// 固定系统头在首轮首次组装时产生;宿主禁止把它与其他消息一起替换。
|
|
105
|
+
// 它不含本轮材料,保留同一静态头以复用前缀即可。
|
|
106
|
+
if(nodes.length&&agent.session.eventAt(nodes[0])?.type==='system/message')kept.add(nodes[0]);
|
|
107
|
+
const tail=nodes.filter(seq=>!kept.has(seq));
|
|
108
|
+
if(!tail.length)return;
|
|
109
|
+
const first=nodes.indexOf(tail[0]);
|
|
110
|
+
if(nodes.slice(first).some(seq=>kept.has(seq)))throw new Error('角色上下文不是尾部增量');
|
|
111
|
+
// user/message 支持轮次外的上下文替换(宿主 checkpoint 也用此事件)。
|
|
112
|
+
// system/developer 消息必须处于尚未关闭的 turn/step,维护阶段不能伪造该位置。
|
|
113
|
+
agent.session.append('user/message',{
|
|
114
|
+
id:randomUUID(),role:'user',source:{kind:'pygmalion-roleplay-rollback'},content:[]},
|
|
115
|
+
{surfaceOp:{op:'replace',startSeq:tail[0],endSeq:tail.at(-1)},sourceEventSeqs:tail});
|
|
116
|
+
await flush(agent);
|
|
117
|
+
});
|
|
118
|
+
},
|
|
119
|
+
async size(sessionId,workspace) {
|
|
120
|
+
const agent=agents.get(sessionId);
|
|
121
|
+
if(agent&&workspace)validate(agent,sessionId,workspace);
|
|
122
|
+
if(agent)return agent.session.deriveMessages().reduce((sum,message)=>sum+64+message.content.reduce((n,b)=>n+(b.type==='text'?b.text.length:0),0),0);
|
|
123
|
+
return 0;
|
|
124
|
+
},
|
|
125
|
+
async release(sessionId) { const handle=handles.get(sessionId);if(handle){handles.delete(sessionId);await handle.dispose();} },
|
|
126
|
+
async dispose() { for(const id of [...handles.keys()])await this.release(id); },
|
|
127
|
+
};
|
|
128
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** 内容编写子 agent 没有外部工具;重试由生成工具统一负责。 */
|
|
2
|
+
export const name = 'pygmalion-roleplay-worker';
|
|
3
|
+
export const inject = ['tools'];
|
|
4
|
+
export function apply(ctx) {
|
|
5
|
+
// 模型请求的 assembly 早于 pre-step;必须在 preset 建立时限制,不能等首步再隐藏。
|
|
6
|
+
ctx.tools.restrict({allow:[]});
|
|
7
|
+
ctx.tools.guard(()=>'角色内容编写子 agent 不执行任何工具');
|
|
8
|
+
// 请求级重试归调用服务;不进入宿主的全局恢复链。
|
|
9
|
+
ctx.on('agent/request-error',async()=>undefined);
|
|
10
|
+
}
|