pygmalion 0.1.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.
@@ -0,0 +1,96 @@
1
+ import { targetOfSession } from './inbound.js';
2
+ import { registerQQTools, registerDirectorTools } from './tools.js';
3
+ import { attachSessionToCwdWorkspace } from './dsh-bookkeeping.js';
4
+
5
+ /**
6
+ * 构造 standing 层 pygmalion 工具执行所需的会话依赖(deps 需含
7
+ * api/routes/persona/roleId/httpApiToken/log)。target 为惰性闭包:调用时经
8
+ * routes.get(sessionId) 现取目标,因此同一 deps 可被 setup 与「已存在 agent 补
9
+ * 登记」两处复用。
10
+ */
11
+ export function buildSessionDeps(deps, sessionId) {
12
+ const { api, routes, persona, roleId, httpApiToken, httpApiPath, log } = deps;
13
+ return {
14
+ api, routes,
15
+ target: () => routes.get(sessionId)?.target ?? targetOfSession(sessionId),
16
+ roleId, httpApiToken, httpApiPath, persona, log,
17
+ workspaceOf: roleId !== undefined && persona !== undefined
18
+ ? async () => persona.roleWorkspace(roleId)
19
+ : undefined,
20
+ };
21
+ }
22
+
23
+ export function createSetupAgent(deps) {
24
+ const { log, api, routes, outbound, workspaceRegistry, defaultCwd, resolvePreset, agentPresets, persona, roleId, httpApiToken, director } = deps;
25
+ const directorSvc = director?.get?.('pygmalion.director');
26
+ return async (agentCtx, sessionId) => {
27
+ // 1. Join the agent's preset FIRST so its tools, prompt sections, and
28
+ // skill catalog are in scope before any QQ-only tool registers.
29
+ // `mount()` returns the preset that was actually mounted; on rejection
30
+ // we surface a clear error to `agents.create` so the agent never
31
+ // publishes half-configured.
32
+ let mountedPresetId;
33
+ if (agentPresets !== undefined && resolvePreset !== undefined) {
34
+ let presetId;
35
+ try {
36
+ presetId = (await resolvePreset(sessionId)).id;
37
+ }
38
+ catch (error) {
39
+ log.error('QQ setupAgent: resolving agent preset failed for %s: %o', sessionId, error);
40
+ throw error instanceof Error ? error : new Error(String(error));
41
+ }
42
+ try {
43
+ const mounted = await agentPresets.mount(agentCtx, presetId);
44
+ mountedPresetId = mounted.id;
45
+ log.info('QQ setupAgent: %s joined preset "%s"', sessionId, mounted.id);
46
+ }
47
+ catch (error) {
48
+ log.error('QQ setupAgent: mounting preset "%s" failed for %s: %o', presetId ?? '(default)', sessionId, error);
49
+ throw error instanceof Error ? error : new Error(String(error));
50
+ }
51
+ }
52
+ else {
53
+ log.warn('QQ setupAgent: agentPresets service is absent; %s will run on the empty global layer '
54
+ + '(only QQ-specific tools will be visible). Load an agent-presets plugin in the host composition.', sessionId);
55
+ }
56
+ // 2. 登记会话依赖到 pygmalion.director 宿主服务:preset 桥插件把 pygmalion 工具注册在
57
+ // standing 层(每进程一份),工具执行时按 exec.agent.id 从本表动态解析每会话依赖。
58
+ if (directorSvc !== undefined && typeof directorSvc.registerSession === 'function') {
59
+ directorSvc.registerSession(sessionId, buildSessionDeps(deps, sessionId));
60
+ }
61
+ // 3. 工具注册:导演 preset 已把 pygmalion 工具注册进 standing 层(与 fs/bash 同层,
62
+ // resume 恢复会话后 dispatch 依然可达)→ 跳过 own 层注册;
63
+ // 否则(非导演 preset / 无 agentPresets / 旧版 preset 缺桥插件行)回退 own 层注册,保持旧行为。
64
+ const target = () => routes.get(sessionId)?.target ?? targetOfSession(sessionId);
65
+ const standingReady = mountedPresetId === 'pygmalion-director'
66
+ && directorSvc !== undefined && typeof directorSvc.hasStandingTools === 'function'
67
+ && directorSvc.hasStandingTools();
68
+ if (standingReady) {
69
+ log.debug?.('QQ setupAgent: %s 使用 standing 层 pygmalion 工具(preset=%s),跳过 own 层注册', sessionId, mountedPresetId);
70
+ }
71
+ else {
72
+ registerQQTools(agentCtx, sessionId, api, target);
73
+ const okDir = registerDirectorTools(agentCtx, sessionId, {
74
+ api, routes, target,
75
+ roleId,
76
+ httpApiToken,
77
+ httpApiPath,
78
+ persona,
79
+ log,
80
+ workspaceOf: roleId !== undefined && persona !== undefined
81
+ ? async () => persona.roleWorkspace(roleId)
82
+ : undefined,
83
+ });
84
+ if (okDir === true) {
85
+ log.debug?.('QQ setupAgent: director tools (director_send/recollect/life_run) registered for %s (own layer)', sessionId);
86
+ }
87
+ else {
88
+ log.warn?.(`QQ setupAgent: director tools could NOT be registered for %s (agentCtx.tools unavailable)`, sessionId);
89
+ }
90
+ }
91
+ outbound.registerApprovalAnswerer(agentCtx, sessionId);
92
+ routes.ensure(sessionId, target());
93
+ void attachSessionToCwdWorkspace(workspaceRegistry, defaultCwd, sessionId, log);
94
+ };
95
+ }
96
+ //# sourceMappingURL=setup-agent.js.map
@@ -0,0 +1,142 @@
1
+ import { targetKey } from './threads.js';
2
+ import { baseSessionId } from './inbound.js';
3
+ export function createSlashHandler(deps) {
4
+ const { log, alwaysAllow, threads, agents, approval, outbound, agentPresets, botId } = deps;
5
+ /** List presets through the host service; `undefined` when unavailable/failed. */
6
+ const listPresets = async () => {
7
+ if (agentPresets === undefined)
8
+ return undefined;
9
+ try {
10
+ return await agentPresets.list();
11
+ }
12
+ catch (error) {
13
+ log.warn('QQ slash: listing agent presets failed: %o', error);
14
+ return undefined;
15
+ }
16
+ };
17
+ return async (sessionId, message, text, reply) => {
18
+ if (!text.startsWith('/'))
19
+ return false;
20
+ const [command, ...rest] = text.slice(1).split(/\s+/);
21
+ switch (command) {
22
+ case 'help':
23
+ await reply([
24
+ '/help — 显示可用命令',
25
+ '/ping — 延迟检测',
26
+ '/me — 显示你的 openid',
27
+ '/new [preset] — 开启新会话(可选 preset id,见 /presets)',
28
+ '/presets — 列出可用的 agent preset',
29
+ '/approve ask|never|status — 审批策略',
30
+ '/always clear — 清除"始终允许"清单',
31
+ ].join('\n'));
32
+ return true;
33
+ case 'ping':
34
+ await reply(`✅ pong(${new Date().toLocaleTimeString()})`);
35
+ return true;
36
+ case 'me':
37
+ await reply(`🆔 你的 openid: \`${message.senderId}\`${message.senderName !== undefined ? `(${message.senderName})` : ''}`);
38
+ return true;
39
+ case 'presets': {
40
+ const presets = await listPresets();
41
+ if (presets === undefined) {
42
+ await reply(agentPresets === undefined
43
+ ? '⚠️ 当前环境不支持 preset 查询(host 未加载 agent-presets 服务)'
44
+ : '⚠️ 读取 preset 列表失败,请稍后再试');
45
+ return true;
46
+ }
47
+ await reply(presets.length === 0
48
+ ? '当前没有可用的 agent preset(检查 host 的 agent-presets 配置)'
49
+ : [
50
+ '可用 agent preset:',
51
+ ...presets.map(preset => `- ${preset.id}${preset.name !== undefined ? `(${preset.name})` : ''}${preset.broken !== undefined ? ` ⚠️ 不可用:${preset.broken}` : ''}`),
52
+ '用 /new <id> 以指定 preset 开启新会话',
53
+ ].join('\n'));
54
+ return true;
55
+ }
56
+ case 'new': {
57
+ // Optional argument: the agent preset id the NEW session composes
58
+ // from (validated against the host roster below). Unknown or broken
59
+ // ids are refused BEFORE the thread bumps, so the current thread and
60
+ // its anchor stay untouched.
61
+ const arg = rest[0];
62
+ let presetId;
63
+ if (arg !== undefined) {
64
+ if (agentPresets === undefined) {
65
+ await reply('⚠️ 当前环境不支持按会话指定 preset(host 未加载 agent-presets 服务)');
66
+ return true;
67
+ }
68
+ const presets = await listPresets();
69
+ if (presets === undefined) {
70
+ await reply('⚠️ 读取 preset 列表失败,请稍后再试');
71
+ return true;
72
+ }
73
+ const found = presets.find(preset => preset.id === arg);
74
+ if (found === undefined) {
75
+ const ids = presets.map(preset => preset.id);
76
+ await reply(`⚠️ 未知的 preset “${arg}”。可用:${ids.length > 0 ? ids.join(', ') : '(无)'}。\n用 /presets 查看详情。`);
77
+ return true;
78
+ }
79
+ if (found.broken !== undefined) {
80
+ await reply(`⚠️ preset “${arg}” 当前不可用:${found.broken}`);
81
+ return true;
82
+ }
83
+ presetId = found.id;
84
+ }
85
+ // Cancel any agent still running on the current thread so its queued
86
+ // or mid-stream assistant messages are dropped instead of leaking
87
+ // into the abandoned session id. Force-close the C2C stream first
88
+ // so QQ's "其它流式消息发送中" guard does not block the new thread.
89
+ const key = targetKey(message.reply);
90
+ const before = threads.current(key);
91
+ const oldAgent = agents.get(sessionId);
92
+ await outbound.closeStream(sessionId).catch(() => undefined);
93
+ try {
94
+ oldAgent?.cancel({ kind: 'user' });
95
+ }
96
+ catch (error) {
97
+ log.warn('failed to cancel old QQ agent on /new: %o', error);
98
+ }
99
+ const thread = threads.next(key);
100
+ const baseId = baseSessionId(message.reply, botId);
101
+ const newId = thread === 0 ? baseId : `${baseId}#n${thread}`;
102
+ // Record (or explicitly clear) the per-session override so the agent
103
+ // materializing newId composes from it; a plain /new resets to the
104
+ // plugin-config default.
105
+ threads.setPreset(newId, presetId);
106
+ log.info('QQ /new: target=%s beforeThread=%d afterThread=%d oldAgent=%s newSessionId=%s preset=%s', key, before, thread, oldAgent ? 'present' : 'none', newId, presetId ?? '(config default)');
107
+ await reply(presetId === undefined
108
+ ? `✅ 已开启新会话(#n${thread})。下次发送的消息将进入 \`${newId}\`。旧的对话仍保留,可手动在侧边栏切换。`
109
+ : `✅ 已开启新会话(#n${thread},preset=${presetId})。下次发送的消息将进入 \`${newId}\`。旧的对话仍保留,可手动在侧边栏切换。`);
110
+ return true;
111
+ }
112
+ case 'approve': {
113
+ const sub = rest[0] ?? 'status';
114
+ if (sub === 'ask' || sub === 'never') {
115
+ const agent = agents.get(sessionId);
116
+ if (approval === undefined || agent === undefined) {
117
+ await reply('⚠️ 当前环境不支持审批策略切换');
118
+ return true;
119
+ }
120
+ approval.setPolicy(agent, sub);
121
+ await reply(`✅ 审批策略已切换为 ${sub}`);
122
+ return true;
123
+ }
124
+ const listed = alwaysAllow.list(sessionId);
125
+ await reply(listed.length > 0
126
+ ? `始终允许的工具:${listed.join(', ')}(用 /approve ask|never 切换策略)`
127
+ : '无始终允许的工具(用 /approve ask|never 切换策略)');
128
+ return true;
129
+ }
130
+ case 'always':
131
+ if (rest[0] === 'clear') {
132
+ const removed = alwaysAllow.clear(sessionId);
133
+ await reply(`✅ 已清除 ${removed} 条"始终允许"规则`);
134
+ return true;
135
+ }
136
+ return false;
137
+ default:
138
+ return false;
139
+ }
140
+ };
141
+ }
142
+ //# sourceMappingURL=slash-commands.js.map
package/src/store.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Small durable JSON stores for the adapter: per-session reply routes
3
+ * (target + passive-reply anchor) and the approval always-allow rules.
4
+ * Both write atomically (tmp + rename) and tolerate absent files.
5
+ */
6
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
7
+ import { dirname } from 'node:path';
8
+ async function readJson(file, fallback) {
9
+ try {
10
+ return JSON.parse(await readFile(file, 'utf8'));
11
+ }
12
+ catch {
13
+ return fallback;
14
+ }
15
+ }
16
+ async function writeJsonAtomic(file, value) {
17
+ await mkdir(dirname(file), { recursive: true });
18
+ const tmp = `${file}.tmp`;
19
+ await writeFile(tmp, JSON.stringify(value), 'utf8');
20
+ await rename(tmp, file);
21
+ }
22
+ /** Reply routing with passive-reply accounting. */
23
+ export class RouteStore {
24
+ file;
25
+ routes = {};
26
+ writing = Promise.resolve();
27
+ constructor(file) {
28
+ this.file = file;
29
+ }
30
+ async load() {
31
+ this.routes = await readJson(this.file, {});
32
+ }
33
+ /** Record an inbound message as the newest passive-reply anchor. */
34
+ anchor(sessionId, target, msgId) {
35
+ this.routes[sessionId] = { target, lastMsgId: msgId, lastMsgAt: Date.now(), used: 0 };
36
+ this.flush();
37
+ }
38
+ /** Ensure a route exists for proactive sends (schedule reminders). */
39
+ ensure(sessionId, target) {
40
+ if (this.routes[sessionId] === undefined) {
41
+ this.routes[sessionId] = { target };
42
+ this.flush();
43
+ }
44
+ }
45
+ get(sessionId) {
46
+ return this.routes[sessionId];
47
+ }
48
+ /** Snapshot every known route (session id → record), for the HTTP channels listing. */
49
+ entries() {
50
+ return Object.entries(this.routes).map(([sessionId, record]) => ({ sessionId, record }));
51
+ }
52
+ /**
53
+ * Consume a passive-reply anchor: returns the inbound msg id while the
54
+ * window is open and under the reply budget, otherwise undefined (send as
55
+ * an active message). Each consumption bumps the counter.
56
+ */
57
+ consumePassive(sessionId, ttlMs, limit) {
58
+ const record = this.routes[sessionId];
59
+ if (record === undefined
60
+ || record.lastMsgId === undefined
61
+ || record.lastMsgAt === undefined
62
+ || (record.used ?? 0) >= limit
63
+ || Date.now() - record.lastMsgAt > ttlMs)
64
+ return undefined;
65
+ record.used = (record.used ?? 0) + 1;
66
+ this.flush(); // 持久化 used(修 D14:重启后被动回复预算不归零)
67
+ return record.lastMsgId;
68
+ }
69
+ /**
70
+ * 修剪过期会话(修 D12):删除「很久没有用户活动」的会话路由(旧线程会累积)。
71
+ * 纯主动目标(无 lastMsgAt)保留——它们廉价且可能仍被计划引用。
72
+ */
73
+ prune(ttlMs) {
74
+ const now = Date.now();
75
+ let removed = 0;
76
+ for (const [k, r] of Object.entries(this.routes)) {
77
+ if (r.lastMsgAt !== undefined && now - r.lastMsgAt > ttlMs) {
78
+ delete this.routes[k];
79
+ removed++;
80
+ }
81
+ }
82
+ if (removed > 0)
83
+ this.flush();
84
+ return removed;
85
+ }
86
+ /** Drop the passive anchor so later sends go active (e.g. after flushing). */
87
+ clearPassive(sessionId) {
88
+ const record = this.routes[sessionId];
89
+ if (record?.lastMsgId !== undefined) {
90
+ record.lastMsgId = undefined;
91
+ record.lastMsgAt = undefined;
92
+ record.used = 0;
93
+ this.flush();
94
+ }
95
+ }
96
+ flush() {
97
+ this.writing = this.writing.then(() => writeJsonAtomic(this.file, this.routes), () => writeJsonAtomic(this.file, this.routes));
98
+ }
99
+ }
100
+ /** Approval "always allow" rules, persisted per QQ session. */
101
+ export class AlwaysAllowStore {
102
+ file;
103
+ rules = {};
104
+ writing = Promise.resolve();
105
+ constructor(file) {
106
+ this.file = file;
107
+ }
108
+ async load() {
109
+ this.rules = await readJson(this.file, {});
110
+ }
111
+ allows(sessionId, toolName) {
112
+ return this.rules[sessionId]?.includes(toolName) === true;
113
+ }
114
+ add(sessionId, toolName) {
115
+ const list = this.rules[sessionId] ?? [];
116
+ if (!list.includes(toolName)) {
117
+ this.rules[sessionId] = [...list, toolName];
118
+ this.flush();
119
+ }
120
+ }
121
+ clear(sessionId) {
122
+ let removed = 0;
123
+ if (sessionId === undefined) {
124
+ removed = Object.keys(this.rules).length;
125
+ this.rules = {};
126
+ }
127
+ else {
128
+ removed = (this.rules[sessionId]?.length ?? 0);
129
+ delete this.rules[sessionId];
130
+ }
131
+ this.flush();
132
+ return removed;
133
+ }
134
+ list(sessionId) {
135
+ return this.rules[sessionId] ?? [];
136
+ }
137
+ /** 修剪(修 D12):丢弃已不存在的会话 id 的 always-allow 规则。 */
138
+ prune(activeSessionIds) {
139
+ const set = new Set(activeSessionIds);
140
+ let removed = 0;
141
+ for (const k of Object.keys(this.rules)) {
142
+ if (!set.has(k)) {
143
+ delete this.rules[k];
144
+ removed++;
145
+ }
146
+ }
147
+ if (removed > 0)
148
+ this.flush();
149
+ return removed;
150
+ }
151
+ flush() {
152
+ this.writing = this.writing.then(() => writeJsonAtomic(this.file, this.rules), () => writeJsonAtomic(this.file, this.rules));
153
+ }
154
+ }
155
+ //# sourceMappingURL=store.js.map
package/src/threads.js ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Per-target conversation-thread counter, plus the per-session preset
3
+ * overrides recorded by `/new <preset>`.
4
+ *
5
+ * Each QQ target (c2c user / group / channel) starts on an implicit "thread
6
+ * zero" that reuses the bare `qq:v2:<scope>:<id>` session id. The `/new`
7
+ * slash command atomically bumps this counter, which makes the next inbound
8
+ * message resolve to a fresh session id (e.g. `qq:v2:c2c:U1#n1`). Old
9
+ * threads remain intact on disk; only the current pointer advances.
10
+ *
11
+ * When `/new` carries a preset id, the override is stored keyed by the NEW
12
+ * session id, so the agent materializing that id (even after a restart,
13
+ * via create or resume) composes from the requested preset instead of the
14
+ * plugin-config default. A plain `/new` clears any override for the new id.
15
+ */
16
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
17
+ import { dirname } from 'node:path';
18
+ /** Accept both the v2 object shape and the legacy bare counter map. */
19
+ function normalizePayload(raw) {
20
+ const empty = { counters: {}, presets: {} };
21
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
22
+ return empty;
23
+ const record = raw;
24
+ if (!('counters' in record) && !('presets' in record)) {
25
+ // Legacy file: Record<targetKey, number>. Migrate in memory; the next
26
+ // flush persists the v2 shape.
27
+ const counters = {};
28
+ for (const [key, value] of Object.entries(record)) {
29
+ if (typeof value === 'number')
30
+ counters[key] = value;
31
+ }
32
+ return { counters, presets: {} };
33
+ }
34
+ const counters = {};
35
+ const rawCounters = record.counters;
36
+ if (rawCounters !== null && typeof rawCounters === 'object' && !Array.isArray(rawCounters)) {
37
+ for (const [key, value] of Object.entries(rawCounters)) {
38
+ if (typeof value === 'number')
39
+ counters[key] = value;
40
+ }
41
+ }
42
+ const presets = {};
43
+ const rawPresets = record.presets;
44
+ if (rawPresets !== null && typeof rawPresets === 'object' && !Array.isArray(rawPresets)) {
45
+ for (const [key, value] of Object.entries(rawPresets)) {
46
+ if (typeof value === 'string' && value.length > 0)
47
+ presets[key] = value;
48
+ }
49
+ }
50
+ return { counters, presets };
51
+ }
52
+ async function readJson(file) {
53
+ try {
54
+ return JSON.parse(await readFile(file, 'utf8'));
55
+ }
56
+ catch {
57
+ return undefined;
58
+ }
59
+ }
60
+ async function writeJsonAtomic(file, value) {
61
+ await mkdir(dirname(file), { recursive: true });
62
+ const tmp = `${file}.tmp`;
63
+ await writeFile(tmp, JSON.stringify(value), 'utf8');
64
+ await rename(tmp, file);
65
+ }
66
+ /** Stable target key: c2c:openid | group:openid | channel:channel_id. */
67
+ export function targetKey(target) {
68
+ if (target.kind === 'c2c')
69
+ return `c2c:${target.userId}`;
70
+ if (target.kind === 'group')
71
+ return `group:${target.groupId}`;
72
+ return `channel:${target.channelId}`;
73
+ }
74
+ export class ThreadStore {
75
+ file;
76
+ payload = { counters: {}, presets: {} };
77
+ writing = Promise.resolve();
78
+ constructor(file) {
79
+ this.file = file;
80
+ }
81
+ async load() {
82
+ this.payload = normalizePayload(await readJson(this.file));
83
+ }
84
+ /** Return the current thread counter (0 when never bumped). */
85
+ current(key) {
86
+ return this.payload.counters[key] ?? 0;
87
+ }
88
+ /** Atomically increment and return the new thread number. */
89
+ next(key) {
90
+ const next = (this.payload.counters[key] ?? 0) + 1;
91
+ this.payload.counters[key] = next;
92
+ this.flush();
93
+ return next;
94
+ }
95
+ /**
96
+ * The preset override recorded for one session id by `/new <preset>`.
97
+ * @returns the preset id, or `undefined` to use the plugin-config default.
98
+ */
99
+ presetFor(sessionId) {
100
+ return this.payload.presets[sessionId];
101
+ }
102
+ /**
103
+ * Record (or clear) the preset override for one session id. Persisted with
104
+ * the counters so a restart between `/new` and the next message keeps the
105
+ * requested composition.
106
+ */
107
+ setPreset(sessionId, preset) {
108
+ if (preset === undefined)
109
+ delete this.payload.presets[sessionId];
110
+ else
111
+ this.payload.presets[sessionId] = preset;
112
+ this.flush();
113
+ }
114
+ flush() {
115
+ this.writing = this.writing.then(() => writeJsonAtomic(this.file, this.payload), () => writeJsonAtomic(this.file, this.payload));
116
+ }
117
+ }
118
+ //# sourceMappingURL=threadstore.js.map