pygmalion 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -66,3 +66,9 @@ node scripts/start-local-test.mjs --install
66
66
  本次结构整理按影响选择检查:通信改动优先 self-test-channel、管理 API 用 phase5、脚本/hook 用 phase4、心跳状态用 heartbeat-retry。不要把全部历史脚本都作为每次提交的重复门槛;没有新变更或失败时不重复运行已通过检查。
67
67
 
68
68
  打包核对使用临时目录中的实际 tgz。宿主辅助器支持 packageRoot 参数,直接从解包目录启动维护模式宿主;不能把源码软链接当作发布包的验收。
69
+
70
+ ## 生活脚本内部唤醒
71
+
72
+ Node 生活脚本通过 IPC 将 `wake()` 事件交给父进程绑定的角色运行时,收到送达或免打扰延迟回执;通信失败抛错。已移除 HTTP 入口原有的 10 分钟生活脚本节流。Python 自行调用的 HTTP 兼容入口保留。
73
+
74
+ `node scripts/self-test-life-dsh.mjs` 验证真实宿主的 skill → life_run → 子进程 → IPC → 角色会话 → 模型请求 → director_send → 本地通信出口,并检查连续三个事件的回执与持久化日志。两版宿主均已通过;模型和通信使用本地测试接口,不代表真实模型、QQ 或整进程重启端到端验收。
@@ -2,6 +2,12 @@
2
2
 
3
3
  本文面向通过 npm 安装 Pygmalion 的用户,说明如何更新插件、保留自己的数据,以及恢复到升级前的版本。Pygmalion 0.2.0 支持 dsh 0.2.1-rc.2;0.2.1 同时支持 dsh 0.2.1-rc.2 与 0.2.2-rc.1,无需迁移角色或记忆数据。
4
4
 
5
+ ## 0.2.3 修复
6
+
7
+ Node 生活脚本的 `wake()` 改为 IPC → 父进程 → 角色运行时,不依赖 HTTP 端口或 token;返回处理结果,失败不再静默。移除生活脚本唤醒的 10 分钟节流。Python 自行调用的 HTTP 兼容入口仍保留。
8
+
9
+ 升级后重启引擎,并重新启动原有生活脚本,使其加载新版 IPC 助手。双版本本机真实宿主链路已验证(本地模型和通信测试接口);整进程重启后的端到端验收尚未完成。
10
+
5
11
  ## 0.2.2 修复
6
12
 
7
13
  修复 dsh 0.2.2-rc.1 中调用 `skill` 成功后,`meme_read` 等按需工具晚一个模型步才可见的问题。工具注册现在在宿主等待的结果处理阶段完成;保持 dsh 0.2.1-rc.2 兼容。升级后重启引擎生效,无需迁移数据。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pygmalion",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Pygmalion:将 DeepSeek Harness(dsh)改造为「拟真 AI 好友」服务的 dsh 插件——QQ 官方机器人接入、文件系统双索引长期记忆、heartbeat+脚本+hook 主动交互,一次安装即用(含管理网页)",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/agent-life.js CHANGED
@@ -11,8 +11,7 @@
11
11
  * 运行状态、进程退出时把输出写进 life/.logs/ 与 .manifest.json(管理页可见),不限制运行
12
12
  * 时长/次数/超时。脚本以「有事件就唤醒」为设计原则:脚本里设计的每个生活事件(心情变化、
13
13
  * 到点作息、突发小事件、想 ta 的时刻)发生时都直接调用 wake() —— node 脚本启动时已预加载
14
- * 全局 wake(),内部经 HTTP 调用插件的 /wakeup 端点(Bearer PYG_TOKEN 鉴权),插件侧节流+
15
- * 撞车检测后唤醒 dsh;是否开口由 dsh 判断(可沉默)。脚本无需自己写网络代码。
14
+ * 全局 wake(),内部经 IPC 调用父进程绑定的角色运行时唤醒 dsh;是否开口由 dsh 判断(可沉默)。脚本无需自己写网络代码。
16
15
  *
17
16
  * 注入脚本的环境变量:
18
17
  * PYG_QQ 账号 QQ 号
@@ -35,14 +34,13 @@ const SCRIPT_EXTS = ['.mjs', '.js', '.py', '.ts'];
35
34
  const STDOUT_CAP = 2 * 1024 * 1024;
36
35
 
