pygmalion 0.1.5 → 0.1.6

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.
@@ -1,282 +1,282 @@
1
- /**
2
- * 单 bot 管线工厂:把一个 bot 记录(data/bots/<id>.json)构建成完整接入管线。
3
- *
4
- * 由 BotManager 在启动/运行时调用:start() 内包一个 `ctx.effect`(活跃 fiber 内注册
5
- * `ctx.on('agent/disposed')` 与 dsh `webServer.register`,effect teardown 即注销),
6
- * stop() 就是该 effect 返回的 disposer。store 文件名按 botId 隔离(qq-<botId>-*.json)。
7
- */
8
- import { join } from 'node:path';
9
- import { QQApi } from './qqapi.js';
10
- import { QQGateway } from './gateway.js';
11
- import { RefIndexStore } from './refindex.js';
12
- import { AlwaysAllowStore, RouteStore } from './store.js';
13
- import { InboundPipeline, normalizeMessage, SESSION_PREFIX } from './inbound.js';
14
- import { OutboundPipeline } from './outbound.js';
15
- import { createSlashHandler } from './slash-commands.js';
16
- import { createSetupAgent, buildSessionDeps } from './setup-agent.js';
17
- import { ThreadStore } from './threads.js';
18
- import { resolveHttpApiMount, createHttpApiHandler } from './http-api.js';
19
- import * as personaLib from './persona.js';
20
-
21
- const ROUTE_TTL = 7 * 24 * 3600 * 1000; // 7 天无用户活动的会话路由修剪(修 D12)
22
-
23
- /** Strict, narrow validator for QQ INTERACTION_CREATE payloads. */
24
- function asInteractionButton(payload) {
25
- if (payload === null || typeof payload !== 'object')
26
- return undefined;
27
- const root = payload;
28
- if (typeof root.id !== 'string')
29
- return undefined;
30
- const data = root.data;
31
- if (data === null || typeof data !== 'object')
32
- return undefined;
33
- const resolved = data.resolved;
34
- if (resolved === null || typeof resolved !== 'object')
35
- return undefined;
36
- const buttonData = resolved.button_data;
37
- if (typeof buttonData !== 'string')
38
- return undefined;
39
- return { id: root.id, buttonData };
40
- }
41
-
42
- /**
43
- * @param deps 全局依赖(index.js apply 解析):
44
- * agents / sessionPersistence / workspaceRegistry / attachments / approval /
45
- * agentPresets / webServer(均来自 ctx)/ persona / log / storages(目录)
46
- * @param bot bot 记录(已过 BotConfig schema 校验)
47
- * @param ctx 宿主 context(注册/注销 agent 生命周期监听)
48
- * @returns {
49
- * bot, facade, // facade 供 heartbeat:{ botId, roleId, routes, threads, inbound, withinChatWindowMs, httpApiToken }
50
- * getStatus(), // 最近一次 gateway 连接状态
51
- * start(), stop() // 启动/停管线(幂等)
52
- * }
53
- */
54
- export function createBotPipeline(deps, bot, ctx) {
55
- const { log, persona, config } = deps;
56
- const ns = `qq-${bot.id}`;
57
- const api = new QQApi(bot, log);
58
- const refIndex = new RefIndexStore(join(deps.storages, `${ns}-refindex.jsonl`));
59
- const routes = new RouteStore(join(deps.storages, `${ns}-routes.json`));
60
- const alwaysAllow = new AlwaysAllowStore(join(deps.storages, `${ns}-always-allow.json`));
61
- const threads = new ThreadStore(join(deps.storages, `${ns}-threads.json`));
62
- const inbound = new InboundPipeline({
63
- config: bot,
64
- api,
65
- log,
66
- refIndex,
67
- routes,
68
- agents: deps.agents,
69
- sessionPersistence: deps.sessionPersistence,
70
- attachments: deps.attachments,
71
- approval: deps.approval,
72
- threads,
73
- persona,
74
- roleId: bot.roleId,
75
- botId: bot.id,
76
- botAppId: bot.qqAppId,
77
- });
78
- const outbound = new OutboundPipeline({
79
- config: bot,
80
- api,
81
- log,
82
- routes,
83
- alwaysAllow,
84
- inbound,
85
- persona,
86
- botId: bot.id,
87
- isDirector: (sessionId) => personaLib.isRoleDirectorSession(bot.roleId, sessionId),
88
- });
89
- outbound.bind(ctx);
90
- const onSlashCommand = createSlashHandler({
91
- log, alwaysAllow, threads, agents: deps.agents, approval: deps.approval,
92
- outbound, agentPresets: deps.agentPresets, botId: bot.id,
93
- });
94
- const presetOverride = (typeof bot.agentPreset === 'string' && bot.agentPreset.length > 0)
95
- ? bot.agentPreset
96
- : 'standard';
97
- const setupDeps = {
98
- log,
99
- api,
100
- routes,
101
- outbound,
102
- workspaceRegistry: deps.workspaceRegistry,
103
- persona,
104
- roleId: bot.roleId,
105
- defaultCwd: process.cwd(),
106
- resolvePreset: deps.agentPresets === undefined
107
- ? undefined
108
- : async (sessionId) => {
109
- let presetId = presetOverride;
110
- const openid = persona.openidFromSessionId(sessionId);
111
- if (openid !== undefined) {
112
- try {
113
- const role = await persona.loadRole(bot.roleId);
114
- if (role && role.binding.openid === openid && role.persona?.name) {
115
- presetId = 'pygmalion-director';
116
- }
117
- }
118
- catch (error) {
119
- log.warn('pygmalion loadRole failed for %s: %o', openid, error);
120
- }
121
- }
122
- return deps.agentPresets.resolve(threads.presetFor(sessionId) ?? presetId);
123
- },
124
- agentPresets: deps.agentPresets,
125
- httpApiToken: bot.httpApiToken,
126
- httpApiPath: bot.httpApiPath,
127
- director: deps.director,
128
- };
129
- const setupAgent = createSetupAgent(setupDeps);
130
- // 已存在 agent(dsh 核心冷恢复/重组合创建,未走 pygmalion setup)时,ensureAgent
131
- // 命中既有分支不会执行 setup → standing 导演工具缺会话上下文。此回调只补登记
132
- // sessionDeps(不重挂 preset——mount 对已绑定 agent 会 throw),幂等可重复调用。
133
- const registerSessionContext = (sessionId) => {
134
- const directorSvc = deps.director?.get?.('pygmalion.director');
135
- if (directorSvc === undefined || typeof directorSvc.registerSession !== 'function') return;
136
- directorSvc.registerSession(sessionId, buildSessionDeps(setupDeps, sessionId));
137
- };
138
- // 冷恢复兜底(修 D19):重启后 dsh 核心重建既有 agent 不触发 setup/ensureAgent(无入站
139
- // 消息),sessionDeps 永不登记。向宿主登记惰性构造器,depsFor 未命中时按 sessionId
140
- // 现场构造并缓存(buildSessionDeps 除 target 惰性闭包外全是本 bot 常量,任意会话可构造)。
141
- const directorSvc = deps.director?.get?.('pygmalion.director');
142
- if (directorSvc !== undefined && typeof directorSvc.registerSessionBuilder === 'function') {
143
- directorSvc.registerSessionBuilder(bot.id, (sessionId) => buildSessionDeps(setupDeps, sessionId));
144
- }
145
- inbound.attachHooks({ onSlashCommand, setupAgent, registerSessionContext });
146
-
147
- // 可选 HTTP 推送/唤醒 API:按 botId 自动生成 path,token 由 BotManager 生成。
148
- // 宿主无 webServer 时跳过挂载(status 标 unavailable),不 throw。
149
- let httpApiMount;
150
- let httpApiUnavailable = false;
151
- if (bot.httpApiToken) {
152
- httpApiMount = resolveHttpApiMount({ path: bot.httpApiPath, token: bot.httpApiToken });
153
- if (deps.webServer === undefined) {
154
- httpApiMount = undefined;
155
- httpApiUnavailable = true;
156
- log.warn('pygmalion: bot %s 配置了 httpApiToken,但宿主无 webServer(该 API 仅在 dsh web 等 Web 组合下可用),已跳过挂载', bot.id);
157
- }
158
- }
159
-
160
- let status = { state: 'stopped', detail: '' };
161
- const setStatus = (state, detail = '') => { status = { state, detail }; };
162
-
163
- const gateway = new QQGateway(bot, api, {
164
- onMessage: (payload, eventType) => {
165
- const message = normalizeMessage(payload, eventType);
166
- if (message === undefined)
167
- return;
168
- void inbound.handle(message).catch((error) => {
169
- log.error('inbound handling failed (%s): %o', bot.id, error);
170
- });
171
- },
172
- onInteraction: (payload) => {
173
- const interaction = asInteractionButton(payload);
174
- if (interaction === undefined)
175
- return;
176
- if (outbound.handleApprovalCallback(interaction.buttonData) !== undefined) {
177
- void api.ackInteraction(interaction.id).catch((error) => {
178
- log.warn('interaction ack failed: %o', error);
179
- });
180
- }
181
- },
182
- onReady: () => { log.info('QQ gateway ready (bot=%s appid=%s)', bot.id, api.appId()); },
183
- onStatus: setStatus,
184
- }, log, join(deps.storages, `${ns}-gateway-session.json`));
185
-
186
- const facade = {
187
- botId: bot.id,
188
- roleId: bot.roleId,
189
- routes,
190
- threads,
191
- inbound,
192
- withinChatWindowMs: bot.withinChatWindowMs,
193
- httpApiToken: bot.httpApiToken,
194
- };
195
-
196
- let dispose = null;
197
- let started = false;
198
- let stopping = false;
199
-
200
- function start() {
201
- if (started || stopping)
202
- return;
203
- started = true;
204
- // ctx.effect 返回 disposer;effect 运行时 fiber 活跃,ctx.on / webServer.register 均合法。
205
- dispose = ctx.effect(() => {
206
- const stops = [];
207
- void refIndex.init();
208
- void routes.load().then(() => {
209
- try {
210
- routes.prune(ROUTE_TTL);
211
- alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
212
- }
213
- catch { /* ignore */ }
214
- });
215
- void alwaysAllow.load();
216
- void threads.load();
217
- void gateway.start();
218
- const pruneTimer = setInterval(() => {
219
- try {
220
- routes.prune(ROUTE_TTL);
221
- alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
222
- }
223
- catch { /* ignore */ }
224
- }, 6 * 3600 * 1000);
225
- pruneTimer.unref?.();
226
- stops.push(() => clearInterval(pruneTimer));
227
- const onDisposed = ctx.on('agent/disposed', ({ agent }) => {
228
- if (!agent.id.startsWith(`${SESSION_PREFIX}:${bot.id}:`))
229
- return;
230
- deps.director?.get?.('pygmalion.director')?.unregisterSession?.(agent.id);
231
- void outbound.closeStream(agent.id);
232
- inbound.onAgentDisposed(agent.id);
233
- });
234
- stops.push(() => { if (typeof onDisposed === 'function') onDisposed(); });
235
- if (httpApiMount !== undefined && deps.webServer !== undefined) {
236
- stops.push(deps.webServer.register({
237
- kind: 'prefix',
238
- path: httpApiMount.path,
239
- handler: createHttpApiHandler({
240
- mountPath: httpApiMount.path,
241
- token: httpApiMount.token,
242
- config: bot,
243
- log,
244
- api,
245
- routes,
246
- threads,
247
- ensureAgent: (sessionId) => inbound.ensureAgent(sessionId),
248
- persona,
249
- botId: bot.id,
250
- roleId: bot.roleId,
251
- activityAt: (sessionId) => inbound.userActivityAt(sessionId),
252
- withinChatWindowMs: bot.withinChatWindowMs,
253
- scriptWakeMinIntervalMs: config?.heartbeat?.scriptWakeMinIntervalMs ?? 600000,
254
- }),
255
- }));
256
- log.info('pygmalion: httpApi mounted for bot %s at %s', bot.id, httpApiMount.path);
257
- }
258
- return () => {
259
- stops.forEach((fn) => { try { fn(); } catch { /* ignore */ } });
260
- outbound.disposeAllStreams();
261
- inbound.dispose();
262
- gateway.dispose();
263
- api.dispose();
264
- void outbound.dispose();
265
- started = false;
266
- dispose = null;
267
- setStatus('stopped');
268
- };
269
- }, `pygmalion.bot:${bot.id}()`);
270
- return dispose;
271
- }
272
-
273
- function stop() {
274
- stopping = true;
275
- const d = dispose;
276
- dispose = null;
277
- try { if (typeof d === 'function') d(); } catch { /* ignore */ }
278
- stopping = false;
279
- }
280
-
281
- return { bot, facade, getStatus: () => status, start, stop, httpApiUnavailable };
282
- }
1
+ /**
2
+ * 单 bot 管线工厂:把一个 bot 记录(data/bots/<id>.json)构建成完整接入管线。
3
+ *
4
+ * 由 BotManager 在启动/运行时调用:start() 内包一个 `ctx.effect`(活跃 fiber 内注册
5
+ * `ctx.on('agent/disposed')` 与 dsh `webServer.register`,effect teardown 即注销),
6
+ * stop() 就是该 effect 返回的 disposer。store 文件名按 botId 隔离(qq-<botId>-*.json)。
7
+ */
8
+ import { join } from 'node:path';
9
+ import { QQApi } from './qqapi.js';
10
+ import { QQGateway } from './gateway.js';
11
+ import { RefIndexStore } from './refindex.js';
12
+ import { AlwaysAllowStore, RouteStore } from './store.js';
13
+ import { InboundPipeline, normalizeMessage, SESSION_PREFIX } from './inbound.js';
14
+ import { OutboundPipeline } from './outbound.js';
15
+ import { createSlashHandler } from './slash-commands.js';
16
+ import { createSetupAgent, buildSessionDeps } from './setup-agent.js';
17
+ import { ThreadStore } from './threads.js';
18
+ import { resolveHttpApiMount, createHttpApiHandler } from './http-api.js';
19
+ import * as personaLib from './persona.js';
20
+
21
+ const ROUTE_TTL = 7 * 24 * 3600 * 1000; // 7 天无用户活动的会话路由修剪(修 D12)
22
+
23
+ /** Strict, narrow validator for QQ INTERACTION_CREATE payloads. */
24
+ function asInteractionButton(payload) {
25
+ if (payload === null || typeof payload !== 'object')
26
+ return undefined;
27
+ const root = payload;
28
+ if (typeof root.id !== 'string')
29
+ return undefined;
30
+ const data = root.data;
31
+ if (data === null || typeof data !== 'object')
32
+ return undefined;
33
+ const resolved = data.resolved;
34
+ if (resolved === null || typeof resolved !== 'object')
35
+ return undefined;
36
+ const buttonData = resolved.button_data;
37
+ if (typeof buttonData !== 'string')
38
+ return undefined;
39
+ return { id: root.id, buttonData };
40
+ }
41
+
42
+ /**
43
+ * @param deps 全局依赖(index.js apply 解析):
44
+ * agents / sessionPersistence / workspaceRegistry / attachments / approval /
45
+ * agentPresets / webServer(均来自 ctx)/ persona / log / storages(目录)
46
+ * @param bot bot 记录(已过 BotConfig schema 校验)
47
+ * @param ctx 宿主 context(注册/注销 agent 生命周期监听)
48
+ * @returns {
49
+ * bot, facade, // facade 供 heartbeat:{ botId, roleId, routes, threads, inbound, withinChatWindowMs, httpApiToken }
50
+ * getStatus(), // 最近一次 gateway 连接状态
51
+ * start(), stop() // 启动/停管线(幂等)
52
+ * }
53
+ */
54
+ export function createBotPipeline(deps, bot, ctx) {
55
+ const { log, persona, config } = deps;
56
+ const ns = `qq-${bot.id}`;
57
+ const api = new QQApi(bot, log);
58
+ const refIndex = new RefIndexStore(join(deps.storages, `${ns}-refindex.jsonl`));
59
+ const routes = new RouteStore(join(deps.storages, `${ns}-routes.json`));
60
+ const alwaysAllow = new AlwaysAllowStore(join(deps.storages, `${ns}-always-allow.json`));
61
+ const threads = new ThreadStore(join(deps.storages, `${ns}-threads.json`));
62
+ const inbound = new InboundPipeline({
63
+ config: bot,
64
+ api,
65
+ log,
66
+ refIndex,
67
+ routes,
68
+ agents: deps.agents,
69
+ sessionPersistence: deps.sessionPersistence,
70
+ attachments: deps.attachments,
71
+ approval: deps.approval,
72
+ threads,
73
+ persona,
74
+ roleId: bot.roleId,
75
+ botId: bot.id,
76
+ botAppId: bot.qqAppId,
77
+ });
78
+ const outbound = new OutboundPipeline({
79
+ config: bot,
80
+ api,
81
+ log,
82
+ routes,
83
+ alwaysAllow,
84
+ inbound,
85
+ persona,
86
+ botId: bot.id,
87
+ isDirector: (sessionId) => personaLib.isRoleDirectorSession(bot.roleId, sessionId),
88
+ });
89
+ outbound.bind(ctx);
90
+ const onSlashCommand = createSlashHandler({
91
+ log, alwaysAllow, threads, agents: deps.agents, approval: deps.approval,
92
+ outbound, agentPresets: deps.agentPresets, botId: bot.id,
93
+ });
94
+ const presetOverride = (typeof bot.agentPreset === 'string' && bot.agentPreset.length > 0)
95
+ ? bot.agentPreset
96
+ : 'standard';
97
+ const setupDeps = {
98
+ log,
99
+ api,
100
+ routes,
101
+ outbound,
102
+ workspaceRegistry: deps.workspaceRegistry,
103
+ persona,
104
+ roleId: bot.roleId,
105
+ defaultCwd: process.cwd(),
106
+ resolvePreset: deps.agentPresets === undefined
107
+ ? undefined
108
+ : async (sessionId) => {
109
+ let presetId = presetOverride;
110
+ const openid = persona.openidFromSessionId(sessionId);
111
+ if (openid !== undefined) {
112
+ try {
113
+ const role = await persona.loadRole(bot.roleId);
114
+ if (role && role.binding.openid === openid && role.persona?.name) {
115
+ presetId = 'pygmalion-director';
116
+ }
117
+ }
118
+ catch (error) {
119
+ log.warn('pygmalion loadRole failed for %s: %o', openid, error);
120
+ }
121
+ }
122
+ return deps.agentPresets.resolve(threads.presetFor(sessionId) ?? presetId);
123
+ },
124
+ agentPresets: deps.agentPresets,
125
+ httpApiToken: bot.httpApiToken,
126
+ httpApiPath: bot.httpApiPath,
127
+ director: deps.director,
128
+ };
129
+ const setupAgent = createSetupAgent(setupDeps);
130
+ // 已存在 agent(dsh 核心冷恢复/重组合创建,未走 pygmalion setup)时,ensureAgent
131
+ // 命中既有分支不会执行 setup → standing 导演工具缺会话上下文。此回调只补登记
132
+ // sessionDeps(不重挂 preset——mount 对已绑定 agent 会 throw),幂等可重复调用。
133
+ const registerSessionContext = (sessionId) => {
134
+ const directorSvc = deps.director?.get?.('pygmalion.director');
135
+ if (directorSvc === undefined || typeof directorSvc.registerSession !== 'function') return;
136
+ directorSvc.registerSession(sessionId, buildSessionDeps(setupDeps, sessionId));
137
+ };
138
+ // 冷恢复兜底(修 D19):重启后 dsh 核心重建既有 agent 不触发 setup/ensureAgent(无入站
139
+ // 消息),sessionDeps 永不登记。向宿主登记惰性构造器,depsFor 未命中时按 sessionId
140
+ // 现场构造并缓存(buildSessionDeps 除 target 惰性闭包外全是本 bot 常量,任意会话可构造)。
141
+ const directorSvc = deps.director?.get?.('pygmalion.director');
142
+ if (directorSvc !== undefined && typeof directorSvc.registerSessionBuilder === 'function') {
143
+ directorSvc.registerSessionBuilder(bot.id, (sessionId) => buildSessionDeps(setupDeps, sessionId));
144
+ }
145
+ inbound.attachHooks({ onSlashCommand, setupAgent, registerSessionContext });
146
+
147
+ // 可选 HTTP 推送/唤醒 API:按 botId 自动生成 path,token 由 BotManager 生成。
148
+ // 宿主无 webServer 时跳过挂载(status 标 unavailable),不 throw。
149
+ let httpApiMount;
150
+ let httpApiUnavailable = false;
151
+ if (bot.httpApiToken) {
152
+ httpApiMount = resolveHttpApiMount({ path: bot.httpApiPath, token: bot.httpApiToken });
153
+ if (deps.webServer === undefined) {
154
+ httpApiMount = undefined;
155
+ httpApiUnavailable = true;
156
+ log.warn('pygmalion: bot %s 配置了 httpApiToken,但宿主无 webServer(该 API 仅在 dsh web 等 Web 组合下可用),已跳过挂载', bot.id);
157
+ }
158
+ }
159
+
160
+ let status = { state: 'stopped', detail: '' };
161
+ const setStatus = (state, detail = '') => { status = { state, detail }; };
162
+
163
+ const gateway = new QQGateway(bot, api, {
164
+ onMessage: (payload, eventType) => {
165
+ const message = normalizeMessage(payload, eventType);
166
+ if (message === undefined)
167
+ return;
168
+ void inbound.handle(message).catch((error) => {
169
+ log.error('inbound handling failed (%s): %o', bot.id, error);
170
+ });
171
+ },
172
+ onInteraction: (payload) => {
173
+ const interaction = asInteractionButton(payload);
174
+ if (interaction === undefined)
175
+ return;
176
+ if (outbound.handleApprovalCallback(interaction.buttonData) !== undefined) {
177
+ void api.ackInteraction(interaction.id).catch((error) => {
178
+ log.warn('interaction ack failed: %o', error);
179
+ });
180
+ }
181
+ },
182
+ onReady: () => { log.info('QQ gateway ready (bot=%s appid=%s)', bot.id, api.appId()); },
183
+ onStatus: setStatus,
184
+ }, log, join(deps.storages, `${ns}-gateway-session.json`));
185
+
186
+ const facade = {
187
+ botId: bot.id,
188
+ roleId: bot.roleId,
189
+ routes,
190
+ threads,
191
+ inbound,
192
+ withinChatWindowMs: bot.withinChatWindowMs,
193
+ httpApiToken: bot.httpApiToken,
194
+ };
195
+
196
+ let dispose = null;
197
+ let started = false;
198
+ let stopping = false;
199
+
200
+ function start() {
201
+ if (started || stopping)
202
+ return;
203
+ started = true;
204
+ // ctx.effect 返回 disposer;effect 运行时 fiber 活跃,ctx.on / webServer.register 均合法。
205
+ dispose = ctx.effect(() => {
206
+ const stops = [];
207
+ void refIndex.init();
208
+ void routes.load().then(() => {
209
+ try {
210
+ routes.prune(ROUTE_TTL);
211
+ alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
212
+ }
213
+ catch { /* ignore */ }
214
+ });
215
+ void alwaysAllow.load();
216
+ void threads.load();
217
+ void gateway.start();
218
+ const pruneTimer = setInterval(() => {
219
+ try {
220
+ routes.prune(ROUTE_TTL);
221
+ alwaysAllow.prune(routes.entries().map((e) => e.sessionId));
222
+ }
223
+ catch { /* ignore */ }
224
+ }, 6 * 3600 * 1000);
225
+ pruneTimer.unref?.();
226
+ stops.push(() => clearInterval(pruneTimer));
227
+ const onDisposed = ctx.on('agent/disposed', ({ agent }) => {
228
+ if (!agent.id.startsWith(`${SESSION_PREFIX}:${bot.id}:`))
229
+ return;
230
+ deps.director?.get?.('pygmalion.director')?.unregisterSession?.(agent.id);
231
+ void outbound.closeStream(agent.id);
232
+ inbound.onAgentDisposed(agent.id);
233
+ });
234
+ stops.push(() => { if (typeof onDisposed === 'function') onDisposed(); });
235
+ if (httpApiMount !== undefined && deps.webServer !== undefined) {
236
+ stops.push(deps.webServer.register({
237
+ kind: 'prefix',
238
+ path: httpApiMount.path,
239
+ handler: createHttpApiHandler({
240
+ mountPath: httpApiMount.path,
241
+ token: httpApiMount.token,
242
+ config: bot,
243
+ log,
244
+ api,
245
+ routes,
246
+ threads,
247
+ ensureAgent: (sessionId) => inbound.ensureAgent(sessionId),
248
+ persona,
249
+ botId: bot.id,
250
+ roleId: bot.roleId,
251
+ activityAt: (sessionId) => inbound.userActivityAt(sessionId),
252
+ withinChatWindowMs: bot.withinChatWindowMs,
253
+ scriptWakeMinIntervalMs: config?.heartbeat?.scriptWakeMinIntervalMs ?? 600000,
254
+ }),
255
+ }));
256
+ log.info('pygmalion: httpApi mounted for bot %s at %s', bot.id, httpApiMount.path);
257
+ }
258
+ return () => {
259
+ stops.forEach((fn) => { try { fn(); } catch { /* ignore */ } });
260
+ outbound.disposeAllStreams();
261
+ inbound.dispose();
262
+ gateway.dispose();
263
+ api.dispose();
264
+ void outbound.dispose();
265
+ started = false;
266
+ dispose = null;
267
+ setStatus('stopped');
268
+ };
269
+ }, `pygmalion.bot:${bot.id}()`);
270
+ return dispose;
271
+ }
272
+
273
+ function stop() {
274
+ stopping = true;
275
+ const d = dispose;
276
+ dispose = null;
277
+ try { if (typeof d === 'function') d(); } catch { /* ignore */ }
278
+ stopping = false;
279
+ }
280
+
281
+ return { bot, facade, getStatus: () => status, start, stop, httpApiUnavailable };
282
+ }