37
36
  /** 预加载进每个 node 生活脚本的唤醒助手 + 内存级状态(插件自动写入,启动时 --import 预加载)。
38
- * - wake({mood,topic,reason,force}):唤起 dsh(内部经 PYG_BASE+PYG_HTTP_API_PATH 调 /wakeup,Bearer PYG_TOKEN)。
37
+ * - wake({mood,topic,reason,force}):唤起 dsh(经 IPC 调用父进程绑定的角色运行时)。
39
38
  * - pyg.state:脚本所有需要跨重启保留的可变状态写在这里(如 pyg.state.a = 1),插件自动 checkpoint
40
39
  * 到 life/.state-<脚本名>.json(写变/唤醒时/退出时),重启后重新拉起自动恢复 —— 重启前 pyg.state.a 是 1,
41
40
  * 重启后还是 1。不要用脚本顶层变量存重要状态(进程随 dsh 重启/被杀时顶层变量会丢)。 */
42
41
  const WAKE_HELPER_SOURCE = `// Pygmalion 生活脚本唤醒助手 + 内存级状态(插件自动写入,启动时 --import 预加载)。
43
- // ① 唤醒:脚本内直接调用 wake({ mood, topic, reason, force }) 唤起 dsh —— 内部经
44
- // PYG_BASE + PYG_HTTP_API_PATH 调用插件的 /wakeup 端点(Bearer PYG_TOKEN 鉴权),
45
- // 插件侧节流+撞车检测后唤醒导演会话。脚本无需自己写任何网络代码。
42
+ // ① 唤醒:脚本内调用 wake({ event, mood, topic, reason }),通过 IPC 通知角色运行时。
43
+ // 返回送达或免打扰延迟回执;通信失败会抛错。脚本无需配置端口或凭据。
46
44
  // ② 内存级状态:脚本所有需要跨重启保留的可变状态必须写在 pyg.state 上(如 pyg.state.a = 1)。
47
45
  // 插件自动 checkpoint 到 life/.state-<脚本名>.json(写变/唤醒时/退出时),dsh 或脚本重启后
48
46
  // 重新拉起时自动恢复 —— 重启前 pyg.state.a 是 1,重启后还是 1。不要用脚本顶层变量存重要状态。
@@ -69,30 +67,33 @@ function __pygScheduleFlush() {
69
67
  __pygFlushTimer = setTimeout(() => { __pygFlushTimer = null; __pygFlushState(__pygState); }, 800);
70
68
  }
71
69
 
70
+ const pending = new Map();
71
+ let sequence = 0;
72
+ process.on('message', message => {
73
+ const request = pending.get(message?.id);
74
+ if (!request) return;
75
+ pending.delete(message.id);
76
+ if (!pending.size) process.channel?.unref();
77
+ if (message.ok) request.resolve(message.result);
78
+ else request.reject(new Error(message.error || '生活脚本唤醒失败'));
79
+ });
80
+ process.channel?.unref();
81
+ process.on('disconnect', () => {
82
+ __pygFlushState(__pygState);
83
+ // IPC 无法跨父进程重建;退出后由既有恢复机制按 checkpoint 重新拉起。
84
+ process.exit(0);
85
+ });
72
86
  globalThis.wake = async (opts = {}) => {
73
- const o = opts ?? {};
74
- const base = process.env.PYG_BASE;
75
- const p = process.env.PYG_HTTP_API_PATH;
76
- const token = process.env.PYG_TOKEN;
77
- const openid = process.env.PYG_OPENID;
78
- const roleHook = process.env.PYG_ROLE_HOOK === '1';
79
- // 唤醒前先 checkpoint 状态(事件边界保证恢复一致性)。
80
87
  __pygFlushState(__pygState);
81
- if (!base || !p || !token || (!openid && !roleHook)) return; // 未配置唤醒端点,静默降级
82
- try {
83
- await fetch(base + p + '/wakeup', {
84
- method: 'POST',
85
- headers: { 'content-type': 'application/json', authorization: 'Bearer ' + token },
86
- body: JSON.stringify({
87
- ...(roleHook ? {} : { channel: 'c2c:' + openid }),
88
- reason: o.reason || '',
89
- mood: o.mood || '',
90
- topic: o.topic || '',
91
- kind: 'script-hook',
92
- force: Boolean(o.force),
93
- }),
88
+ if (!process.connected) throw new Error('生活脚本唤醒通道未连接');
89
+ const id = ++sequence;
90
+ return new Promise((resolve, reject) => {
91
+ pending.set(id, { resolve, reject }); process.channel?.ref();
92
+ process.send({ type: 'life-wake', id, input: opts }, error => {
93
+ if (!error) return;
94
+ pending.delete(id); if (!pending.size) process.channel?.unref(); reject(error);
94
95
  });
95
- } catch { /* 唤醒失败不抛进脚本主流程 */ }
96
+ });
96
97
  };
97
98
  globalThis.__pygWake = globalThis.wake;
98
99
  globalThis.pyg = {
@@ -141,23 +142,15 @@ async function beginLifeLog({ workspace, script, startedAt }) {
141
142
  }
142
143
 
143
144
  /** 生活脚本的每次生命周期结束都回报导演。脚本自行调用 wake() 是“发生了什么”,
144
- * 这里则是运行时的事实通知;二者不能互相替代。没有 HTTP 鉴权时静默降级,但绝不影响
145
+ * 这里则是运行时的事实通知;二者不能互相替代。通知失败记录警告,但绝不影响
145
146
  * 脚本退出与日志落盘。 */
146
147
  async function notifyLifeScriptEnded(opts, script, { exitCode, error } = {}) {
147
- if (!opts?.baseUrl || !opts?.httpApiPath || !opts?.token || (!opts?.openid && !opts?.roleScopedHook)) return;
148
148
  const result = exitCode === 0 ? '正常结束' : error || `以退出码 ${exitCode ?? '未知'} 结束`;
149
149
  try {
150
- await fetch(`${opts.baseUrl}${opts.httpApiPath}/wakeup`, {
151
- method: 'POST',
152
- headers: { 'content-type': 'application/json', authorization: `Bearer ${opts.token}` },
153
- body: JSON.stringify({
154
- ...(opts.roleScopedHook ? {} : { channel: `c2c:${opts.openid}` }),
155
- reason: `生活脚本「${basename(script)}」${result}。`,
156
- contextText: `[脚本结束] 生活脚本「${basename(script)}」${result}\n日志目录:life/.logs/`,
157
- force: true,
158
- }),
159
- });
160
- } catch { /* 通知失败不改变脚本已经结束这一事实 */ }
150
+ await deliverLifeWake(opts, { reason: `生活脚本「${basename(script)}」${result}。` });
151
+ } catch (failure) {
152
+ console.warn('生活脚本结束通知未送达:%s', failure.message);
153
+ }
161
154
  }
162
155
 
163
156
  async function readJson(file, fallback) {
@@ -203,6 +196,17 @@ let runSeq = 0;
203
196
  * @param {object} opts { workspace, qq, dataRoot, stateFile, lastUserAt, token, baseUrl, timeoutMs? }
204
197
  * @returns {Promise<{ok, runId?, pid?, startedAt?, script?, error?}>}
205
198
  */
199
+ const wakeHandlers = new Map();
200
+ /** 绑定由父进程确定的角色;脚本不能自行指定目标。 */
201
+ export function registerLifeWake(roleId, handler) {
202
+ wakeHandlers.set(roleId, handler);
203
+ return () => { if (wakeHandlers.get(roleId) === handler) wakeHandlers.delete(roleId); };
204
+ }
205
+ async function deliverLifeWake(opts, input) {
206
+ const handler = wakeHandlers.get(opts.qq);
207
+ if (!handler) throw new Error('生活脚本所属角色的唤醒服务尚未就绪');
208
+ return handler(input);
209
+ }
206
210
  export async function startLifeScript(script, opts) {
207
211
  const ext = extname(script).toLowerCase();
208
212
  let command = process.execPath; // node 用于 .js/.mjs/.ts
@@ -253,6 +257,7 @@ export async function startLifeScript(script, opts) {
253
257
  if (logFile) fd = openSync(logFile, 'a');
254
258
  } catch { logFile = null; }
255
259
  const stdio = fd != null ? ['ignore', fd, fd] : ['ignore', 'pipe', 'pipe'];
260
+ if (ext !== '.py') stdio.push('ipc');
256
261
 
257
262
  let child;
258
263
  try { child = spawn(command, args, { env, stdio, detached: true, windowsHide: true }); }
@@ -260,7 +265,17 @@ export async function startLifeScript(script, opts) {
260
265
  if (fd != null) { try { closeSync(fd); } catch { /* ignore */ } }
261
266
  return { ok: false, error: `spawn ${command}: ${String(e)}` };
262
267
  }
263
- child.unref(); // 不因子进程保活父进程;父进程退出后脚本照常运行(跨重启恢复基础)
268
+ child.on('message', async message => {
269
+ if (message?.type !== 'life-wake' || !Number.isSafeInteger(message.id)) return;
270
+ try {
271
+ const result = await deliverLifeWake(opts, message.input ?? {});
272
+ if (child.connected) child.send({ id: message.id, ok: true, result }, () => {});
273
+ } catch (error) {
274
+ if (child.connected) child.send({ id: message.id, ok: false, error: error.message }, () => {});
275
+ }
276
+ });
277
+ child.channel?.unref();
278
+ child.unref(); // 不因子进程保活父进程;Node 脚本在 IPC 断开后 checkpoint 并退出,等待恢复
264
279
 
265
280
  running.set(runId, {
266
281
  runId, scriptPath: script, scriptName, pid: child.pid, startedAt, workspace: opts.workspace, logFile: logFile ?? undefined, child,
package/src/http-api.js CHANGED
@@ -294,19 +294,8 @@ async function handleWakeup(deps, res, body) {
294
294
  sendJson(res, 400, { ok: false, error: 'topic(可选)必须是字符串:脚本事件的主题' });
295
295
  return;
296
296
  }
297
- // 脚本唤醒节流:同角色 scriptWakeMinIntervalMs 内至多一次(防脚本循环轰炸)。
298
- if (kind === 'script-hook' && deps.persona && deps.roleId && force !== true) {
299
- try {
300
- const min = deps.scriptWakeMinIntervalMs ?? 10 * 60 * 1000;
301
- const role = await deps.persona.loadRole(deps.roleId);
302
- if (role && Date.now() - (role.state?.lastScriptWakeAt ?? 0) < min) {
303
- sendJson(res, 200, { ok: false, skipped: 'throttled', scriptWake: true });
304
- return;
305
- }
306
- } catch { /* 节流读取失败不阻塞 */ }
307
- }
308
297
  // 免打扰时段:不丢弃脚本唤醒,写入 role.state.deferredWakeup(合并只留最新),
309
- // 由 heartbeat 在安静时段结束后真正唤醒 dsh;也记 lastScriptWakeAt 防脚本连发。
298
+ // 由 heartbeat 在安静时段结束后真正唤醒 dsh;lastScriptWakeAt 仅保留历史记录用途,不再用于限流。
310
299
  if (deps.persona && deps.roleId) {
311
300
  try {
312
301
  const role = await deps.persona.loadRole(deps.roleId);
@@ -1,3 +1,5 @@
1
+ import { inQuietHours } from './quiet-hours.js';
2
+ import { registerLifeWake } from './agent-life.js';
1
3
  /** 单角色运行时:统一会话依赖、恢复、交付取消与内部唤醒;不处理通信协议。 */
2
4
  import { RoleAgentResolver } from './role-agent.js';
3
5
  import { createSetupAgent, buildSessionDeps } from './setup-agent.js';
@@ -49,13 +51,27 @@ export function createRoleRuntime(deps, connection, transport) {
49
51
  },
50
52
  withinChatWindowMs: connection.withinChatWindowMs }, { ...params, target });
51
53
  }
54
+ let releaseLifeWake;
52
55
  return { setupDeps, setupAgent, registerSessionContext, roleAgents, beginDelivery, boundTarget, wake,
53
56
  signal: lifetime.signal,
54
57
  start() {
58
+ releaseLifeWake = registerLifeWake(roleId, async input => {
59
+ lifetime.signal.throwIfAborted();
60
+ const params = { kind: 'script-hook', event: input.event, mood: input.mood,
61
+ topic: input.topic, reason: input.reason, force: true };
62
+ const role = await persona.loadRole(roleId);
63
+ if (inQuietHours(role?.proactive?.quietHours || [])) {
64
+ await persona.updateRoleState(roleId, state => ({ ...state,
65
+ deferredWakeup: { ...params, atMs: Date.now() } }));
66
+ return { ok: true, deferred: true, woken: false, reason: 'quiet-hours' };
67
+ }
68
+ return wake(params);
69
+ });
55
70
  deps.devices?.registerRole?.(roleId, (contextText, { priority = false } = {}) => wake({ reason: '设备事件', contextText,
56
71
  force: priority, interruptTool: priority ? 'director_send' : undefined }));
57
72
  },
58
73
  dispose() {
74
+ releaseLifeWake?.();
59
75
  lifetime.abort(new Error('角色连接已停止,本次交互已取消'));
60
76
  for (const id of sessionIds) director?.unregisterSession?.(id);
61
77
  director?.unregisterSessionBuilder?.(connection.id);
package/src/tools.js CHANGED
@@ -414,7 +414,7 @@ export function buildDirectorToolDefs(resolveCtx) {
414
414
  + '脚本以“有事件就唤醒”为设计原则:脚本里设计的每个生活事件(心情变化、到点作息、'
415
415
  + '突发小事件、想用户的时刻)在发生时都调用 wake({ mood, topic, reason, force }) —— node '
416
416
  + '脚本启动时已自动预加载全局 wake(),直接调用即可(无需 import / fetch / 网络):内部经'
417
- + 'HTTP 调插件 /wakeup 端点,插件节流(默认同角色 10 分钟内至多一次)+ 撞车检测后'
417
+ + 'IPC 将事件交给父进程的角色运行时后'
418
418
  + '唤醒 dsh 注入 [脚本事件] 情境;是否开口、如何开口由你(导演)被唤醒后自行判断'
419
419
  + '(可以选择沉默)。wake() 的意义是让事件成为导演已经知晓的角色经历;事件被知晓后目的已经达成,'
420
420
  + '是否把它转化成 QQ 消息是另一项独立判断。'